From 221407e25fbb61c0523fdb58b5bbf62cdcd0e571 Mon Sep 17 00:00:00 2001 From: tedin7 Date: Tue, 24 Nov 2026 19:57:22 +0100 Subject: [PATCH 1/2] startup: clear depth and stencil views (command-list slot 51) Refs #870. --- CMakeLists.txt | 21 ++ docs/experiments.md | 12 + docs/startup-runtime.md | 33 +++ src/startup_stubs/d3d12_xs_device.cpp | 71 ++++++ src/startup_stubs/list_clear_depth.h | 77 +++++++ tests/list_clear_depth_check.cpp | 101 ++++++++ tests/startup_depth_clear.cpp | 320 ++++++++++++++++++++++++++ 7 files changed, 635 insertions(+) create mode 100644 src/startup_stubs/list_clear_depth.h create mode 100644 tests/list_clear_depth_check.cpp create mode 100644 tests/startup_depth_clear.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index d667940c03..4490ebd6c6 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1225,6 +1225,27 @@ foreach(mutation IN ITEMS overflow typeless samples) set_tests_properties(startup_list_copy_validation_${mutation}_control PROPERTIES WILL_FAIL TRUE) endforeach() +# ClearDepthStencilView (list slot 51) on a depth view, read back through both planes. +add_executable(startup_depth_clear tests/startup_depth_clear.cpp) +target_compile_features(startup_depth_clear PRIVATE cxx_std_17) +target_link_libraries(startup_depth_clear PRIVATE d3d12_xs_shim d3d12 dxgi) +foreach(backend IN ITEMS warp hardware) + add_test(NAME startup_depth_clear_${backend} COMMAND startup_depth_clear ${backend}) + set_tests_properties(startup_depth_clear_${backend} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 + ENVIRONMENT "X2W_D3D12_PERMISSIVE=1;X2W_D3D12_LIST_NOOP=1;X2W_D3D12_RENDER=1;X2W_D3D12_DEBUG=1") +endforeach() + +# Which ClearDepthStencilView calls are forwarded (src/startup_stubs/list_clear_depth.h), without a device. The mutated +# runs are the negative controls. +add_executable(list_clear_depth_check tests/list_clear_depth_check.cpp) +target_include_directories(list_clear_depth_check PRIVATE src) +target_compile_features(list_clear_depth_check PRIVATE cxx_std_17) +add_test(NAME list_clear_depth COMMAND list_clear_depth_check) +foreach(mutation IN ITEMS keep-stencil allow-read-only) + add_test(NAME list_clear_depth_${mutation}_control COMMAND list_clear_depth_check --mutate ${mutation}) + set_tests_properties(list_clear_depth_${mutation}_control PROPERTIES WILL_FAIL TRUE) +endforeach() + add_executable(startup_nv12_draw tests/startup_nv12_draw.cpp tests/desktop_gpu.cpp) target_compile_features(startup_nv12_draw PRIVATE cxx_std_17) target_include_directories(startup_nv12_draw PRIVATE src) diff --git a/docs/experiments.md b/docs/experiments.md index 79707139dd..3a053d4169 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -13261,6 +13261,18 @@ The [MASM fixture](../tests/cpu/switch_fsgsbase_rdpid.asm) exports 9 translated Not covered by this experiment: host segment-base writes (`wrfsbase`/`wrgsbase`, which require an explicit isolation/restoration profile), cross-thread `FS_BASE`/`GS_BASE` migration, and title CPU code execution. +## Depth stencil clears (command-list slot 51) + +`ClearDepthStencilView` had no handler; the title's call reached the `x2w-noop` stand-in and the depth buffer was never +cleared on the desktop list. Slot 51 is derived from the desktop order plus the console shift (47 + 4), not seen in a +title log. The stand-in forwards a clear whose depth is in [0, 1], whose planes the view can write and whose rectangles +can be read, and counts the refusals. See [Depth stencil clears](startup-runtime.md#depth-stencil-clears). + +```powershell +cmake --build --preset dev --target startup_depth_clear list_clear_depth_check +ctest --preset dev --no-tests=error -R "^(startup_depth_clear_(warp|hardware)|list_clear_depth.*)$" -V +``` + ## Render target binds with a single descriptor range `OMSetRenderTargets` (command-list slot 50) with `RTsSingleHandleToDescriptorRange` true used to be dropped without a diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index 0fdd338bab..50fc704488 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -444,6 +444,39 @@ These slots have not been seen in a title log yet. `CopyTextureRegion` (16) and `ctest -R '^startup_list_copy_validation'` runs the pure checks on any host; `startup_list_copy_{warp,hardware}` copies, resolves and reads back through the `x2w_d3d12_list_copy_stats` export. +## Depth stencil clears + +Command-list slot 51 is `ClearDepthStencilView(view, flags, depth, stencil, rect count, rects)`. The slot is DERIVED, not +seen in a title log: it is desktop slot 47 plus four, between slots 50 (`OMSetRenderTargets`) and 52 +(`ClearRenderTargetView`), which are both observed at desktop plus four. Before this change slot 51 fell through to the +`x2w-noop` stand-in, so a depth buffer that the title cleared was never cleared on the desktop list and a depth test +ran against whatever the new texture held. + +The depth value is the fourth argument, so a real call passes it in `xmm3`. The generic noop entry takes integer +registers only and would lose it, so with `X2W_D3D12_LIST_NOOP=1` and render mode the list table points slot 51 at the +handler itself. The handler keeps the per-slot call counts the generic entry would have kept, but a frame trace +and a capture do not see it. + +The handler reads the view through its shadow record as slot 50 does, moves the resource to `DEPTH_WRITE` and calls the +desktop `ClearDepthStencilView`. The decision is in `src/startup_stubs/list_clear_depth.h`: unknown flag bits and +the stencil bit of a format without a stencil plane are dropped; no flag left means nothing to clear (not counted); a +cleared depth that is not a number in [0, 1], a cleared plane that the view marks read-only, or rectangles that cannot be +read are refused, because the desktop list would report an error for them. A view that holds nothing adds to the +unresolved count of `x2w_d3d12_render_target_stats`; the other refusals add to the second counter of +`x2w_d3d12_depth_clear_stats(forwarded, refused)`. Each refusal logs one line (the first six); the first four calls log +their arguments. A forwarded clear also adds to `clears` in the `x2w-render totals` line. A closed list ignores the call. + +One limit: a resource that an earlier bind in the same recording holds as `DEPTH_READ` (a read-only view) is moved to +`DEPTH_WRITE` by a clear through another view of it, and a later draw with the read-only view still bound would then +find the wrong state. No title call shows that pattern yet. + +`list_clear_depth_check` runs the decision without a device; its two mutated runs (a stencil clear kept for a format +without stencil, a read-only plane cleared) must fail. `startup_depth_clear_{warp,hardware}` clears a 4x4 +`D32_FLOAT_S8X24_UINT` texture through the stand-in and reads both planes back: both planes, depth only (the stencil +argument ignored), stencil only (the depth argument ignored), one rectangle, then the refusals and the closed list. It +does not draw. Before the first clear the planes are read once, and the check fails if they already hold what the first +clear writes. + ## Composite provenance fixture Issue #1628 asks whether a uniform colour left in a composite's destination came from the composite or was diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index 133458e612..2731763235 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -47,6 +47,7 @@ #include "console_plane_size.h" #include "descriptor_heap_type.h" #include "small_texture_4k.h" +#include "list_clear_depth.h" #include "null_binding_cause.h" #include "null_texture_view.h" #include "packed_target_format.h" @@ -1175,6 +1176,8 @@ x2w_startup::DrawReadbacks& draw_dumps() LONG render_resets, render_closes, render_clears, render_executes, render_reset_failures; // OMSetRenderTargets calls that bound targets, and render target / depth handles that resolved to no view. LONG render_target_binds, render_target_unresolved; +// ClearDepthStencilView calls forwarded to the desktop list, and calls refused by rule (not counting an unresolved view). +LONG render_depth_clears, render_depth_clears_refused; // A console recording survives its allocator's Reset; a desktop one is discarded with it, and // resetting an allocator whose lists the GPU still runs is invalid. Each title allocator therefore @@ -1358,6 +1361,14 @@ extern "C" __declspec(dllexport) void x2w_d3d12_render_target_stats(unsigned* bi if (unresolved) *unresolved = static_cast(InterlockedCompareExchange(&render_target_unresolved, 0, 0)); } +// Fixtures: ClearDepthStencilView calls forwarded, and calls refused for a read-only plane, a depth outside [0, 1] or +// unreadable rectangles. A view that holds nothing is counted by x2w_d3d12_render_target_stats instead. +extern "C" __declspec(dllexport) void x2w_d3d12_depth_clear_stats(unsigned* forwarded, unsigned* refused) +{ + if (forwarded) *forwarded = static_cast(InterlockedCompareExchange(&render_depth_clears, 0, 0)); + if (refused) *refused = static_cast(InterlockedCompareExchange(&render_depth_clears_refused, 0, 0)); +} + // Fixtures: the number of desktop allocators a title allocator stands for (0 if it has none yet). extern "C" __declspec(dllexport) unsigned x2w_d3d12_allocator_pool_size(void* allocator) { @@ -2558,6 +2569,64 @@ void __stdcall list_clear_target(Wrapper* self, u64 handle, const float* colour, red_producers().after(self, red_sample); InterlockedIncrement(&render_clears); } +static_assert(x2w_clear_depth::clear_depth == D3D12_CLEAR_FLAG_DEPTH && x2w_clear_depth::clear_stencil == D3D12_CLEAR_FLAG_STENCIL, + "the clear flag bits of list_clear_depth.h are the SDK values"); +// List slot 51 (desktop 47 + 4), ClearDepthStencilView(view, flags, depth, stencil, rect count, rects). DERIVED, not +// seen in a title log: slots 50 and 52 around it are observed at desktop + 4. The depth value is the fourth argument, +// so it arrives in xmm3 and the generic noop_slot entry would lose it; the table points at this function directly +// (see where the list table is filled) and it keeps the per-slot counts noop_slot would have kept. +// The view is read from its shadow record, as OMSetRenderTargets does. Desktop resources rest in COMMON, so the +// resource is moved to DEPTH_WRITE first. A view that holds nothing is counted with the unresolved handles of +// OMSetRenderTargets; a clear the desktop list would reject (read-only plane, depth outside [0, 1], unreadable +// rectangles) is refused and counted in x2w_d3d12_depth_clear_stats. See startup_stubs/list_clear_depth.h. +void __stdcall list_clear_depth(Wrapper* self, u64 handle, UINT flags, float depth, UINT stencil, UINT rect_count, + const D3D12_RECT* rects) +{ + InterlockedIncrement64(&list_slot_calls[51]); + InterlockedIncrement64(&list_slot_census[51]); + InterlockedIncrement(&draw_calls_seen); + auto* list = recording(self); + if (!list) return; + const u64 desktop = desktop_cpu_handle(handle); + const ResolvedView view = desktop ? resolve_view(desktop, 21) : ResolvedView{}; + ID3D12Resource* target = view.resource; + static LONG logged; + if (first_calls(logged, 4)) + log("x2w-render ClearDepthStencilView view=0x%llx target=%p flags=0x%x depth=%.3f stencil=0x%x rects=%u", handle, + static_cast(target), flags, depth, stencil & 0xffu, rect_count); + if (!target) { + InterlockedIncrement(&render_target_unresolved); + static LONG refused; + if (first_calls(refused, 6)) + log("x2w-d3d12 ClearDepthStencilView skipped: view 0x%llx is %s", handle, + view.wrong_kind ? "not a depth stencil view" + : view.skipped ? "a skipped depth stencil view" : "not a known depth stencil view"); + return; + } + x2w_clear_depth::Request request; + request.flags = flags; + request.depth = depth; + request.format_has_stencil = format_has_stencil(view_format_of(desktop, target)); + request.depth_read_only = (view.dsv_flags & D3D12_DSV_FLAG_READ_ONLY_DEPTH) != 0; + request.stencil_read_only = (view.dsv_flags & D3D12_DSV_FLAG_READ_ONLY_STENCIL) != 0; + request.rect_count = rect_count; + request.rects_readable = !rect_count || (rects && x2w_local::readable(rects, std::size_t{rect_count} * sizeof(D3D12_RECT))); + const x2w_clear_depth::Plan plan = x2w_clear_depth::plan(request); + if (plan.verdict == x2w_clear_depth::Verdict::nothing_to_clear) return; + if (plan.verdict != x2w_clear_depth::Verdict::forward) { + InterlockedIncrement(&render_depth_clears_refused); + static LONG refused_by_rule; + if (first_calls(refused_by_rule, 6)) + log("x2w-d3d12 ClearDepthStencilView refused: %s (flags 0x%x, depth %.3f)", x2w_clear_depth::reason(plan.verdict), flags, depth); + return; + } + require_state(self, target, D3D12_RESOURCE_STATE_DEPTH_WRITE); + list->ClearDepthStencilView(D3D12_CPU_DESCRIPTOR_HANDLE{static_cast(desktop)}, + static_cast(plan.flags), depth, static_cast(stencil), plan.rect_count, + plan.rect_count ? rects : nullptr); + InterlockedIncrement(&render_depth_clears); + InterlockedIncrement(&render_clears); +} // List slot 50 (desktop 46 + 4), OMSetRenderTargets(count, handles, single range, depth). // With single_range the title passes the first handle only and the rest follow it at the title's own // descriptor stride (also for one target). A descriptor of the wrong kind, a handle that holds no view, a @@ -4255,6 +4324,8 @@ void build_tables() list_typed[30] = reinterpret_cast(&list_resolve_query); } } + // Slot 51 takes a float (xmm3), which the generic entry cannot pass on: the table calls the handler itself. + if (render_mode() && list_noop()) tables[list_kind][51] = reinterpret_cast(&list_clear_depth); tables[device_kind][16] = reinterpret_cast(&device_create_root_signature); // Queue: not the desktop order (slot 18 is GetTimestampFrequency, desktop 16). Slots are diff --git a/src/startup_stubs/list_clear_depth.h b/src/startup_stubs/list_clear_depth.h new file mode 100644 index 0000000000..2cf0d9e508 --- /dev/null +++ b/src/startup_stubs/list_clear_depth.h @@ -0,0 +1,77 @@ +// What a title's ClearDepthStencilView (command-list slot 51, desktop 47 + 4) may forward to the desktop list. +// Plain C++ with no Windows types, so the decision is checked without a device (tests/list_clear_depth_check.cpp). +// +// The desktop call is only valid for a plane the view can write, a depth value in [0, 1] when depth is cleared, and +// a rectangle array that can be read. Anything else would make the debug layer report an error or remove the +// device, so it is refused here and counted by the caller. +#pragma once + +#include + +namespace x2w_clear_depth { + +// D3D12_CLEAR_FLAG_DEPTH and D3D12_CLEAR_FLAG_STENCIL; the caller checks the values against the SDK. +constexpr unsigned clear_depth = 1; +constexpr unsigned clear_stencil = 2; + +enum class Verdict { + forward, // call the desktop list with Plan::flags and Plan::rect_count + nothing_to_clear, // no plane left to clear after normalising: not an error, not forwarded + bad_depth, // depth is cleared and the value is not a number in [0, 1] + read_only_plane, // a plane to clear is read-only in this view + unreadable_rects, // rects were announced but cannot be read +}; + +struct Request { + unsigned flags = 0; + float depth = 0.0f; + bool format_has_stencil = false; + bool depth_read_only = false; + bool stencil_read_only = false; + unsigned rect_count = 0; + bool rects_readable = true; // meaningful only when rect_count is not zero +}; + +struct Plan { + Verdict verdict = Verdict::nothing_to_clear; + unsigned flags = 0; + unsigned rect_count = 0; +}; + +inline Plan plan(const Request& request) +{ + Plan out; + unsigned flags = request.flags & (clear_depth | clear_stencil); + if (!request.format_has_stencil) flags &= ~clear_stencil; + if (!flags) return out; + if ((flags & clear_depth) && !(request.depth >= 0.0f && request.depth <= 1.0f)) { // false for NaN + out.verdict = Verdict::bad_depth; + return out; + } + if (((flags & clear_depth) && request.depth_read_only) || ((flags & clear_stencil) && request.stencil_read_only)) { + out.verdict = Verdict::read_only_plane; + return out; + } + if (request.rect_count && !request.rects_readable) { + out.verdict = Verdict::unreadable_rects; + return out; + } + out.verdict = Verdict::forward; + out.flags = flags; + out.rect_count = request.rect_count; + return out; +} + +inline const char* reason(Verdict verdict) +{ + switch (verdict) { + case Verdict::forward: return "forwarded"; + case Verdict::nothing_to_clear: return "no plane to clear"; + case Verdict::bad_depth: return "depth is not a number in [0, 1]"; + case Verdict::read_only_plane: return "a plane to clear is read-only in the view"; + case Verdict::unreadable_rects: return "the rectangles cannot be read"; + } + return "unknown"; +} + +} // namespace x2w_clear_depth diff --git a/tests/list_clear_depth_check.cpp b/tests/list_clear_depth_check.cpp new file mode 100644 index 0000000000..a69960ec5b --- /dev/null +++ b/tests/list_clear_depth_check.cpp @@ -0,0 +1,101 @@ +// Checks src/startup_stubs/list_clear_depth.h without a device: which ClearDepthStencilView calls are forwarded, with +// which flags, and which are refused. +// +// list_clear_depth_check [--mutate keep-stencil|allow-read-only] +// +// The expectations are written out case by case. Each mutation changes them to those of a wrong decision (a stencil +// clear kept for a format without stencil, a clear of a read-only plane forwarded); each must make the check fail. +#include "startup_stubs/list_clear_depth.h" + +#include +#include +#include +#include + +namespace { +using namespace x2w_clear_depth; +int failures, cases; +bool keep_stencil, allow_read_only; + +void expect(const char* label, const Request& request, Verdict verdict, unsigned flags = 0, unsigned rects = 0) +{ + ++cases; + const Plan got = plan(request); + if (got.verdict == verdict && got.flags == flags && got.rect_count == rects) return; + ++failures; + std::printf("FAIL %s: got %s (flags %u, rects %u), expected %s (flags %u, rects %u)\n", label, reason(got.verdict), got.flags, + got.rect_count, reason(verdict), flags, rects); +} +Request make(unsigned flags, bool stencil_format, float depth = 0.25f) +{ + Request request; + request.flags = flags; + request.format_has_stencil = stencil_format; + request.depth = depth; + return request; +} +} // namespace + +int main(int argc, char** argv) +{ + if (argc == 3 && std::strcmp(argv[1], "--mutate") == 0) { + keep_stencil = std::strcmp(argv[2], "keep-stencil") == 0; + allow_read_only = std::strcmp(argv[2], "allow-read-only") == 0; + if (!keep_stencil && !allow_read_only) return 2; + } else if (argc != 1) { + return 2; + } + const float nan = std::numeric_limits::quiet_NaN(); + const float inf = std::numeric_limits::infinity(); + + expect("depth only, depth-only format", make(1, false), Verdict::forward, 1); + expect("depth only, stencil format", make(1, true), Verdict::forward, 1); + expect("stencil only, stencil format", make(2, true), Verdict::forward, 2); + expect("both planes, stencil format", make(3, true), Verdict::forward, 3); + // The stencil bit is dropped for a format without a stencil plane; what is left is still cleared. + expect("both planes, depth-only format", make(3, false), Verdict::forward, keep_stencil ? 3u : 1u); + expect("stencil only, depth-only format", make(2, false), keep_stencil ? Verdict::forward : Verdict::nothing_to_clear, + keep_stencil ? 2u : 0u); + expect("no flags", make(0, true), Verdict::nothing_to_clear); + expect("unknown flag bits only", make(0xfc, true), Verdict::nothing_to_clear); + expect("unknown bits dropped from a valid mask", make(0xff, true), Verdict::forward, 3); + + expect("depth 0", make(1, true, 0.0f), Verdict::forward, 1); + expect("depth 1", make(1, true, 1.0f), Verdict::forward, 1); + expect("depth above 1", make(1, true, 1.5f), Verdict::bad_depth); + expect("depth below 0", make(1, true, -0.25f), Verdict::bad_depth); + expect("depth NaN", make(1, true, nan), Verdict::bad_depth); + expect("depth infinite", make(3, true, inf), Verdict::bad_depth); + // The depth value is ignored when only stencil is cleared. + expect("stencil only, junk depth", make(2, true, nan), Verdict::forward, 2); + + Request depth_ro = make(1, true); + depth_ro.depth_read_only = true; + expect("depth clear, depth plane read-only", depth_ro, allow_read_only ? Verdict::forward : Verdict::read_only_plane, + allow_read_only ? 1u : 0u); + depth_ro.flags = 2; + expect("stencil clear, only the depth plane read-only", depth_ro, Verdict::forward, 2); + Request stencil_ro = make(3, true); + stencil_ro.stencil_read_only = true; + expect("both planes, stencil plane read-only", stencil_ro, Verdict::read_only_plane); + stencil_ro.flags = 1; + expect("depth clear, only the stencil plane read-only", stencil_ro, Verdict::forward, 1); + // A read-only stencil bit does not matter once a depth-only format dropped the stencil clear. + Request dropped = make(3, false); + dropped.stencil_read_only = true; + expect("stencil dropped before the read-only check", dropped, Verdict::forward, 1); + + Request rects = make(1, true); + rects.rect_count = 3; + rects.rects_readable = true; + expect("three readable rectangles", rects, Verdict::forward, 1, 3); + rects.rects_readable = false; + expect("three unreadable rectangles", rects, Verdict::unreadable_rects); + rects.rect_count = 0; + expect("no rectangles, pointer unreadable", rects, Verdict::forward, 1, 0); + + std::printf("%d cases, %d failures\n", cases, failures); + if (failures) return 1; + std::printf("list clear depth checks passed\n"); + return 0; +} diff --git a/tests/startup_depth_clear.cpp b/tests/startup_depth_clear.cpp new file mode 100644 index 0000000000..8a4050e5d0 --- /dev/null +++ b/tests/startup_depth_clear.cpp @@ -0,0 +1,320 @@ +// ClearDepthStencilView (command-list slot 51) on a depth view, checked by reading the depth and stencil planes back. +// +// startup_depth_clear (X2W_D3D12_PERMISSIVE=1 X2W_D3D12_LIST_NOOP=1 X2W_D3D12_RENDER=1 X2W_D3D12_DEBUG=1) +// +// Through D3D12XboxCreateDevice the probe makes one 4x4 D32_FLOAT_S8X24_UINT texture and a DSV heap with four views: +// 0 writable, 1 depth plane read-only, 2 never created, 3 stencil plane read-only. Calls are recorded on one list, each +// followed by a submit and a readback of texel (0,0) and texel (3,3) of both planes: +// +// 0 nothing cleared yet control: the readback is not the value of step 1 +// 1 flags 3, depth 0.75, stencil 0x11 both planes written +// 2 flags 1, depth 0.25, stencil argument 0x77 depth written; the stencil argument is ignored +// 3 flags 2, depth argument 7.0, stencil 0x5A stencil written; the depth argument is ignored +// 4 flags 1, depth 0.5 with the rectangle (0,0)-(2,2) only the rectangle is cleared +// 5 refused: depth 1.5, NaN, depth plane read-only, stencil plane read-only, unreadable rectangles; the empty +// view; flags 0 does nothing nothing changes, refusals are counted +// 6 a call on the closed list ignored +// +// Counters come from x2w_d3d12_depth_clear_stats (forwarded, refused by rule) and x2w_d3d12_render_target_stats +// (handles that held no view). The desktop device must not be removed and the debug layer must store no errors. +// +// Exit codes: 0 pass, 77 no physical adapter, other values name the failing step. +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +using Microsoft::WRL::ComPtr; +extern "C" __declspec(dllimport) HRESULT WINAPI D3D12XboxCreateDevice(IUnknown*, const void*, REFIID, void**); +extern "C" __declspec(dllimport) void x2w_d3d12_render_target_stats(unsigned* binds, unsigned* unresolved); +extern "C" __declspec(dllimport) void x2w_d3d12_depth_clear_stats(unsigned* forwarded, unsigned* refused); + +namespace { +using Word = std::uint64_t; +template Word arg(T* value) { return reinterpret_cast(value); } +Word invoke(void* object, unsigned index, Word a = 0, Word b = 0, Word c = 0, Word d = 0, Word e = 0, Word f = 0, Word g = 0) +{ + using Slot = Word (WINAPI*)(void*, Word, Word, Word, Word, Word, Word, Word); + return reinterpret_cast((*static_cast(object))[index])(object, a, b, c, d, e, f, g); +} +bool ok(Word hr) { return SUCCEEDED(static_cast(hr)); } + +// ClearDepthStencilView(view, flags, depth, stencil, rect count, rects): the depth is a float, so the call must be +// typed (the integer-only invoke above would put it in the wrong register). +void clear_depth_stencil(void* list, D3D12_CPU_DESCRIPTOR_HANDLE view, UINT flags, float depth, UINT stencil, UINT count = 0, + const D3D12_RECT* rects = nullptr) +{ + using Slot = void (WINAPI*)(void*, Word, UINT, float, UINT, UINT, const D3D12_RECT*); + reinterpret_cast((*static_cast(list))[51])(list, view.ptr, flags, depth, stencil, count, rects); +} + +struct Counts { + unsigned forwarded = 0, refused = 0, unresolved = 0; + static Counts read() + { + Counts counts; + unsigned binds = 0; + x2w_d3d12_depth_clear_stats(&counts.forwarded, &counts.refused); + x2w_d3d12_render_target_stats(&binds, &counts.unresolved); + return counts; + } +}; +bool counted(const char* name, unsigned forwarded, unsigned refused, unsigned unresolved, Counts& before) +{ + const Counts now = Counts::read(); + const bool good = now.forwarded - before.forwarded == forwarded && now.refused - before.refused == refused && + now.unresolved - before.unresolved == unresolved; + std::printf("%s: forwarded +%u (expected +%u), refused +%u (expected +%u), unresolved +%u (expected +%u)\n", name, + now.forwarded - before.forwarded, forwarded, now.refused - before.refused, refused, + now.unresolved - before.unresolved, unresolved); + before = now; + return good; +} + +struct Texels { + float depth00 = 0, depth33 = 0; + std::uint8_t stencil00 = 0, stencil33 = 0; +}; + +struct Probe { + ComPtr desktop; + ComPtr readback; + D3D12_PLACED_SUBRESOURCE_FOOTPRINT footprint[2]{}; + void* queue = nullptr; + void* fence = nullptr; + Word fence_value = 0; + + bool submit(void* list) + { + void* lists[] = {list}; + invoke(queue, 10, 1, arg(lists)); + if (!ok(invoke(queue, 14, arg(fence), ++fence_value))) return false; + const auto deadline = GetTickCount64() + 10000; + while (invoke(fence, 8) < fence_value) { + if (GetTickCount64() >= deadline) return false; + Sleep(1); + } + return true; + } + UINT64 debug_errors() + { + ComPtr info; + if (FAILED(desktop.As(&info))) return 0; + UINT64 errors = 0; + for (UINT64 i = 0, n = info->GetNumStoredMessages(); i < n; ++i) { + SIZE_T bytes = 0; + if (FAILED(info->GetMessage(i, nullptr, &bytes))) continue; + std::vector storage(bytes); + auto* message = reinterpret_cast(storage.data()); + if (FAILED(info->GetMessage(i, message, &bytes))) continue; + if (message->Severity <= D3D12_MESSAGE_SEVERITY_ERROR) { + ++errors; + std::printf("debug layer: %.*s\n", static_cast(message->DescriptionByteLength), message->pDescription); + } + } + return errors; + } + // Both planes of the texture, copied on a desktop queue. The resource rests in COMMON between title lists; the + // barrier is explicit because a depth texture is not implicitly promoted. + bool read(ID3D12Resource* texture, Texels& out) + { + D3D12_COMMAND_QUEUE_DESC desc{}; + ComPtr observer; + ComPtr allocator; + ComPtr copy; + ComPtr done; + if (FAILED(desktop->CreateCommandQueue(&desc, IID_PPV_ARGS(&observer))) || + FAILED(desktop->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator))) || + FAILED(desktop->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.Get(), nullptr, IID_PPV_ARGS(©))) || + FAILED(desktop->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&done)))) + return false; + D3D12_RESOURCE_BARRIER barrier{}; + barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; + barrier.Transition.pResource = texture; + barrier.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES; + barrier.Transition.StateBefore = D3D12_RESOURCE_STATE_COMMON; + barrier.Transition.StateAfter = D3D12_RESOURCE_STATE_COPY_SOURCE; + copy->ResourceBarrier(1, &barrier); + for (UINT plane = 0; plane < 2; ++plane) { + D3D12_TEXTURE_COPY_LOCATION to{readback.Get(), D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT}; + to.PlacedFootprint = footprint[plane]; + D3D12_TEXTURE_COPY_LOCATION from{texture, D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX}; + from.SubresourceIndex = plane; + copy->CopyTextureRegion(&to, 0, 0, 0, &from, nullptr); + } + std::swap(barrier.Transition.StateBefore, barrier.Transition.StateAfter); + copy->ResourceBarrier(1, &barrier); + if (FAILED(copy->Close())) return false; + ID3D12CommandList* lists[] = {copy.Get()}; + observer->ExecuteCommandLists(1, lists); + HANDLE event = CreateEventW(nullptr, FALSE, FALSE, nullptr); + const bool finished = event && SUCCEEDED(observer->Signal(done.Get(), 1)) && + SUCCEEDED(done->SetEventOnCompletion(1, event)) && WaitForSingleObject(event, 10000) == WAIT_OBJECT_0; + if (event) CloseHandle(event); + unsigned char* memory = nullptr; + if (!finished || FAILED(readback->Map(0, nullptr, reinterpret_cast(&memory)))) return false; + const auto depth_at = [&](UINT x, UINT y) { + float value; + std::memcpy(&value, memory + footprint[0].Offset + y * footprint[0].Footprint.RowPitch + x * 4, sizeof(value)); + return value; + }; + out.depth00 = depth_at(0, 0); + out.depth33 = depth_at(3, 3); + out.stencil00 = memory[footprint[1].Offset]; + out.stencil33 = memory[footprint[1].Offset + 3 * footprint[1].Footprint.RowPitch + 3]; + readback->Unmap(0, nullptr); + return true; + } +}; + +bool same_float(float a, float b) { return std::fabs(a - b) < 1e-6f; } +bool expect(const char* name, const Texels& got, float depth00, float depth33, int stencil00, int stencil33) +{ + const bool good = same_float(got.depth00, depth00) && same_float(got.depth33, depth33) && got.stencil00 == stencil00 && got.stencil33 == stencil33; + std::printf("%s: depth (0,0) %.3f (3,3) %.3f stencil %02x %02x (expected %.3f %.3f %02x %02x)\n", name, got.depth00, + got.depth33, got.stencil00, got.stencil33, depth00, depth33, stencil00, stencil33); + return good; +} +} // namespace + +int main(int argc, char** argv) +{ + if (argc != 2) return 2; + ComPtr factory; + if (FAILED(CreateDXGIFactory1(IID_PPV_ARGS(&factory)))) return 3; + ComPtr adapter; + if (std::strcmp(argv[1], "hardware") == 0) { + for (UINT n = 0;; ++n) { + ComPtr candidate; + const HRESULT hr = factory->EnumAdapterByGpuPreference(n, DXGI_GPU_PREFERENCE_HIGH_PERFORMANCE, IID_PPV_ARGS(&candidate)); + if (hr == DXGI_ERROR_NOT_FOUND) return 77; + if (FAILED(hr)) return 3; + DXGI_ADAPTER_DESC1 desc{}; + if (FAILED(candidate->GetDesc1(&desc))) return 3; + if (!(desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE) && + SUCCEEDED(D3D12CreateDevice(candidate.Get(), D3D_FEATURE_LEVEL_12_0, __uuidof(ID3D12Device), nullptr))) { + adapter = candidate; + break; + } + } + } else if (std::strcmp(argv[1], "warp") != 0 || FAILED(factory->EnumWarpAdapter(IID_PPV_ARGS(&adapter)))) { + return 3; + } + DXGI_ADAPTER_DESC adapter_desc{}; + if (FAILED(adapter->GetDesc(&adapter_desc))) return 3; + std::printf("adapter=%ls\n", adapter_desc.Description); + + + Probe probe; + std::array parameters{}; + void* device = nullptr; + if (FAILED(D3D12XboxCreateDevice(adapter.Get(), parameters.data(), __uuidof(ID3D12Device), &device))) return 4; + if (FAILED(D3D12CreateDevice(adapter.Get(), D3D_FEATURE_LEVEL_12_0, IID_PPV_ARGS(&probe.desktop)))) return 4; + + D3D12_HEAP_PROPERTIES heap{D3D12_HEAP_TYPE_DEFAULT}; + const D3D12_RESOURCE_DESC texture_desc{D3D12_RESOURCE_DIMENSION_TEXTURE2D, 0, 4, 4, 1, 1, DXGI_FORMAT_D32_FLOAT_S8X24_UINT, {1, 0}, + D3D12_TEXTURE_LAYOUT_UNKNOWN, D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL}; + D3D12_CLEAR_VALUE clear{}; + clear.Format = DXGI_FORMAT_D32_FLOAT_S8X24_UINT; + clear.DepthStencil = {1.0f, 0}; + ComPtr texture; + if (FAILED(probe.desktop->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &texture_desc, D3D12_RESOURCE_STATE_COMMON, &clear, + IID_PPV_ARGS(&texture)))) + return 5; + UINT64 bytes = 0; + probe.desktop->GetCopyableFootprints(&texture_desc, 0, 2, 0, probe.footprint, nullptr, nullptr, &bytes); + heap.Type = D3D12_HEAP_TYPE_READBACK; + const D3D12_RESOURCE_DESC buffer{D3D12_RESOURCE_DIMENSION_BUFFER, 0, bytes, 1, 1, 1, DXGI_FORMAT_UNKNOWN, {1, 0}, + D3D12_TEXTURE_LAYOUT_ROW_MAJOR}; + if (FAILED(probe.desktop->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &buffer, D3D12_RESOURCE_STATE_COPY_DEST, nullptr, + IID_PPV_ARGS(&probe.readback)))) + return 5; + + // The DSV heap: view 0 writable, 1 depth plane read-only, 2 never created, 3 stencil plane read-only. + const struct { + D3D12_DESCRIPTOR_HEAP_DESC desc; + Word backing, bytes; + } heap_desc{{D3D12_DESCRIPTOR_HEAP_TYPE_DSV, 4}, 0, 0}; + void* dsv_heap = nullptr; + if (!ok(invoke(device, 14, arg(&heap_desc), arg(&__uuidof(ID3D12DescriptorHeap)), arg(&dsv_heap)))) return 6; + const UINT stride = probe.desktop->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_DSV); + const D3D12_CPU_DESCRIPTOR_HANDLE first{static_cast(invoke(dsv_heap, 9))}; + const std::array dsv{{first, {first.ptr + stride}, {first.ptr + 2 * stride}, {first.ptr + 3 * stride}}}; + D3D12_DEPTH_STENCIL_VIEW_DESC writable{DXGI_FORMAT_D32_FLOAT_S8X24_UINT, D3D12_DSV_DIMENSION_TEXTURE2D, D3D12_DSV_FLAG_NONE, {}}; + D3D12_DEPTH_STENCIL_VIEW_DESC depth_read_only = writable, stencil_read_only = writable; + depth_read_only.Flags = D3D12_DSV_FLAG_READ_ONLY_DEPTH; + stencil_read_only.Flags = D3D12_DSV_FLAG_READ_ONLY_STENCIL; + invoke(device, 21, arg(texture.Get()), arg(&writable), dsv[0].ptr); + invoke(device, 21, arg(texture.Get()), arg(&depth_read_only), dsv[1].ptr); + invoke(device, 21, arg(texture.Get()), arg(&stencil_read_only), dsv[3].ptr); + + D3D12_COMMAND_QUEUE_DESC queue_desc{}; + const unsigned list_desc[] = {D3D12_COMMAND_LIST_TYPE_DIRECT, 2, 1, 0}; + void *allocator = nullptr, *list = nullptr; + if (!ok(invoke(device, 8, arg(&queue_desc), arg(&__uuidof(ID3D12CommandQueue)), arg(&probe.queue))) || + !ok(invoke(device, 36, 0, 0, arg(&__uuidof(ID3D12Fence)), arg(&probe.fence))) || + !ok(invoke(device, 9, D3D12_COMMAND_LIST_TYPE_DIRECT, arg(&__uuidof(ID3D12CommandAllocator)), arg(&allocator))) || + !ok(invoke(device, 73, arg(list_desc), arg(allocator), 0, arg(&__uuidof(ID3D12GraphicsCommandList)), arg(&list)))) + return 7; + + // Records one case: reset, the calls, close, submit, read both planes back. + Texels seen; + const auto run = [&](auto&& calls) { + if (!ok(invoke(list, 139, arg(allocator), 0))) return false; + calls(); + invoke(list, 9); + return probe.submit(list) && probe.read(texture.Get(), seen); + }; + Counts counts = Counts::read(); + constexpr float nan = std::numeric_limits::quiet_NaN(); + + if (!run([&] {})) return 8; + if (!counted("0 nothing recorded", 0, 0, 0, counts)) return 9; + const Texels before = seen; + std::printf("0 before any clear: depth (0,0) %.3f, stencil %02x\n", before.depth00, before.stencil00); + if (same_float(before.depth00, 0.75f) || before.stencil00 == 0x11) return 10; // control: step 1 must change what is read + + if (!run([&] { clear_depth_stencil(list, dsv[0], 3, 0.75f, 0x11); })) return 11; + if (!counted("1 both planes", 1, 0, 0, counts) || !expect("1", seen, 0.75f, 0.75f, 0x11, 0x11)) return 12; + + if (!run([&] { clear_depth_stencil(list, dsv[0], 1, 0.25f, 0x77); })) return 13; + if (!counted("2 depth only", 1, 0, 0, counts) || !expect("2", seen, 0.25f, 0.25f, 0x11, 0x11)) return 14; + + if (!run([&] { clear_depth_stencil(list, dsv[0], 2, 7.0f, 0x5A); })) return 15; + if (!counted("3 stencil only", 1, 0, 0, counts) || !expect("3", seen, 0.25f, 0.25f, 0x5A, 0x5A)) return 16; + + const D3D12_RECT corner{0, 0, 2, 2}; + if (!run([&] { clear_depth_stencil(list, dsv[0], 1, 0.5f, 0, 1, &corner); })) return 17; + if (!counted("4 rectangle", 1, 0, 0, counts) || !expect("4", seen, 0.5f, 0.25f, 0x5A, 0x5A)) return 18; + + const auto* unreadable = reinterpret_cast(static_cast(0x10)); + if (!run([&] { + clear_depth_stencil(list, dsv[0], 1, 1.5f, 0); // depth above 1 + clear_depth_stencil(list, dsv[0], 1, nan, 0); // not a number + clear_depth_stencil(list, dsv[1], 1, 0.9f, 0); // depth plane read-only + clear_depth_stencil(list, dsv[3], 3, 0.9f, 0x99); // stencil plane read-only + clear_depth_stencil(list, dsv[0], 1, 0.9f, 0, 2, unreadable); + clear_depth_stencil(list, dsv[2], 1, 0.9f, 0); // a view that holds nothing + clear_depth_stencil(list, dsv[0], 0, 0.9f, 0x99); // no plane: nothing to do + })) + return 19; + if (!counted("5 refusals", 0, 5, 1, counts) || !expect("5", seen, 0.5f, 0.25f, 0x5A, 0x5A)) return 20; + + // The list is closed now: a call must be ignored. + clear_depth_stencil(list, dsv[0], 3, 0.0f, 0xff); + if (!counted("6 closed list", 0, 0, 0, counts)) return 21; + + const HRESULT removed = probe.desktop->GetDeviceRemovedReason(); + const UINT64 errors = probe.debug_errors(); + std::printf("device removed reason: 0x%08lx, debug layer errors: %llu\n", static_cast(removed), + static_cast(errors)); + return removed == S_OK && errors == 0 ? 0 : 70; +} From ab828adfaa51cfa40eace2bd509720b2d5bb967c Mon Sep 17 00:00:00 2001 From: tedin7 Date: Wed, 25 Nov 2026 01:53:28 +0100 Subject: [PATCH 2/2] startup: keep slot 51 timing and the bound read-only depth state --- src/startup_stubs/d3d12_xs_device.cpp | 41 ++++++++++++++++----------- 1 file changed, 24 insertions(+), 17 deletions(-) diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index 2731763235..1bf39a80aa 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -181,7 +181,6 @@ std::vector descriptor_ranges; // API documents 1,048,576, but a driver may accept fewer (1,000,000 on the GTX 1660 SUPER here), so // the accepted maximum is measured once and cached rather than assumed. constexpr std::uint64_t view_heap_probe_floor = 65536; - void log(const char* format, ...); bool first_calls(LONG& counter, LONG limit); void request_translation(Wrapper* pipeline); @@ -307,6 +306,21 @@ struct Timed { InterlockedIncrement64(&time_calls[category]); } }; +// Per-slot tick, call and census counters of a command-list slot, recorded when it goes out of scope (slot < 0: none). +struct ListSlotTimed { + int slot; + LARGE_INTEGER start; + explicit ListSlotTimed(int n) : slot(n) { QueryPerformanceCounter(&start); } + ~ListSlotTimed() + { + if (slot < 0) return; + LARGE_INTEGER end; + QueryPerformanceCounter(&end); + InterlockedAdd64(&list_slot_ticks[slot], end.QuadPart - start.QuadPart); + InterlockedIncrement64(&list_slot_calls[slot]); + InterlockedIncrement64(&list_slot_census[slot]); + } +}; void log(const char* format, ...) { @@ -521,20 +535,7 @@ template __declspec(noinline) u64 noop_slot(u64 rcx, u64 rdx, u64 r8, u64 r9, u64 s0, u64 s1, u64 s2, u64 s3) { Timed timed(K == list_kind ? time_list : K == queue_kind ? time_queue : time_device_noop); - struct SlotTimed { - LARGE_INTEGER start; - SlotTimed() { QueryPerformanceCounter(&start); } - ~SlotTimed() - { - LARGE_INTEGER end; - QueryPerformanceCounter(&end); - if (K == list_kind) { - InterlockedAdd64(&list_slot_ticks[N & 255], end.QuadPart - start.QuadPart); - InterlockedIncrement64(&list_slot_calls[N & 255]); - InterlockedIncrement64(&list_slot_census[N & 255]); - } - } - } slot_timed; + ListSlotTimed slot_timed(K == list_kind ? N & 255 : -1); if (K == list_kind) InterlockedIncrement(&draw_calls_seen); if (K == list_kind && capture_active) { const u64 stack[4] = {s0, s1, s2, s3}; @@ -2582,8 +2583,9 @@ static_assert(x2w_clear_depth::clear_depth == D3D12_CLEAR_FLAG_DEPTH && x2w_clea void __stdcall list_clear_depth(Wrapper* self, u64 handle, UINT flags, float depth, UINT stencil, UINT rect_count, const D3D12_RECT* rects) { - InterlockedIncrement64(&list_slot_calls[51]); - InterlockedIncrement64(&list_slot_census[51]); + // The table calls this entry directly, so it keeps the timing noop_slot would have recorded for slot 51. + Timed timed(time_list); + ListSlotTimed slot_timed(51); InterlockedIncrement(&draw_calls_seen); auto* list = recording(self); if (!list) return; @@ -2620,10 +2622,15 @@ void __stdcall list_clear_depth(Wrapper* self, u64 handle, UINT flags, float dep log("x2w-d3d12 ClearDepthStencilView refused: %s (flags 0x%x, depth %.3f)", x2w_clear_depth::reason(plan.verdict), flags, depth); return; } + // The clear needs DEPTH_WRITE; a texture still bound through a read-only view goes back to its read state after it. + D3D12_RESOURCE_STATES bound_read = D3D12_RESOURCE_STATE_COMMON; + for (const auto& known : pass_of(self).states) + if (known.first == target && (known.second & D3D12_RESOURCE_STATE_DEPTH_READ)) bound_read = known.second; require_state(self, target, D3D12_RESOURCE_STATE_DEPTH_WRITE); list->ClearDepthStencilView(D3D12_CPU_DESCRIPTOR_HANDLE{static_cast(desktop)}, static_cast(plan.flags), depth, static_cast(stencil), plan.rect_count, plan.rect_count ? rects : nullptr); + if (bound_read != D3D12_RESOURCE_STATE_COMMON) require_state(self, target, bound_read); InterlockedIncrement(&render_depth_clears); InterlockedIncrement(&render_clears); }