diff --git a/CMakeLists.txt b/CMakeLists.txt index ab6f8d14cf..a08fa313cb 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1346,6 +1346,26 @@ foreach(backend IN ITEMS warp hardware) ENVIRONMENT "X2W_D3D12_BUDGET=1;X2W_D3D12_PERMISSIVE=1;X2W_D3D12_LIST_NOOP=1;X2W_D3D12_RENDER=1;X2W_D3D12_DEBUG=0") endforeach() +# X2W_D3D12_RETIRE_REASONS=1 names why released resources still hold their desktop object (needs RELEASE_RETIRED and +# BUDGET). `off` (no RETIRE_REASONS) and `no-retire` (no RELEASE_RETIRED) are negative controls: the line must stay empty. +add_executable(startup_resource_retire_reasons tests/startup_resource_retire_reasons.cpp) +target_include_directories(startup_resource_retire_reasons PRIVATE src) +target_compile_features(startup_resource_retire_reasons PRIVATE cxx_std_17) +target_link_libraries(startup_resource_retire_reasons PRIVATE d3d12_xs_shim d3d12 dxgi) +foreach(backend IN ITEMS warp hardware) + set(reasons_base "X2W_D3D12_BUDGET=1;X2W_D3D12_PERMISSIVE=1;X2W_D3D12_LIST_NOOP=1;X2W_D3D12_RENDER=1;X2W_D3D12_DEBUG=0") + add_test(NAME startup_resource_retire_reasons_${backend} COMMAND startup_resource_retire_reasons ${backend}) + set_tests_properties(startup_resource_retire_reasons_${backend} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 + ENVIRONMENT "${reasons_base};X2W_D3D12_RELEASE_RETIRED=1;X2W_D3D12_RETIRE_REASONS=1") + add_test(NAME startup_resource_retire_reasons_off_${backend} COMMAND startup_resource_retire_reasons ${backend} off) + set_tests_properties(startup_resource_retire_reasons_off_${backend} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 + ENVIRONMENT "${reasons_base};X2W_D3D12_RELEASE_RETIRED=1") + add_test(NAME startup_resource_retire_reasons_no_retire_${backend} COMMAND startup_resource_retire_reasons ${backend} no-retire) + set_tests_properties(startup_resource_retire_reasons_no_retire_${backend} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 + ENVIRONMENT "${reasons_base};X2W_D3D12_RETIRE_REASONS=1") +endforeach() + + add_executable(startup_resource_retire_title tests/startup_resource_retire_title.cpp) target_include_directories(startup_resource_retire_title PRIVATE src) target_compile_features(startup_resource_retire_title PRIVATE cxx_std_17) @@ -1362,6 +1382,28 @@ foreach(backend IN ITEMS warp hardware) ENVIRONMENT "X2W_D3D12_BUDGET=1;X2W_D3D12_PERMISSIVE=1;X2W_D3D12_LIST_NOOP=1;X2W_D3D12_RENDER=1;X2W_RESOURCE_INDEX_CHECK=1;X2W_D3D12_DEBUG=0") endforeach() +# X2W_D3D12_RELEASE_RETIRED_VIEWS=1 frees a released class texture that only tracked slot-18 descriptor slots keep alive by +# replacing those slots with null descriptors. `keep` is the negative control (views switch off, or retire switch off). +add_executable(startup_resource_retire_views tests/startup_resource_retire_views.cpp) +target_include_directories(startup_resource_retire_views PRIVATE src) +target_compile_features(startup_resource_retire_views PRIVATE cxx_std_17) +target_link_libraries(startup_resource_retire_views PRIVATE d3d12_xs_shim d3d12 dxgi d3dcompiler) +foreach(backend IN ITEMS warp hardware) + foreach(debug IN ITEMS 0 1) + set(retire_views_env "X2W_D3D12_BUDGET=1;X2W_D3D12_PERMISSIVE=1;X2W_D3D12_LIST_NOOP=1;X2W_D3D12_RENDER=1;X2W_D3D12_DEBUG=${debug}") + add_test(NAME startup_resource_retire_views_${backend}_debug${debug} COMMAND startup_resource_retire_views ${backend}) + set_tests_properties(startup_resource_retire_views_${backend}_debug${debug} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 + ENVIRONMENT "${retire_views_env};X2W_D3D12_RELEASE_RETIRED=1;X2W_D3D12_RELEASE_RETIRED_VIEWS=1") + endforeach() + set(retire_views_keep "X2W_D3D12_BUDGET=1;X2W_D3D12_PERMISSIVE=1;X2W_D3D12_LIST_NOOP=1;X2W_D3D12_RENDER=1;X2W_D3D12_DEBUG=0") + add_test(NAME startup_resource_retire_views_keep_${backend} COMMAND startup_resource_retire_views ${backend} keep) + set_tests_properties(startup_resource_retire_views_keep_${backend} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 + ENVIRONMENT "${retire_views_keep};X2W_D3D12_RELEASE_RETIRED=1") + add_test(NAME startup_resource_retire_views_noretire_${backend} COMMAND startup_resource_retire_views ${backend} keep) + set_tests_properties(startup_resource_retire_views_noretire_${backend} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 + ENVIRONMENT "${retire_views_keep};X2W_D3D12_RELEASE_RETIRED_VIEWS=1") +endforeach() + # GPU writes the dispatch record that the desktop command processor consumes (Refs #1412). add_executable(startup_compute_binding_trace tests/startup_compute_binding_trace.cpp) target_compile_features(startup_compute_binding_trace PRIVATE cxx_std_20) diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index c70bbe8e61..cddcd0878d 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -1338,6 +1338,8 @@ ctest --preset dev --no-tests=error -R '^startup_trap_header(_prefix_control|_pr | `X2W_D3D12_QUERY_SLOTS=1` | diagnostic, in render mode: binds command-list slots 28 to 30 to the hypothesised occlusion query methods (see [Occlusion queries](#occlusion-queries)). Unset, the three slots stay no-ops | | `X2W_D3D12_BUDGET=1` | adds [video memory budget and allocation counts](#d3d12-resource-budget) to the D3D12 heartbeat | | `X2W_D3D12_RELEASE_RETIRED=1` | opt-in, effective with `X2W_D3D12_RENDER=1` only (the list handlers that record holds exist only there): frees the desktop object of a released committed 2D texture of one narrow class once no recorded list, submission or release-time fence refers to it ([details](#d3d12-resource-budget)). Unset, nothing changes | +| `X2W_D3D12_RELEASE_RETIRED_VIEWS=1` | opt-in, effective only together with `X2W_D3D12_RELEASE_RETIRED=1`: a released class texture that only tracked slot-18 descriptor slots keep alive (the title never overwrites them) is freed once those slots are replaced by null descriptors ([details](#d3d12-resource-budget)). Unset, nothing changes | +| `X2W_D3D12_RETIRE_REASONS=1` | diagnostic only, effective with `X2W_D3D12_RELEASE_RETIRED=1` and `X2W_D3D12_BUDGET=1`: adds one `x2w-retire held:` line to the heartbeat that counts final-released resources whose desktop object is still alive, by reason ([details](#d3d12-resource-budget)). Unset, nothing is recorded | | `X2W_DRAW_NULL_IDENTITY=1` | null descriptors read as identity values instead of zero | | `X2W_DEPTH_STATE=1` | translated draws of slot 57 pipelines take their depth-stencil state and stencil reference from state block A instead of the desktop default (depth and stencil off); a refused block keeps the default. Off by default, then nothing changes: see [Shortcuts that are known to be wrong](#shortcuts-that-are-known-to-be-wrong) | | `X2W_PRESENT_SIGNATURE_EVERY=` | in render mode, samples a coarse signature of the presented picture every `n` presents from the start, without a script request (`0` off). Unset, sampling starts, every 4 presents, only once a script with a `wait` asks for it: see [Waiting for the presented picture](#waiting-for-the-presented-picture) | @@ -1413,6 +1415,47 @@ unordered-access flag, and live in a default heap without heap flags: reusing the same title address or desktop pointer does not skip uploads or resolve a retired wrapper. +`X2W_D3D12_RELEASE_RETIRED_VIEWS=1` (only with `X2W_D3D12_RELEASE_RETIRED=1`) ends the +`view-refs` retention. Once a released class texture's release-time fences have passed, +the drain (a try-lock, never blocking) replaces every tracked slot-18 descriptor slot +that names it, in every heap and so every `CopyDescriptors*` copy, by a null SRV of the +same dimension: the shadow entry and its ref are dropped, the desktop descriptor is +rewritten with `CreateShaderResourceView(nullptr, ...)`, the view records naming the +resource lose it, and the view token in title descriptor memory is cleared when it +still carries that id. A draw that reads the slot afterwards binds a null texture +(zeros). The texture is then freed by the normal rules: lists and submissions that hold +it through `retire_hold` keep the desktop object until the recording is dropped or the +submission's fence passes. No recorded list or submission reads a title heap's SRV +descriptor (translated draws build their own descriptors from the tokens at draw time +and hold what they sample), so the rewrite cannot reach GPU work. A slot that cannot be +rewritten keeps its ref and the texture stays retained. Not covered: a title thread +that writes the same slot at the moment of the drain, and a guest that uses the +resource after its final release (unsupported with the switch, as before). +`startup_resource_retire_views_*` reads the desktop descriptors back through a compute +probe; the `keep` and `noretire` cases are the negative controls. + +`X2W_D3D12_RETIRE_REASONS=1` (with `X2W_D3D12_RELEASE_RETIRED=1` and +`X2W_D3D12_BUDGET=1`) adds a diagnostic line to the heartbeat. It counts every +resource whose final guest Release happened and whose desktop object is still +alive, once, by the first cause that applies. Format: `reason=count/bytes(oldest Nf)`, +bytes from the budget ticket, `oldest` in frames since the final Release: +- `view-refs`: a tracked slot 18 descriptor still names it; + `view-refs-in-visible-heap` is the part with a descriptor in a shader-visible heap. +- `list-hold`, `flight`: a closed or recording list, or a submission, holds a + desktop reference. +- `queued-waiting-fence`: queued, the release-time fence of a queue has not passed; + `drain-pending`: ready, the drain has not run yet; `unqueued`: no queue could take its marker. +- `left-class:`: it was in the class and the first use named left it. +- `never-class:`: it was + never in the class (`slot`: created by a path that does not classify). +- `other`: none of the above. +`total` is the sum; `unattributed` is the budget's retained count and bytes minus +`total` (backing heaps, upload and readback objects, and anything created outside the wrappers). +Wrappers without a desktop object (tiled address textures) are not counted. A +released resource that only a list or submission keeps alive after its wrapper +let go is matched by its desktop pointer. Without the switches nothing is +recorded and no line is built. + Every other resource (buffers, placed buffers, reserved resources, render/depth/UAV targets, and slot 127 `__XMemAllocationHooks__` textures) keeps the lifetime described above. A resource leaves the class for good when a UAV/RTV/DSV view is diff --git a/src/startup_stubs/d3d12_capture.inl b/src/startup_stubs/d3d12_capture.inl index 879f71f8e1..6f92733f06 100644 --- a/src/startup_stubs/d3d12_capture.inl +++ b/src/startup_stubs/d3d12_capture.inl @@ -320,7 +320,7 @@ void note_view(int slot, u64 resource, u64 counter, const void* desc, std::size_ retire_release_view_ref(reinterpret_cast(view_records()[prev - 1].resource)); } } else if (slot == 18 && resource) { - retire_leave_class(reinterpret_cast(resource)); + retire_leave_class(reinterpret_cast(resource), RetireLeft::view); } ReleaseSRWLockExclusive(¬e_lock); const std::size_t token_bytes = slot == 22 ? x2w_startup::title_sampler_stride : 32u; @@ -367,7 +367,7 @@ void note_copy(u64 dest_title, u64 src_title, u64 dest_desktop, u64 src_desktop, const std::uint32_t src_id = from[i]; if (src_id && src_id - 1 < view_records().size() && view_records()[src_id - 1].slot == 18 && view_materialized()[src_id - 1]) - retire_leave_class(reinterpret_cast(view_records()[src_id - 1].resource)); + retire_leave_class(reinterpret_cast(view_records()[src_id - 1].resource), RetireLeft::view_copy); } } ReleaseSRWLockExclusive(¬e_lock); diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index b5b79f4442..06a1eb1c16 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -139,6 +139,13 @@ struct IndirectGraphicsPipeline { UINT cached_srv_root = UINT_MAX; }; +// Why a resource is outside the retire class (X2W_D3D12_RELEASE_RETIRED), decided at creation, and why it left it later. +// Both only feed the opt-in X2W_D3D12_RETIRE_REASONS diagnostics. never::slot is the zero value: created by a path that +// does not classify. +enum class RetireNever : std::uint8_t { slot, none, buffer, dimension, msaa, rt_ds_uav, heap_type, heap_flags, title_memory, + aliased, reserved, count }; +enum class RetireLeft : std::uint8_t { none, view, view_copy, residency, present, hold_missed, count }; + struct alignas(16) WrapperOwn { IUnknown* real; LONG refs; @@ -159,6 +166,10 @@ struct alignas(16) WrapperOwn { // accesses: a race needs the guest to use a resource across its own final Release. bool retire_hold_missed; // Resource: retire_hold could not record a use (no desktop object or no room), so the // drain must keep it for the process instead of dropping a list's desktop object. + bool retire_views_stuck; // Resource: X2W_D3D12_RELEASE_RETIRED_VIEWS could not clear every descriptor slot that + // names it, so it stays retained (and is not scanned again). + std::uint8_t retire_never; // RetireNever of this resource (set only with X2W_D3D12_RELEASE_RETIRED) + std::uint8_t retire_left; // RetireLeft: the first use that took it out of the class volatile LONG retire_view_refs; // Live tracked slot-18 SRV descriptor slots referencing this resource. bool retire_has_written_gen; // Whether written_textures()[title_memory].generation was snapshotted at Release. u64 retire_written_gen; // Snapshotted written_textures() generation for stale-entry cleanup. @@ -792,6 +803,14 @@ bool release_retired_enabled() return on; } +// X2W_D3D12_RELEASE_RETIRED_VIEWS=1 (needs X2W_D3D12_RELEASE_RETIRED=1): a released class member that only tracked slot-18 +// descriptor slots keep alive is freed once every such slot has been replaced by a null descriptor. +bool release_retired_views_enabled() +{ + static const bool on = release_retired_enabled() && x2w_local::env_on("X2W_D3D12_RELEASE_RETIRED_VIEWS"); + return on; +} + // The retire class of X2W_D3D12_RELEASE_RETIRED, decided once at creation from the desktop description: a committed // 2D texture with one sample, no render-target, depth-stencil or unordered-access use, in a default heap with no heap // flags. Slot 27 and non-hooked slot 127 have no title memory; slot 133 committed 2D textures with title memory are @@ -799,13 +818,27 @@ bool release_retired_enabled() // resources with __XMemAllocationHooks__ title memory remain excluded. Every use reaches the shim through handlers // that retire_hold or shadow-slot SRV ref-counting cover, or that clear the flag; see // docs/startup-runtime.md#d3d12-resource-budget. -bool retire_class(const D3D12_HEAP_PROPERTIES& props, D3D12_HEAP_FLAGS heap_flags, const D3D12_RESOURCE_DESC& desc, - const void* title_memory, bool allow_title_memory = false) +RetireNever retire_classify(const D3D12_HEAP_PROPERTIES& props, D3D12_HEAP_FLAGS heap_flags, const D3D12_RESOURCE_DESC& desc, + const void* title_memory, bool allow_title_memory) { - return release_retired_enabled() && props.Type == D3D12_HEAP_TYPE_DEFAULT && heap_flags == D3D12_HEAP_FLAG_NONE && - desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE2D && desc.SampleDesc.Count == 1 && - (desc.Flags & ~D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE) == D3D12_RESOURCE_FLAG_NONE && - (!title_memory || allow_title_memory); + if (desc.Dimension == D3D12_RESOURCE_DIMENSION_BUFFER) return RetireNever::buffer; + if (desc.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D) return RetireNever::dimension; + if (desc.SampleDesc.Count != 1) return RetireNever::msaa; + if ((desc.Flags & ~D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE) != D3D12_RESOURCE_FLAG_NONE) return RetireNever::rt_ds_uav; + if (props.Type != D3D12_HEAP_TYPE_DEFAULT) return RetireNever::heap_type; + if (heap_flags != D3D12_HEAP_FLAG_NONE) return RetireNever::heap_flags; + if (title_memory && !allow_title_memory) return RetireNever::title_memory; + return RetireNever::none; +} + +// Decides the retire class of a new wrapper once, from the desktop description, and records the reason for the diagnostics. +void retire_set_class(Wrapper* w, const D3D12_HEAP_PROPERTIES& props, D3D12_HEAP_FLAGS heap_flags, + const D3D12_RESOURCE_DESC& desc, const void* title_memory, bool allow_title_memory = false) +{ + if (!release_retired_enabled()) return; + const RetireNever why = retire_classify(props, heap_flags, desc, title_memory, allow_title_memory); + w->own().retire_never = static_cast(why); + w->own().retire_when_idle = why == RetireNever::none; } template @@ -838,8 +871,12 @@ __declspec(noinline) u64 create_slot(Wrapper* self, u64 a, u64 b, u64 c, u64 d, Wrapper* child = wrap(static_cast(*out), kind); if constexpr (K == device_kind && N == 27) { if (kind == resource_kind && args[0]) - child->own().retire_when_idle = retire_class(*reinterpret_cast(args[0]), - static_cast(args[1]), desc_copy, nullptr); + retire_set_class(child, *reinterpret_cast(args[0]), + static_cast(args[1]), desc_copy, nullptr); + } + if constexpr (K == device_kind && (N == 29 || N == 30)) { + if (kind == resource_kind && release_retired_enabled()) + child->own().retire_never = static_cast(N == 29 ? RetireNever::aliased : RetireNever::reserved); } if constexpr (K == device_kind && (N == 27 || N == 28 || N == 29)) { if (x2w_budget::enabled()) { @@ -931,7 +968,7 @@ ULONG __stdcall add_ref(Wrapper* self) { return static_cast(InterlockedIn void retire_placement(Wrapper* w); void register_retire_queue(Wrapper* queue); void retire_resource(Wrapper* w); -void retire_leave_class(const void* object); +void retire_leave_class(const void* object, RetireLeft why); void retire_add_view_ref(const void* object); void retire_release_view_ref(const void* object); void retire_drop_heap_views(Wrapper* heap); @@ -941,6 +978,8 @@ void retire_drop_recording(Wrapper* list); void retire_discard_holds(Wrapper* list); void retire_note_submission(ID3D12CommandQueue* queue, const std::vector& lists); void drain_retired_resources(); +bool retire_reasons_enabled(); +void retire_diag_note_release(Wrapper* w); void drop_mesh_lease_owner(Wrapper* w); void discard_mesh_lease_recording(ID3D12CommandList* list); void clear_unplaced_buffers(Wrapper* device); @@ -960,6 +999,7 @@ ULONG __stdcall release(Wrapper* self) discard_mesh_lease_recording(static_cast(self->own().real)); retire_drop_recording(self); } + if (self->own().kind == resource_kind && retire_reasons_enabled()) retire_diag_note_release(self); if (self->own().retire_when_idle) retire_resource(self); if (self->own().kind == device_kind) clear_unplaced_buffers(self); @@ -1243,7 +1283,7 @@ HRESULT __stdcall device_residency(Wrapper* self, UINT count, void* const* objec { std::vector real(count); for (UINT i = 0; i < count; ++i) { - retire_leave_class(objects[i]); // no hold tracks the residency of a desktop object + retire_leave_class(objects[i], RetireLeft::residency); // no hold tracks the residency of a desktop object real[i] = reinterpret_cast(unwrap(reinterpret_cast(objects[i]))); } return N == 34 ? device_of(self)->MakeResident(count, real.data()) : device_of(self)->Evict(count, real.data()); @@ -3968,13 +4008,13 @@ __declspec(noinline) u64 view_slot(Wrapper* self, u64 a, u64 b, u64 c, u64 d) Timed timed(time_view); // UAV, RTV and DSV views keep the resource's old lifetime; slot-18 SRVs stay in the retire class as long as // their descriptor slots are tracked by shadow_slot and translated draws hold bound resources with retire_hold. - if constexpr (N >= 19 && N <= 21) retire_leave_class(reinterpret_cast(a)); - if constexpr (N == 19) retire_leave_class(reinterpret_cast(b)); + if constexpr (N >= 19 && N <= 21) retire_leave_class(reinterpret_cast(a), RetireLeft::view); + if constexpr (N == 19) retire_leave_class(reinterpret_cast(b), RetireLeft::view); u64 args[4] = {unwrap(a), unwrap(b), unwrap(c), unwrap(d)}; const u64 title_dest = args[D]; args[D] = desktop_cpu_handle(args[D]); if (!args[D]) { - if constexpr (N == 18) retire_leave_class(reinterpret_cast(a)); + if constexpr (N == 18) retire_leave_class(reinterpret_cast(a), RetireLeft::view); return 0; } const auto record_view = [&](bool materialized) { @@ -4313,7 +4353,7 @@ HRESULT __stdcall device_place_resource_x(Wrapper* self, void* address, const D3 w->own().budget = x2w_budget::committed(device_of(self), created, props.Type); w->own().title_memory = address; note_resource(w, desc, 0); - w->own().retire_when_idle = retire_class(props, D3D12_HEAP_FLAG_NONE, texture, address, /*allow_title_memory=*/true); + retire_set_class(w, props, D3D12_HEAP_FLAG_NONE, texture, address, /*allow_title_memory=*/true); *out = w; return S_OK; } @@ -4391,6 +4431,7 @@ HRESULT __stdcall device_place_resource_x(Wrapper* self, void* address, const D3 clear, text, static_cast(hr), placement, resource ? resource->GetGPUVirtualAddress() : 0ull); if (FAILED(hr)) return hr; Wrapper* w = wrap(resource, resource_kind); + if (release_retired_enabled()) w->own().retire_never = static_cast(RetireNever::buffer); w->own().title_memory = address; const ResourceInfo record{*desc, desc->Width, aliased ? Placement::aliased_buffer : Placement::copied_buffer, self, initial_state}; auto& group = placement_group(desc->Width); @@ -4469,10 +4510,13 @@ void register_retire_queue(Wrapper* queue) } // A use the holds do not cover (a view, residency, presentation) takes the resource out of the class for good. -void retire_leave_class(const void* object) +void retire_leave_class(const void* object, RetireLeft why) { if (!release_retired_enabled()) return; - if (Wrapper* w = as_wrapper(object)) w->own().retire_when_idle = false; + if (Wrapper* w = as_wrapper(object)) { + if (w->own().retire_when_idle) w->own().retire_left = static_cast(why); // the first use counts + w->own().retire_when_idle = false; + } } void retire_add_view_ref(const void* object) @@ -4573,6 +4617,7 @@ void retire_hold(Wrapper* list, Wrapper* resource) // The use cannot be recorded: leave the class, and mark it so the drain keeps the desktop object for the // process (as it keeps a submission it could not fence) rather than dropping one a list still names. resource->own().retire_when_idle = false; + resource->own().retire_left = static_cast(RetireLeft::hold_missed); resource->own().retire_hold_missed = true; } ReleaseSRWLockExclusive(&retire_lock); @@ -4673,10 +4718,143 @@ void retire_resource(Wrapper* w) if (!queued) InterlockedIncrement64(&retire_kept); // stays retained, as without the switch } +// A null SRV of the dimension the title's view had (the draw path binds the same R8G8B8A8_UNORM null for a view that +// resolves to nothing). A null resource reads no more of the description than its format and dimension. +D3D12_SHADER_RESOURCE_VIEW_DESC retire_null_srv_desc(const ViewRecord& record) +{ + D3D12_SHADER_RESOURCE_VIEW_DESC desc{}; + desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; + desc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + desc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; + if (record.desc_bytes >= 40) { + D3D12_SRV_DIMENSION dimension; + std::memcpy(&dimension, record.desc + 4, sizeof(dimension)); + if (dimension >= D3D12_SRV_DIMENSION_TEXTURE1D && dimension <= D3D12_SRV_DIMENSION_TEXTURECUBEARRAY) + desc.ViewDimension = dimension; + } + switch (desc.ViewDimension) { + case D3D12_SRV_DIMENSION_TEXTURE1D: desc.Texture1D.MipLevels = 1; break; + case D3D12_SRV_DIMENSION_TEXTURE1DARRAY: desc.Texture1DArray.MipLevels = 1; desc.Texture1DArray.ArraySize = 1; break; + case D3D12_SRV_DIMENSION_TEXTURE2DARRAY: desc.Texture2DArray.MipLevels = 1; desc.Texture2DArray.ArraySize = 1; break; + case D3D12_SRV_DIMENSION_TEXTURE2DMSARRAY: desc.Texture2DMSArray.ArraySize = 1; break; + case D3D12_SRV_DIMENSION_TEXTURE3D: desc.Texture3D.MipLevels = 1; break; + case D3D12_SRV_DIMENSION_TEXTURECUBE: desc.TextureCube.MipLevels = 1; break; + case D3D12_SRV_DIMENSION_TEXTURECUBEARRAY: desc.TextureCubeArray.MipLevels = 1; desc.TextureCubeArray.NumCubes = 1; break; + case D3D12_SRV_DIMENSION_TEXTURE2DMS: break; + default: desc.Texture2D.MipLevels = 1; break; + } + return desc; +} + +// True when the release-time fence of every queue has passed (retire_lock held). +bool retire_fences_reached(const RetiredResource& item) +{ + bool reached = item.targets.size() <= retire_queues.size(); + for (std::size_t q = 0; q < item.targets.size() && reached; ++q) + reached = retire_queues[q].fence->GetCompletedValue() >= item.targets[q]; + return reached; +} + +// X2W_D3D12_RELEASE_RETIRED_VIEWS=1: a released class member whose release-time fences have passed and that only +// tracked slot-18 descriptor slots still name gets those slots replaced by null descriptors, so the main drain loop can +// free it. Every slot of every heap that has a shadow is handled, copies included (they are counted the same way). For +// each slot, under note_lock: the shadow entry is cleared and its ref dropped, and the desktop descriptor is rewritten +// as a null SRV of the same dimension. The view records that name the resource then lose it (so a token that a raw +// title copy left behind resolves to nothing), and the token in title descriptor memory is cleared when it still +// carries the id. A slot that cannot be rewritten keeps its ref, and the resource stays retained. Nothing waits. +// Why this cannot reach GPU work: translated draws never bind a title heap. They build their own descriptors from the +// title's tokens at draw time and retire_hold what they sample, so a descriptor of a title heap is read by no recorded +// list or submission (ClearUnorderedAccessView binds a heap for UAV slots only, and those are not touched here). +void retire_null_ready_views() +{ + std::vector ready; + try { + ready.reserve(64); + } catch (const std::bad_alloc&) { + return; + } + if (!TryAcquireSRWLockShared(&retire_lock)) return; + for (const RetiredResource& item : retired_resources) { + Wrapper* w = item.wrapper; + if (ready.size() == ready.capacity()) break; + if (w->own().retire_hold_missed || w->own().retire_views_stuck || !retire_fences_reached(item)) continue; + if (InterlockedCompareExchange(&w->own().retire_view_refs, 0, 0) <= 0) continue; + if (InterlockedCompareExchange(&w->own().refs, 0, 0) != 0) continue; // referenced again: leave its views + ready.push_back(w); + } + ReleaseSRWLockShared(&retire_lock); + if (ready.empty()) return; + + struct Cleared { + u64 title_cpu; + std::uint32_t index, increment, id; + }; + std::vector cleared; + std::size_t stuck = 0; + // draw_lock first, in the order draw_translated takes them: a draw holds it from reading a view record until it + // retire_holds the texture, so clearing the records under it means a draw either recorded its hold already or + // resolves the token to nothing. + if (!TryAcquireSRWLockExclusive(&draw_lock)) return; + if (!TryAcquireSRWLockExclusive(¬e_lock)) { + ReleaseSRWLockExclusive(&draw_lock); + return; + } + try { + std::unordered_set ids; // view ids that name a ready resource + for (std::uint32_t id = 0; id < view_records().size(); ++id) { + const ViewRecord& record = view_records()[id]; + if (record.slot != 18 || !view_materialized()[id]) continue; + if (std::find(ready.begin(), ready.end(), reinterpret_cast(record.resource)) != ready.end()) + ids.insert(id); + } + ID3D12Device* const device = the_device ? device_of(the_device) : nullptr; + for (const HeapInfo& h : heap_infos()) { + if (!h.shadow || ids.empty() || !device || !h.desktop_cpu) continue; + for (std::uint32_t i = 0; i < h.count; ++i) { + const std::uint32_t slot_id = h.shadow[i]; + if (!slot_id || !ids.count(slot_id - 1)) continue; + const ViewRecord& record = view_records()[slot_id - 1]; + const D3D12_SHADER_RESOURCE_VIEW_DESC null_view = retire_null_srv_desc(record); + device->CreateShaderResourceView(nullptr, &null_view, + D3D12_CPU_DESCRIPTOR_HANDLE{static_cast(h.desktop_cpu + u64{i} * h.increment)}); + h.shadow[i] = 0; + retire_release_view_ref(reinterpret_cast(record.resource)); + if (h.title_cpu && h.title_cpu != h.desktop_cpu) cleared.push_back({h.title_cpu, i, h.increment, slot_id - 1}); + } + } + for (Wrapper* w : ready) { + if (InterlockedCompareExchange(&w->own().retire_view_refs, 0, 0) > 0) { + w->own().retire_views_stuck = true; + ++stuck; + continue; + } + for (std::uint32_t id : ids) + if (view_records()[id].resource == reinterpret_cast(w)) view_records()[id].resource = 0; + } + } catch (const std::bad_alloc&) { + } + ReleaseSRWLockExclusive(¬e_lock); + ReleaseSRWLockExclusive(&draw_lock); + for (const Cleared& slot : cleared) { + const u64 token = slot.title_cpu + u64{slot.index} * title_descriptor_stride(slot.title_cpu, slot.increment); + if (!title_backed(token, 32) || !x2w_local::writable(reinterpret_cast(token), 32)) continue; + std::uint32_t words[2]; + std::memcpy(words, reinterpret_cast(token), sizeof(words)); + if (words[0] == view_token_magic && words[1] == slot.id) + InterlockedCompareExchange(reinterpret_cast(token), 0, static_cast(view_token_magic)); + } + if (stuck) { + static LONG reported; + if (first_calls(reported, 4)) log("x2w-d3d12 retire: %zu released textures keep an untracked descriptor; they stay retained", stuck); + } +} + + // Never blocks: a contended lock or an unfinished queue leaves the work for the next call. void drain_retired_resources() { if (!InterlockedCompareExchange(&retire_pending, 0, 0)) return; + if (release_retired_views_enabled()) retire_null_ready_views(); constexpr std::size_t batch = 256; struct RetiredDrop { Wrapper* wrapper; @@ -4768,6 +4946,207 @@ void drain_retired_resources() } } +// X2W_D3D12_RETIRE_REASONS=1 (with X2W_D3D12_RELEASE_RETIRED=1 and X2W_D3D12_BUDGET=1): why resources that the guest +// released for good still hold their desktop object. Every final guest Release of a resource with a desktop object is +// remembered here; the heartbeat classifies the ones whose object is still alive, once each, by the first cause that +// applies, in the order of the enum below. Counts and bytes come from the budget ticket. Without the switches nothing +// is recorded and no line is built. +bool retire_reasons_enabled() +{ + static const bool on = release_retired_enabled() && x2w_budget::enabled() && x2w_local::env_on("X2W_D3D12_RETIRE_REASONS"); + return on; +} + +struct ReleasedResource { + ID3D12Resource* real; // identity once the wrapper let go of it; dereferenced only while a hold keeps it alive + LONG frame; // frame_number at the final Release +}; +SRWLOCK retire_diag_lock = SRWLOCK_INIT; // a leaf, never held together with another lock +std::unordered_map retire_diag_released; + +void retire_diag_note_release(Wrapper* w) +{ + if (!w->own().real) return; + AcquireSRWLockExclusive(&retire_diag_lock); + try { + retire_diag_released[w] = {static_cast(w->own().real), frame_number}; + } catch (const std::bad_alloc&) { // a diagnostic only: the resource is then missing from the counts + } + ReleaseSRWLockExclusive(&retire_diag_lock); +} + +enum class Held { view_refs, list_hold, flight, waiting_fence, drain_pending, unqueued, left_view, left_view_copy, + left_residency, left_present, left_hold_missed, never_slot, never_buffer, never_dimension, never_msaa, + never_rt_ds_uav, never_heap_type, never_heap_flags, never_title_memory, never_aliased, never_reserved, + other, count }; +constexpr const char* held_names[] = {"view-refs", "list-hold", "flight", "queued-waiting-fence", "drain-pending", + "unqueued", "left-class:view", "left-class:view-copy", "left-class:residency", "left-class:present", + "left-class:hold-missed", "never-class:slot", "never-class:buffer", "never-class:dimension", "never-class:msaa", + "never-class:rt-ds-uav", "never-class:heap-type", "never-class:heap-flags", "never-class:title-memory", + "never-class:aliased", "never-class:reserved", "other"}; +static_assert(std::size(held_names) == static_cast(Held::count)); +constexpr Held held_left[] = {Held::other, Held::left_view, Held::left_view_copy, Held::left_residency, Held::left_present, + Held::left_hold_missed}; +constexpr Held held_never[] = {Held::never_slot, Held::other, Held::never_buffer, Held::never_dimension, Held::never_msaa, + Held::never_rt_ds_uav, Held::never_heap_type, Held::never_heap_flags, + Held::never_title_memory, Held::never_aliased, Held::never_reserved}; +static_assert(std::size(held_left) == static_cast(RetireLeft::count)); +static_assert(std::size(held_never) == static_cast(RetireNever::count)); + +struct RetireReasonReport { + u64 count[static_cast(Held::count)]; + u64 bytes[static_cast(Held::count)]; + LONG oldest[static_cast(Held::count)]; // frames since the final Release of the oldest entry + u64 visible_count, visible_bytes; // view-refs entries with a descriptor in a shader-visible heap +}; + +void retire_reasons_collect(RetireReasonReport& report) +{ + // 1: which resources a tracked slot-18 descriptor names, and whether one of those lies in a shader-visible heap. + std::unordered_map viewed; + AcquireSRWLockShared(¬e_lock); + try { + for (const HeapInfo& h : heap_infos()) { + if (!h.shadow) continue; + for (std::uint32_t i = 0; i < h.count; ++i) { + const std::uint32_t id = h.shadow[i]; + if (!id || id - 1 >= view_records().size() || view_records()[id - 1].slot != 18 || !view_materialized()[id - 1]) + continue; + bool& visible = viewed[reinterpret_cast(view_records()[id - 1].resource)]; + visible = visible || h.desktop_gpu != 0; + } + } + } catch (const std::bad_alloc&) { + } + ReleaseSRWLockShared(¬e_lock); + + // 2: the remembered final Releases. + std::vector> entries; + AcquireSRWLockShared(&retire_diag_lock); + try { + entries.assign(retire_diag_released.begin(), retire_diag_released.end()); + } catch (const std::bad_alloc&) { + } + ReleaseSRWLockShared(&retire_diag_lock); + + // 3: the retire bookkeeping. own().real is cleared by the drain under this lock, so a non-null pointer read here + // names a desktop object that stays alive for as long as the lock is held. + std::vector gone; + AcquireSRWLockShared(&retire_lock); + try { + std::unordered_map queued; + std::unordered_set listed, flying; + for (const RetiredResource& item : retired_resources) queued.emplace(item.wrapper, &item); + for (const auto& list : retire_list_holds) listed.insert(list.second.begin(), list.second.end()); + for (const RetireFlight& flight : retire_flights) flying.insert(flight.resources.begin(), flight.resources.end()); + const LONG now = frame_number; + const auto add = [&](Held why, const x2w_budget::Ticket* ticket, LONG frame) { + const int i = static_cast(why); + ++report.count[i]; + report.bytes[i] += ticket ? static_cast(ticket->bytes()) : 0; + report.oldest[i] = (std::max)(report.oldest[i], now - frame); + }; + for (const auto& [w, released] : entries) { + if (InterlockedCompareExchange(&w->own().refs, 0, 0) > 0) continue; // referenced again: not released for good + auto* real = static_cast(w->own().real); + if (!real) { + // The drain let go of it; only a list hold or a submission can still keep the desktop object. + const bool by_list = listed.count(released.real) != 0; + if (!by_list && !flying.count(released.real)) { + gone.push_back(w); + continue; + } + x2w_budget::Ticket* ticket = x2w_budget::ticket_of(released.real); + add(by_list ? Held::list_hold : Held::flight, ticket, released.frame); + if (ticket) ticket->Release(); + continue; + } + const x2w_budget::Ticket* ticket = w->own().budget; + Held why = Held::other; + const auto found = queued.find(w); + if (!w->own().retire_when_idle) { + if (w->own().retire_left && w->own().retire_left < static_cast(RetireLeft::count)) + why = held_left[w->own().retire_left]; + else if (w->own().retire_never < static_cast(RetireNever::count)) + why = held_never[w->own().retire_never]; + } else if (found == queued.end()) { + why = Held::unqueued; + } else if (InterlockedCompareExchange(&w->own().retire_view_refs, 0, 0) > 0) { + why = Held::view_refs; + if (const auto view = viewed.find(w); view != viewed.end() && view->second) { + ++report.visible_count; + report.visible_bytes += ticket ? static_cast(ticket->bytes()) : 0; + } + } else if (listed.count(real)) { + why = Held::list_hold; + } else if (flying.count(real)) { + why = Held::flight; + } else { + const RetiredResource& item = *found->second; + bool reached = item.targets.size() <= retire_queues.size(); + for (std::size_t q = 0; q < item.targets.size() && reached; ++q) + reached = retire_queues[q].fence->GetCompletedValue() >= item.targets[q]; + why = reached ? Held::drain_pending : Held::waiting_fence; + } + add(why, ticket, released.frame); + } + } catch (const std::bad_alloc&) { + } + ReleaseSRWLockShared(&retire_lock); + + // 4: forget entries whose desktop object is gone. + if (!gone.empty()) { + AcquireSRWLockExclusive(&retire_diag_lock); + for (Wrapper* w : gone) + if (!w->own().real) retire_diag_released.erase(w); + ReleaseSRWLockExclusive(&retire_diag_lock); + } +} + +// The heartbeat line, or an empty string when the diagnostics are not switched on. unattributed: what the budget still +// counts as retained, less what this classification found (backing heaps, upload and readback objects, anything it cannot see). +std::size_t retire_reasons_line(char* out, std::size_t capacity) +{ + if (!out || !capacity) return 0; + out[0] = 0; + if (!retire_reasons_enabled()) return 0; + RetireReasonReport report{}; + retire_reasons_collect(report); + const x2w_budget::Snapshot budget = x2w_budget::snapshot(); + std::size_t used = 0; + const auto append = [&](const char* format, auto... args) { + if (used + 1 >= capacity) return; + const int n = std::snprintf(out + used, capacity - used, format, args...); + if (n > 0) used = (std::min)(used + static_cast(n), capacity - 1); + }; + append("x2w-retire held:"); + u64 total_count = 0, total_bytes = 0; + for (int i = 0; i < static_cast(Held::count); ++i) { + if (!report.count[i]) continue; + total_count += report.count[i]; + total_bytes += report.bytes[i]; + append(" %s=%llu/%llu(oldest %ldf)", held_names[i], report.count[i], report.bytes[i], report.oldest[i]); + } + if (!total_count) append(" none"); + if (report.visible_count) append(" view-refs-in-visible-heap=%llu/%llu", report.visible_count, report.visible_bytes); + u64 retained_count = 0, retained_bytes = 0; + for (const auto& retained : budget.retained) { + retained_count += retained.objects; + retained_bytes += retained.bytes; + } + append(" total=%llu/%llu unattributed=%lld/%lld", total_count, total_bytes, + static_cast(retained_count) - static_cast(total_count), + static_cast(retained_bytes) - static_cast(total_bytes)); + return used; +} + +// Fixture export (startup_resource_retire_reasons): the line the heartbeat logs, now. Returns its length; 0 and an +// empty string without the switches. +extern "C" __declspec(dllexport) std::size_t x2w_d3d12_retire_reasons_line(char* out, std::size_t capacity) +{ + return retire_reasons_line(out, capacity); +} + // Fixture probe (startup_resource_retire): what still names a resource of the class by its raw desktop pointer, how many // resources the open recording of a list moved out of COMMON, and how many it holds. Counts entries only. struct RetireProbe { @@ -5177,7 +5556,7 @@ HRESULT __stdcall device_create_committed_x(Wrapper* self, const D3D12_HEAP_PROP Wrapper* w = wrap(resource, resource_kind); w->own().budget = x2w_budget::committed(device_of(self), resource, props->Type); w->own().title_memory = title_memory; - w->own().retire_when_idle = retire_class(*props, flags, copy, title_memory); + retire_set_class(w, *props, flags, copy, title_memory); note_resource(w, desc, info.SizeInBytes != ~0ull ? info.SizeInBytes : 0); *out = w; return S_OK; @@ -5381,7 +5760,7 @@ HRESULT __stdcall queue_present(Wrapper* self, UINT planes, const void* plane_pa if (release_retired_enabled() && planes && plane_parameters) { const auto* words = static_cast(plane_parameters); if (x2w_local::readable(words, 0x18) && words[1] >= 1 && x2w_local::readable(reinterpret_cast(words[2]), 8)) - retire_leave_class(*reinterpret_cast(words[2])); + retire_leave_class(*reinterpret_cast(words[2]), RetireLeft::present); } drain_retired_resources(); Timed timed(time_present); @@ -5539,6 +5918,10 @@ HRESULT __stdcall queue_present(Wrapper* self, UINT planes, const void* plane_pa "%lld ms slept", frame, (now - started) / 1000.0, frame * 1000.0 / (now - started ? now - started : 1), frame_waits[0], frame_waits[1], frame_waits[2], frame_waits[3], static_cast(frame_wait_ms)); if (x2w_budget::enabled()) report_budget(static_cast(self->own().real)); + if (retire_reasons_enabled()) { + char line[1536]; + if (retire_reasons_line(line, sizeof(line))) log("%s", line); + } } return S_OK; } diff --git a/src/startup_stubs/resource_budget.h b/src/startup_stubs/resource_budget.h index fc7d9e75ef..6d6217b40a 100644 --- a/src/startup_stubs/resource_budget.h +++ b/src/startup_stubs/resource_budget.h @@ -74,6 +74,10 @@ class Ticket final : public IUnknown { return refs; } + // Read-only identity for the opt-in retire diagnostics (X2W_D3D12_RETIRE_REASONS). + Category category() const { return category_; } + LONG64 bytes() const { return bytes_; } + void begin_use() { AcquireSRWLockExclusive(&lock); @@ -128,6 +132,16 @@ inline Ticket* attach(ID3D12Object* object, Category category, UINT64 bytes, UIN return nullptr; } +// The ticket stored on a live desktop object, with a reference the caller releases, or null. +inline Ticket* ticket_of(ID3D12Object* object) +{ + constexpr GUID key{0x28213cf4, 0x25cf, 0x42be, {0x80, 0xf1, 0xc5, 0x9e, 0x97, 0xf7, 0x20, 0xd1}}; + IUnknown* stored = nullptr; + UINT size = sizeof(stored); + if (FAILED(object->GetPrivateData(key, &size, &stored)) || !stored) return nullptr; + return static_cast(stored); +} + inline Ticket* resource(ID3D12Device* device, ID3D12Resource* resource, Category category) { if (!enabled()) return nullptr; diff --git a/tests/startup_resource_retire_reasons.cpp b/tests/startup_resource_retire_reasons.cpp new file mode 100644 index 0000000000..72524c5199 --- /dev/null +++ b/tests/startup_resource_retire_reasons.cpp @@ -0,0 +1,456 @@ +// X2W_D3D12_RETIRE_REASONS=1 (docs/startup-runtime.md#d3d12-resource-budget): with X2W_D3D12_RELEASE_RETIRED=1 and +// X2W_D3D12_BUDGET=1 the heartbeat names why resources that the guest released for good still hold their desktop +// object. The fixture creates one resource per main reason, releases it, and compares the whole line the export builds +// (the same text the heartbeat logs) with the expected counts and bytes. Bytes come from the desktop allocation size, +// which is what the budget ticket records. +// +// startup_resource_retire_reasons [off|no-retire] +// (X2W_D3D12_BUDGET=1 X2W_D3D12_PERMISSIVE=1 X2W_D3D12_LIST_NOOP=1 X2W_D3D12_RENDER=1 and +// X2W_D3D12_RELEASE_RETIRED=1 X2W_D3D12_RETIRE_REASONS=1; "off" runs without RETIRE_REASONS, "no-retire" without +// RELEASE_RETIRED: the export must then report nothing) +// +// Expected reasons, each with its own resource: +// view-refs (two, one of them in a shader-visible heap), never-class:rt-ds-uav, never-class:msaa, never-class:buffer, +// left-class:view, left-class:residency, left-class:present, list-hold (an unsubmitted closed list), flight (a +// submission held behind a gate), queued-waiting-fence (a release behind the same gate). +// Then the gate opens, the flight and fence entries leave, and the list hold leaves with the Reset of its list. +#include "startup_stubs/resource_budget.h" + +#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) std::size_t x2w_d3d12_retire_reasons_line(char*, std::size_t); + +namespace { + +constexpr DWORD wait_ms = 10000; +constexpr int settle_limit = 200; +constexpr UINT side = 64; + +template +Result invoke(IUnknown* object, unsigned slot, Args... args) +{ + using Call = Result (WINAPI*)(IUnknown*, Args...); + return reinterpret_cast((*reinterpret_cast(object))[slot])(object, args...); +} + +template +ComPtr desktop_object(IUnknown* guest, ID3D12Device* device, IUnknown* object) +{ + constexpr GUID key{0x0e34d52f, 0xd5a5, 0x4790, {0x91, 0xd4, 0x11, 0xa6, 0x7c, 0xbc, 0x2b, 0xc1}}; + ComPtr output; + if (FAILED(invoke(guest, 5, &key, object))) return output; + ComPtr reference; + UINT bytes = sizeof(IUnknown*); + const HRESULT hr = device->GetPrivateData(key, &bytes, reference.GetAddressOf()); + invoke(guest, 5, &key, static_cast(nullptr)); + if (SUCCEEDED(hr)) reference.As(&output); + return output; +} + +bool require(HRESULT hr, const char* stage) +{ + if (FAILED(hr)) std::printf("FAIL: %s hr=0x%08lx\n", stage, static_cast(hr)); + return SUCCEEDED(hr); +} + +ComPtr pick_adapter(IDXGIFactory4* factory, bool warp) +{ + ComPtr adapter; + if (warp) { + factory->EnumWarpAdapter(IID_PPV_ARGS(&adapter)); + return adapter; + } + wchar_t name[128]{}; + GetEnvironmentVariableW(L"XBOX2WINDOWS_ADAPTER", name, static_cast(std::size(name))); + for (UINT i = 0; factory->EnumAdapters1(i, &adapter) == S_OK; ++i, adapter.Reset()) { + DXGI_ADAPTER_DESC1 desc{}; + if (SUCCEEDED(adapter->GetDesc1(&desc)) && !(desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE) && + (!name[0] || std::wcsstr(desc.Description, name)) && + SUCCEEDED(D3D12CreateDevice(adapter.Get(), D3D_FEATURE_LEVEL_12_0, __uuidof(ID3D12Device), nullptr))) + return adapter; + } + return nullptr; +} + +struct Res { + ComPtr guest; + UINT64 bytes = 0; +}; +struct GuestQueue { + ComPtr queue, done; + ComPtr done_real; + UINT64 value = 0; +}; +struct GuestList { + ComPtr allocator, list; +}; +using Tokens = std::map>; + +Tokens parse(const char* line) +{ + Tokens tokens; + for (const char* p = line; *p;) { + while (*p == ' ') ++p; + const char* end = p; + while (*end && *end != ' ') ++end; + char word[128]{}; + std::memcpy(word, p, (std::min)(static_cast(end - p), sizeof(word) - 1)); + char name[96]{}; + long long count = 0, bytes = 0; + if (std::sscanf(word, "%95[^=]=%lld/%lld", name, &count, &bytes) == 3) tokens[name] = {count, bytes}; + p = end; + } + return tokens; +} + +struct Context { + IUnknown* guest; + ID3D12Device* device; + HANDLE event = nullptr; + std::deque pool; + GuestQueue direct, other, gated; + GuestList drain_list; + D3D12_RESOURCE_DESC desc{}; + std::array iid_resource{__uuidof(ID3D12Resource)}; + + bool wait(ID3D12Fence* fence, UINT64 value) + { + if (fence->GetCompletedValue() >= value) return true; + if (FAILED(fence->SetEventOnCompletion(value, event))) return false; + return WaitForSingleObject(event, wait_ms) == WAIT_OBJECT_0; + } + Res& make(const D3D12_RESOURCE_DESC& d, bool through_slot_27 = false) + { + const D3D12_HEAP_PROPERTIES heap{D3D12_HEAP_TYPE_DEFAULT}; + Res& r = pool.emplace_back(); + r.bytes = device->GetResourceAllocationInfo(0, 1, &d).SizeInBytes; + const HRESULT hr = through_slot_27 + ? invoke(guest, 27, &heap, D3D12_HEAP_FLAG_NONE, &d, D3D12_RESOURCE_STATE_COMMON, nullptr, &iid_resource[0], + r.guest.GetAddressOf()) + : invoke(guest, 127, &heap, D3D12_HEAP_FLAG_NONE, &d, D3D12_RESOURCE_STATE_COMMON, nullptr, nullptr, 0u, nullptr, + &iid_resource[0], r.guest.GetAddressOf()); + if (!require(hr, "create resource")) throw 4; + return r; + } + Res& texture(D3D12_RESOURCE_FLAGS flags = D3D12_RESOURCE_FLAG_NONE, UINT samples = 1) + { + D3D12_RESOURCE_DESC d = desc; + d.Flags = flags; + d.SampleDesc = {samples, 0}; + return make(d); + } + Res& buffer() + { + const D3D12_RESOURCE_DESC d{D3D12_RESOURCE_DIMENSION_BUFFER, 0, 65536, 1, 1, 1, DXGI_FORMAT_UNKNOWN, {1, 0}, + D3D12_TEXTURE_LAYOUT_ROW_MAJOR, D3D12_RESOURCE_FLAG_NONE}; + return make(d, true); + } + bool make_queue(GuestQueue& q) + { + const D3D12_COMMAND_QUEUE_DESC d{}; + return require(invoke(guest, 8, &d, &__uuidof(ID3D12CommandQueue), q.queue.GetAddressOf()), "queue") && + require(invoke(guest, 36, UINT64{0}, D3D12_FENCE_FLAG_NONE, &__uuidof(ID3D12Fence), q.done.GetAddressOf()), "done fence") && + (q.done_real = desktop_object(guest, device, q.done.Get())) != nullptr; + } + bool sync(GuestQueue& q) + { + if (!require(invoke(q.queue.Get(), 14, q.done.Get(), ++q.value), "queue signal")) return false; + if (wait(q.done_real.Get(), q.value)) return true; + std::puts("FAIL: a queue did not reach its completion fence"); + return false; + } + bool sync_all() { return sync(direct) && sync(other) && sync(gated); } + bool make_list(GuestList& l) + { + const unsigned list_desc[] = {static_cast(D3D12_COMMAND_LIST_TYPE_DIRECT), 2, 1, 0}; + return require(invoke(guest, 9, D3D12_COMMAND_LIST_TYPE_DIRECT, &__uuidof(ID3D12CommandAllocator), l.allocator.GetAddressOf()), "allocator") && + require(invoke(guest, 73, list_desc, l.allocator.Get(), nullptr, &__uuidof(ID3D12GraphicsCommandList), l.list.GetAddressOf()), "list") && + require(invoke(l.list.Get(), 139, l.allocator.Get(), nullptr), "list reset"); + } + bool reset_list(GuestList& l) + { + ComPtr next; + if (!require(invoke(guest, 9, D3D12_COMMAND_LIST_TYPE_DIRECT, &__uuidof(ID3D12CommandAllocator), next.GetAddressOf()), "allocator")) return false; + if (!require(invoke(l.list.Get(), 139, next.Get(), nullptr), "list reset")) return false; + l.allocator = next; + return true; + } + bool close(GuestList& l) { return require(invoke(l.list.Get(), 9), "list close"); } + void execute(GuestQueue& q, GuestList& l) + { + IUnknown* lists[] = {l.list.Get()}; + invoke(q.queue.Get(), 10, 1u, lists); + } + void drain() { execute(other, drain_list); } + // A closed list that copies source into destination. + bool record_copy(GuestList& l, Res& destination, Res& source) + { + if (!make_list(l)) return false; + invoke(l.list.Get(), 17, destination.guest.Get(), source.guest.Get()); + return close(l); + } + bool line(std::string& text) const + { + char buffer[2048]{}; + if (!x2w_d3d12_retire_reasons_line(buffer, sizeof(buffer))) return false; + text = buffer; + return true; + } +}; + +struct Want { + const char* name; + long long count, bytes; +}; + +// The line carries exactly the wanted tokens, plus total and unattributed. +bool expect(Context& c, const char* stage, std::initializer_list wants, long long unattributed_count = 0) +{ + std::string text; + if (!c.line(text)) { + std::printf("FAIL: %s: the diagnostics line is empty although the switches are on\n", stage); + return false; + } + Tokens want; + long long total_count = 0, total_bytes = 0; + for (const Want& w : wants) { + want[w.name] = {w.count, w.bytes}; + if (std::strcmp(w.name, "view-refs-in-visible-heap")) total_count += w.count, total_bytes += w.bytes; + } + want["total"] = {total_count, total_bytes}; + const Tokens got = parse(text.c_str()); + Tokens compare = got; + const auto un = compare.find("unattributed"); + const bool unattributed_ok = un != compare.end() && un->second.first == unattributed_count; + compare.erase("unattributed"); + if (compare == want && unattributed_ok) return true; + std::printf("FAIL: %s\n got: %s\n want:", stage, text.c_str()); + for (const auto& [name, value] : want) std::printf(" %s=%lld/%lld", name.c_str(), value.first, value.second); + std::printf(" unattributed=%lld/*\n", unattributed_count); + return false; +} + +// Drains until the line matches, without sleeping. +bool settle(Context& c, const char* stage, std::initializer_list wants, long long unattributed_count = 0) +{ + for (int i = 0; i < settle_limit; ++i) { + c.drain(); + std::string text; + Tokens want; + long long total_count = 0, total_bytes = 0; + for (const Want& w : wants) { + want[w.name] = {w.count, w.bytes}; + if (std::strcmp(w.name, "view-refs-in-visible-heap")) total_count += w.count, total_bytes += w.bytes; + } + want["total"] = {total_count, total_bytes}; + if (c.line(text)) { + Tokens got = parse(text.c_str()); + const auto un = got.find("unattributed"); + const bool unattributed_ok = un != got.end() && un->second.first == unattributed_count; + got.erase("unattributed"); + if (got == want && unattributed_ok) return true; + } + } + return expect(c, stage, wants, unattributed_count); +} + +bool scenario(Context& c) +{ + const struct { + D3D12_DESCRIPTOR_HEAP_DESC desc; + UINT64 backing, bytes; + } visible_heap{{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 1, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE}, 0, 0}, + hidden_heap{{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 1}, 0, 0}; + ComPtr visible, hidden; + if (!require(invoke(c.guest, 14, &visible_heap, &__uuidof(ID3D12DescriptorHeap), visible.GetAddressOf()), "visible heap") || + !require(invoke(c.guest, 14, &hidden_heap, &__uuidof(ID3D12DescriptorHeap), hidden.GetAddressOf()), "hidden heap")) + return false; + D3D12_SHADER_RESOURCE_VIEW_DESC srv{}; + srv.Format = DXGI_FORMAT_R8G8B8A8_UNORM; + srv.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; + srv.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + srv.Texture2D.MipLevels = 1; + + if (!c.sync_all()) return false; // every queue has a completion point before anything is released + Res& A = c.texture(); + Res& B = c.texture(); + invoke(c.guest, 18, A.guest.Get(), &srv, invoke(visible.Get(), 9)); + invoke(c.guest, 18, B.guest.Get(), &srv, invoke(hidden.Get(), 9)); + const UINT64 tb = A.bytes; + A.guest.Reset(); + B.guest.Reset(); + + Res& rt = c.texture(D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET); + Res& msaa = c.texture(D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET, 4); + Res& buf = c.buffer(); + const UINT64 rt_bytes = rt.bytes, msaa_bytes = msaa.bytes, buf_bytes = buf.bytes; + rt.guest.Reset(); + msaa.guest.Reset(); + buf.guest.Reset(); + + // A view whose descriptor handle the shim cannot translate takes the resource out of the class. + Res& viewed = c.texture(); + invoke(c.guest, 18, viewed.guest.Get(), &srv, UINT64{0}); + viewed.guest.Reset(); + Res& resident = c.texture(); + IUnknown* residents[] = {resident.guest.Get()}; + if (!require(invoke(c.guest, 34, 1u, residents), "MakeResident")) return false; + resident.guest.Reset(); + Res& presented = c.texture(); + void* surface = presented.guest.Get(); + const UINT64 plane[10]{0, 1, reinterpret_cast(&surface)}; + const UINT64 present_parameters[8]{}; + if (!require(invoke(c.direct.queue.Get(), 32, 1u, plane, present_parameters), "Present")) return false; + presented.guest.Reset(); + + // A released source that a closed, unsubmitted list names. + GuestList listed; + Res& list_destination = c.texture(); + Res& list_source = c.texture(); + if (!c.record_copy(listed, list_destination, list_source)) return false; + list_source.guest.Reset(); + if (!c.sync_all()) return false; + for (int i = 0; i < 4; ++i) c.drain(); + + // A submission behind a gate, its list reset, then two releases behind the same gate. + ComPtr gate; + if (!require(invoke(c.guest, 36, UINT64{0}, D3D12_FENCE_FLAG_NONE, &__uuidof(ID3D12Fence), gate.GetAddressOf()), "gate fence") || + !require(invoke(c.gated.queue.Get(), 17, gate.Get(), UINT64{1}), "queue wait")) + return false; + GuestList flying; + Res& fly_destination = c.texture(); + Res& fly_source = c.texture(); + if (!c.record_copy(flying, fly_destination, fly_source)) return false; + c.execute(c.gated, flying); + fly_source.guest.Reset(); + if (!c.reset_list(flying)) return false; + Res& waiting = c.texture(); + waiting.guest.Reset(); + if (!c.sync(c.direct) || !c.sync(c.other)) return false; + for (int i = 0; i < 4; ++i) c.drain(); + + if (!expect(c, "every reason once", + {{"view-refs", 2, static_cast(2 * tb)}, {"view-refs-in-visible-heap", 1, static_cast(tb)}, + {"never-class:rt-ds-uav", 1, static_cast(rt_bytes)}, + {"never-class:msaa", 1, static_cast(msaa_bytes)}, + {"never-class:buffer", 1, static_cast(buf_bytes)}, + {"left-class:view", 1, static_cast(tb)}, {"left-class:residency", 1, static_cast(tb)}, + {"left-class:present", 1, static_cast(tb)}, {"list-hold", 1, static_cast(tb)}, + {"flight", 1, static_cast(tb)}, {"queued-waiting-fence", 1, static_cast(tb)}})) + return false; + std::puts("1 one resource per reason: view-refs, rt-ds-uav, msaa, buffer, left view/residency/present, list-hold, flight, fence"); + + if (!require(invoke(gate.Get(), 10, UINT64{1}), "gate signal") || !c.sync_all()) return false; + if (!settle(c, "gate opened", + {{"view-refs", 2, static_cast(2 * tb)}, {"view-refs-in-visible-heap", 1, static_cast(tb)}, + {"never-class:rt-ds-uav", 1, static_cast(rt_bytes)}, + {"never-class:msaa", 1, static_cast(msaa_bytes)}, + {"never-class:buffer", 1, static_cast(buf_bytes)}, + {"left-class:view", 1, static_cast(tb)}, {"left-class:residency", 1, static_cast(tb)}, + {"left-class:present", 1, static_cast(tb)}, {"list-hold", 1, static_cast(tb)}})) + return false; + std::puts("2 gate opened: flight and queued-waiting-fence leave, the rest stays"); + + if (!c.reset_list(listed)) return false; + if (!settle(c, "list reset", + {{"view-refs", 2, static_cast(2 * tb)}, {"view-refs-in-visible-heap", 1, static_cast(tb)}, + {"never-class:rt-ds-uav", 1, static_cast(rt_bytes)}, + {"never-class:msaa", 1, static_cast(msaa_bytes)}, + {"never-class:buffer", 1, static_cast(buf_bytes)}, + {"left-class:view", 1, static_cast(tb)}, {"left-class:residency", 1, static_cast(tb)}, + {"left-class:present", 1, static_cast(tb)}})) + return false; + std::puts("3 list reset: the list hold leaves"); + + // Overwriting the shader-visible descriptor drops one view reference; the resource then retires. + Res& replacement = c.texture(); + invoke(c.guest, 18, replacement.guest.Get(), &srv, invoke(visible.Get(), 9)); + if (!settle(c, "descriptor overwritten", + {{"view-refs", 1, static_cast(tb)}, + {"never-class:rt-ds-uav", 1, static_cast(rt_bytes)}, + {"never-class:msaa", 1, static_cast(msaa_bytes)}, + {"never-class:buffer", 1, static_cast(buf_bytes)}, + {"left-class:view", 1, static_cast(tb)}, {"left-class:residency", 1, static_cast(tb)}, + {"left-class:present", 1, static_cast(tb)}})) + return false; + std::puts("4 descriptor overwritten: the visible-heap view-refs entry retires, the hidden-heap one stays"); + return true; +} + +// Negative control: the same kind of release with the switches off reports nothing. +bool nothing_reported(Context& c) +{ + if (!c.sync_all()) return false; + Res& r = c.texture(); + r.guest.Reset(); + Res& g = c.texture(D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET); + g.guest.Reset(); + for (int i = 0; i < 4; ++i) c.drain(); + char buffer[256]; + std::memset(buffer, 'x', sizeof(buffer)); + const std::size_t length = x2w_d3d12_retire_reasons_line(buffer, sizeof(buffer)); + if (length || buffer[0]) { + std::printf("FAIL: the diagnostics reported %zu bytes without their switches: %s\n", length, buffer); + return false; + } + return true; +} + +} // namespace + +int main(int argc, char** argv) +{ + if (argc < 2 || argc > 3 || (std::strcmp(argv[1], "warp") && std::strcmp(argv[1], "hardware")) || + (argc == 3 && std::strcmp(argv[2], "off") && std::strcmp(argv[2], "no-retire"))) + return 2; + const auto env_on = [](const char* name) { + char value[2]{}; + return GetEnvironmentVariableA(name, value, sizeof(value)) == 1 && value[0] == '1'; + }; + const bool off = argc == 3 && !std::strcmp(argv[2], "off"); + const bool no_retire = argc == 3 && !std::strcmp(argv[2], "no-retire"); + if (env_on("X2W_D3D12_RETIRE_REASONS") != !off || env_on("X2W_D3D12_RELEASE_RETIRED") != !no_retire || + !env_on("X2W_D3D12_BUDGET")) { + std::puts("FAIL: the environment does not match the requested mode"); + return 2; + } + ComPtr factory; + if (FAILED(CreateDXGIFactory1(IID_PPV_ARGS(&factory)))) return 3; + const auto adapter = pick_adapter(factory.Get(), std::strcmp(argv[1], "warp") == 0); + if (!adapter) return 77; + ComPtr guest; + ComPtr device; + std::array parameters{}; + if (!require(D3D12XboxCreateDevice(adapter.Get(), parameters.data(), __uuidof(ID3D12Device), + reinterpret_cast(guest.GetAddressOf())), "Xbox device") || + !require(D3D12CreateDevice(adapter.Get(), D3D_FEATURE_LEVEL_12_0, IID_PPV_ARGS(&device)), "desktop device")) + return 3; + std::printf("mode=%s\n", off ? "off" : no_retire ? "no-retire" : "on"); + Context c{guest.Get(), device.Get()}; + try { + c.desc = {D3D12_RESOURCE_DIMENSION_TEXTURE2D, 0, side, side, 1, 1, DXGI_FORMAT_R8G8B8A8_UNORM, {1, 0}, + D3D12_TEXTURE_LAYOUT_UNKNOWN, D3D12_RESOURCE_FLAG_NONE}; + c.event = CreateEventW(nullptr, FALSE, FALSE, nullptr); + if (!c.event || !c.make_queue(c.direct) || !c.make_queue(c.other) || !c.make_queue(c.gated)) return 4; + if (!c.make_list(c.drain_list) || !c.close(c.drain_list)) return 4; + if (!(off || no_retire ? nothing_reported(c) : scenario(c))) return 5; + } catch (int code) { + return code; + } + if (FAILED(device->GetDeviceRemovedReason())) return 4; + std::puts(off || no_retire ? "retire-reasons off checks passed" : "retire-reasons checks passed"); + return 0; +} diff --git a/tests/startup_resource_retire_views.cpp b/tests/startup_resource_retire_views.cpp new file mode 100644 index 0000000000..6db82d2895 --- /dev/null +++ b/tests/startup_resource_retire_views.cpp @@ -0,0 +1,657 @@ +// X2W_D3D12_RELEASE_RETIRED_VIEWS=1 (with X2W_D3D12_RELEASE_RETIRED=1, Refs #2379): a released committed 2D texture that +// only tracked slot-18 descriptor slots keep alive is freed once those slots hold null descriptors. The title never has +// to overwrite them. +// +// startup_resource_retire_views [keep] +// +// `keep` is the negative control: the views switch is off (or the retire switch is, with the views switch set), so a +// released texture stays retained exactly as before and its descriptors keep naming it. +// +// The fixture reads the desktop descriptors the shim wrote: a compute shader on the fixture's own desktop queue loads +// texel (0,0) through a slot of a guest heap (bound directly when the heap is shader-visible, copied into a probe +// heap when it is not). A filled texture reads back non-zero, a null descriptor reads back zero. +// Cases: +// 1 single SRV in a shader-visible heap, never overwritten: freed after the release fences, descriptor null, view +// token in title descriptor memory cleared. +// 2 the same texture also copied into a second (non-shader-visible) heap, release behind a gated queue: nothing is +// touched until the gate opens, then both copies are null and the texture is freed (copies are handled). +// 3 a closed list recorded a CopyResource from the texture, submitted behind a gate: descriptors are nulled but the +// desktop object lives until the submission's fence, and the copy still reads the texels. +// 4 a closed, never submitted list names the texture: nulled, retained until the recording is discarded. +// 5 a live texture's descriptor is never touched. +#include "startup_stubs/resource_budget.h" + +#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) BOOL x2w_d3d12_budget_snapshot(x2w_budget::Snapshot*, SIZE_T); + +namespace { +using namespace x2w_budget; + +constexpr UINT side = 64, pitch = 256, image_bytes = side * pitch; +constexpr DWORD wait_ms = 10000; +constexpr int settle_limit = 200; +constexpr std::uint32_t view_token_magic = 0x56573258; // "X2WV", d3d12_capture.inl + +template +Result invoke(IUnknown* object, unsigned slot, Args... args) +{ + using Call = Result (WINAPI*)(IUnknown*, Args...); + return reinterpret_cast((*reinterpret_cast(object))[slot])(object, args...); +} + +template +ComPtr desktop_object(IUnknown* guest, ID3D12Device* device, IUnknown* object) +{ + constexpr GUID key{0x0e34d52f, 0xd5a5, 0x4790, {0x91, 0xd4, 0x11, 0xa6, 0x7c, 0xbc, 0x2b, 0xc1}}; + ComPtr output; + if (FAILED(invoke(guest, 5, &key, object))) return output; + ComPtr reference; + UINT bytes = sizeof(IUnknown*); + const HRESULT hr = device->GetPrivateData(key, &bytes, reference.GetAddressOf()); + invoke(guest, 5, &key, static_cast(nullptr)); + if (SUCCEEDED(hr)) reference.As(&output); + return output; +} + +bool require(HRESULT hr, const char* stage) +{ + if (FAILED(hr)) std::printf("FAIL: %s hr=0x%08lx\n", stage, static_cast(hr)); + return SUCCEEDED(hr); +} + +std::uint8_t pattern_byte(int seed, UINT i) { return static_cast(i * 7 + seed * 13 + 1); } + +ComPtr pick_adapter(IDXGIFactory4* factory, bool warp) +{ + ComPtr adapter; + if (warp) { + factory->EnumWarpAdapter(IID_PPV_ARGS(&adapter)); + return adapter; + } + wchar_t name[128]{}; + GetEnvironmentVariableW(L"XBOX2WINDOWS_ADAPTER", name, static_cast(std::size(name))); + for (UINT i = 0; factory->EnumAdapters1(i, &adapter) == S_OK; ++i, adapter.Reset()) { + DXGI_ADAPTER_DESC1 desc{}; + if (SUCCEEDED(adapter->GetDesc1(&desc)) && !(desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE) && + (!name[0] || std::wcsstr(desc.Description, name)) && + SUCCEEDED(D3D12CreateDevice(adapter.Get(), D3D_FEATURE_LEVEL_12_0, __uuidof(ID3D12Device), nullptr))) + return adapter; + } + return nullptr; +} + +struct Res { + ComPtr guest; + const char* name = ""; + UINT64 bytes = 0; + bool released = false; + bool freed = false; +}; + +struct GuestList { + ComPtr allocator, list; +}; + +struct GuestQueue { + ComPtr queue, done; + ComPtr done_real; + UINT64 value = 0; +}; + +struct GuestHeap { + ComPtr guest; + ComPtr real; + UINT64 cpu = 0, gpu = 0; + bool visible = false; +}; + +constexpr char probe_shader[] = R"( +Texture2D source : register(t0); +RWByteAddressBuffer result : register(u0); +[numthreads(1, 1, 1)] void main() +{ + result.Store4(0, asuint(source.Load(int3(0, 0, 0)))); +} +)"; + +struct Context { + IUnknown* guest; + ID3D12Device* device; + ComPtr own_queue; + ComPtr own_allocator; + ComPtr own_list; + ComPtr own_fence; + UINT64 own_value = 0; + HANDLE event = nullptr; + ComPtr upload, readback, probe_out; + ComPtr probe_root; + ComPtr probe_pso; + ComPtr probe_heap; + UINT increment = 0; + Snapshot base{}; + std::deque pool; + GuestQueue direct, gated; + GuestList drain_list; + D3D12_RESOURCE_DESC desc{}; + UINT64 texture_bytes = 0; + std::array iid_resource{__uuidof(ID3D12Resource)}; + + bool wait(ID3D12Fence* fence, UINT64 value) + { + if (fence->GetCompletedValue() >= value) return true; + if (FAILED(fence->SetEventOnCompletion(value, event))) return false; + return WaitForSingleObject(event, wait_ms) == WAIT_OBJECT_0; + } + bool own_run() + { + if (!require(own_list->Close(), "own list close")) return false; + ID3D12CommandList* lists[] = {own_list.Get()}; + own_queue->ExecuteCommandLists(1, lists); + if (!require(own_queue->Signal(own_fence.Get(), ++own_value), "own signal")) return false; + if (wait(own_fence.Get(), own_value)) return true; + std::puts("FAIL: own queue timed out"); + return false; + } + D3D12_TEXTURE_COPY_LOCATION footprint(ID3D12Resource* buffer) const + { + D3D12_TEXTURE_COPY_LOCATION location{buffer, D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, {}}; + location.PlacedFootprint.Footprint = {DXGI_FORMAT_R8G8B8A8_UNORM, side, side, 1, pitch}; + return location; + } + static D3D12_TEXTURE_COPY_LOCATION footprint_tex(ID3D12Resource* tex) + { + return {tex, D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, {0}}; + } + bool make_queue(GuestQueue& q) + { + const D3D12_COMMAND_QUEUE_DESC qd{D3D12_COMMAND_LIST_TYPE_DIRECT, 0, D3D12_COMMAND_QUEUE_FLAG_NONE, 0}; + if (!require(invoke(guest, 8, &qd, &__uuidof(ID3D12CommandQueue), q.queue.GetAddressOf()), "queue") || + !require(invoke(guest, 36, UINT64{0}, D3D12_FENCE_FLAG_NONE, &__uuidof(ID3D12Fence), q.done.GetAddressOf()), "fence")) + return false; + q.done_real = desktop_object(guest, device, q.done.Get()); + return q.done_real != nullptr; + } + bool sync(GuestQueue& q) + { + if (!require(invoke(q.queue.Get(), 14, q.done.Get(), ++q.value), "queue signal")) return false; + if (wait(q.done_real.Get(), q.value)) return true; + std::puts("FAIL: guest queue timed out"); + return false; + } + bool make_list(GuestList& l) + { + const unsigned list_desc[] = {static_cast(D3D12_COMMAND_LIST_TYPE_DIRECT), 2, 1, 0}; + return require(invoke(guest, 9, D3D12_COMMAND_LIST_TYPE_DIRECT, &__uuidof(ID3D12CommandAllocator), + l.allocator.GetAddressOf()), "allocator") && + require(invoke(guest, 73, list_desc, l.allocator.Get(), nullptr, + &__uuidof(ID3D12GraphicsCommandList), l.list.GetAddressOf()), "command list") && + require(invoke(l.list.Get(), 139, l.allocator.Get(), nullptr), "list reset"); + } + bool close(GuestList& l) { return require(invoke(l.list.Get(), 9), "list close"); } + HRESULT reset_list(GuestList& l) + { + ComPtr next; + if (!require(invoke(guest, 9, D3D12_COMMAND_LIST_TYPE_DIRECT, &__uuidof(ID3D12CommandAllocator), + next.GetAddressOf()), "allocator")) + return E_FAIL; + const HRESULT hr = invoke(l.list.Get(), 139, next.Get(), nullptr); + if (SUCCEEDED(hr)) l.allocator = next; + return hr; + } + void execute(GuestQueue& q, GuestList& l) + { + IUnknown* lists[] = {l.list.Get()}; + invoke(q.queue.Get(), 10, 1u, lists); + } + Res& make_committed(const char* name) + { + const D3D12_HEAP_PROPERTIES heap{D3D12_HEAP_TYPE_DEFAULT}; + D3D12_RESOURCE_DESC d = desc; + Res& r = pool.emplace_back(); + r.name = name; + r.bytes = texture_bytes; + if (!require(invoke(guest, 127, &heap, D3D12_HEAP_FLAG_NONE, &d, D3D12_RESOURCE_STATE_COMMON, nullptr, nullptr, 0u, + nullptr, &iid_resource[0], r.guest.GetAddressOf()), name)) + throw 4; + return r; + } + bool fill_desktop(IUnknown* resource, int seed) + { + const auto real = desktop_object(guest, device, resource); + if (!real) return false; + void* mapped = nullptr; + const D3D12_RANGE none{}; + if (!require(upload->Map(0, &none, &mapped), "upload map")) return false; + auto* dst = static_cast(mapped); + for (UINT i = 0; i < image_bytes; ++i) dst[i] = pattern_byte(seed, i); + upload->Unmap(0, nullptr); + if (!require(own_allocator->Reset(), "own allocator") || !require(own_list->Reset(own_allocator.Get(), nullptr), "own list")) + return false; + own_list->CopyTextureRegion(&footprint_tex(real.Get()), 0, 0, 0, &footprint(upload.Get()), nullptr); + D3D12_RESOURCE_BARRIER b{D3D12_RESOURCE_BARRIER_TYPE_TRANSITION, D3D12_RESOURCE_BARRIER_FLAG_NONE, {}}; + b.Transition = {real.Get(), D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, D3D12_RESOURCE_STATE_COPY_DEST, + D3D12_RESOURCE_STATE_COMMON}; + own_list->ResourceBarrier(1, &b); + return own_run(); + } + bool holds(IUnknown* resource, int seed, const char* what) + { + const auto real = desktop_object(guest, device, resource); + if (!real) return false; + if (!require(own_allocator->Reset(), "own allocator") || !require(own_list->Reset(own_allocator.Get(), nullptr), "own list")) + return false; + D3D12_RESOURCE_BARRIER b{D3D12_RESOURCE_BARRIER_TYPE_TRANSITION, D3D12_RESOURCE_BARRIER_FLAG_NONE, {}}; + b.Transition = {real.Get(), D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, D3D12_RESOURCE_STATE_COMMON, + D3D12_RESOURCE_STATE_COPY_SOURCE}; + own_list->ResourceBarrier(1, &b); + own_list->CopyTextureRegion(&footprint(readback.Get()), 0, 0, 0, &footprint_tex(real.Get()), nullptr); + b.Transition.StateBefore = D3D12_RESOURCE_STATE_COPY_SOURCE; + b.Transition.StateAfter = D3D12_RESOURCE_STATE_COMMON; + own_list->ResourceBarrier(1, &b); + if (!own_run()) return false; + void* mapped = nullptr; + const D3D12_RANGE all{0, image_bytes}; + if (!require(readback->Map(0, &all, &mapped), "readback map")) return false; + const auto* src = static_cast(mapped); + UINT mismatches = 0; + for (UINT y = 0; y < side; ++y) + for (UINT x = 0; x < side * 4; ++x) + if (src[y * pitch + x] != pattern_byte(seed, y * pitch + x)) ++mismatches; + readback->Unmap(0, nullptr); + if (mismatches) { + std::printf("FAIL: %s readback had %u mismatched bytes\n", what, mismatches); + return false; + } + return true; + } + void release(Res& r) + { + r.guest.Reset(); + r.released = true; + } + void drain_once() + { + IUnknown* lists[] = {drain_list.list.Get()}; + invoke(direct.queue.Get(), 10, 1u, lists); + } + bool expect(const char* stage, const char* fail) const + { + Snapshot now{}; + if (!x2w_d3d12_budget_snapshot(&now, sizeof(now))) return false; + UINT64 live_n = base.live[texture].objects, ret_n = base.retained[texture].objects; + UINT64 live_b = base.live[texture].bytes, ret_b = base.retained[texture].bytes; + for (const Res& r : pool) { + if (!r.released) { + live_b += r.bytes; + ++live_n; + } else if (!r.freed) { + ret_b += r.bytes; + ++ret_n; + } + } + const auto& got_live = now.live[texture]; + const auto& got_ret = now.retained[texture]; + if (got_live.bytes == live_b && got_live.objects == live_n && got_ret.bytes == ret_b && got_ret.objects == ret_n) + return true; + std::printf("FAIL: %s\n stage '%s' live=%llu/%llu expected=%llu/%llu retained=%llu/%llu expected=%llu/%llu\n", + fail, stage, got_live.bytes, got_live.objects, live_b, live_n, + got_ret.bytes, got_ret.objects, ret_b, ret_n); + return false; + } + bool stays(const char* stage, const char* fail) + { + drain_once(); + return sync(direct) && expect(stage, fail); + } + bool settle(const char* stage, const char* fail) + { + for (int i = 0; i < settle_limit; ++i) { + drain_once(); + Snapshot now{}; + if (!x2w_d3d12_budget_snapshot(&now, sizeof(now))) return false; + UINT64 ret_n = base.retained[texture].objects; + for (const Res& r : pool) if (r.released && !r.freed) ++ret_n; + if (now.retained[texture].objects == ret_n) return expect(stage, fail); + } + return expect(stage, fail); + } + bool make_heap(GuestHeap& h, UINT count, bool visible) + { + const struct { + D3D12_DESCRIPTOR_HEAP_DESC desc; + UINT64 backing, bytes; + } request{{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, count, + visible ? D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE : D3D12_DESCRIPTOR_HEAP_FLAG_NONE}, 0, 0}; + if (!require(invoke(guest, 14, &request, &__uuidof(ID3D12DescriptorHeap), h.guest.GetAddressOf()), "guest heap")) + return false; + h.real = desktop_object(guest, device, h.guest.Get()); + if (!h.real) { + std::puts("FAIL: guest heap has no desktop object"); + return false; + } + h.cpu = invoke(h.guest.Get(), 9); + h.gpu = visible ? invoke(h.guest.Get(), 10) : 0; + h.visible = visible; + return true; + } + // Loads texel (0,0) through the desktop descriptor behind slot `index` of the guest heap. + bool read_slot(const GuestHeap& h, UINT index, float (&texel)[4]) + { + if (!require(own_allocator->Reset(), "probe allocator") || !require(own_list->Reset(own_allocator.Get(), nullptr), "probe list")) + return false; + ID3D12DescriptorHeap* bound = probe_heap.Get(); + D3D12_GPU_DESCRIPTOR_HANDLE gpu = probe_heap->GetGPUDescriptorHandleForHeapStart(); + if (h.visible) { + bound = h.real.Get(); + gpu = h.real->GetGPUDescriptorHandleForHeapStart(); + gpu.ptr += std::uint64_t{index} * increment; + } else { + D3D12_CPU_DESCRIPTOR_HANDLE src = h.real->GetCPUDescriptorHandleForHeapStart(); + src.ptr += std::uint64_t{index} * increment; + device->CopyDescriptorsSimple(1, probe_heap->GetCPUDescriptorHandleForHeapStart(), src, + D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); + } + own_list->SetDescriptorHeaps(1, &bound); + own_list->SetComputeRootSignature(probe_root.Get()); + own_list->SetPipelineState(probe_pso.Get()); + own_list->SetComputeRootDescriptorTable(0, gpu); + own_list->SetComputeRootUnorderedAccessView(1, probe_out->GetGPUVirtualAddress()); + own_list->Dispatch(1, 1, 1); + D3D12_RESOURCE_BARRIER b{D3D12_RESOURCE_BARRIER_TYPE_TRANSITION, D3D12_RESOURCE_BARRIER_FLAG_NONE, {}}; + b.Transition = {probe_out.Get(), D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + D3D12_RESOURCE_STATE_COPY_SOURCE}; + own_list->ResourceBarrier(1, &b); + own_list->CopyBufferRegion(readback.Get(), 0, probe_out.Get(), 0, 16); + b.Transition.StateBefore = D3D12_RESOURCE_STATE_COPY_SOURCE; + b.Transition.StateAfter = D3D12_RESOURCE_STATE_UNORDERED_ACCESS; + own_list->ResourceBarrier(1, &b); + if (!own_run()) return false; + void* mapped = nullptr; + const D3D12_RANGE all{0, 16}; + if (!require(readback->Map(0, &all, &mapped), "probe readback map")) return false; + std::memcpy(texel, mapped, sizeof(texel)); + readback->Unmap(0, nullptr); + return true; + } + // want_null: the slot must read as null (all zero); otherwise it must read the texture's texels (not all zero). + bool slot_is(const GuestHeap& h, UINT index, bool want_null, const char* what) + { + float texel[4]{}; + if (!read_slot(h, index, texel)) return false; + const bool zero = texel[0] == 0.0f && texel[1] == 0.0f && texel[2] == 0.0f && texel[3] == 0.0f; + if (zero == want_null) return true; + std::printf("FAIL: %s: descriptor reads %.3f %.3f %.3f %.3f, expected %s\n", what, texel[0], texel[1], texel[2], + texel[3], want_null ? "null (all zero)" : "texels of the texture"); + return false; + } + // The view token the shim wrote into title descriptor memory for a slot (first word). + static std::uint32_t token_word(const GuestHeap& h, UINT index, UINT stride) + { + std::uint32_t word = 0; + std::memcpy(&word, reinterpret_cast(h.cpu + std::uint64_t{index} * stride), sizeof(word)); + return word; + } +}; + +D3D12_SHADER_RESOURCE_VIEW_DESC texture_view() +{ + D3D12_SHADER_RESOURCE_VIEW_DESC srv{}; + srv.Format = DXGI_FORMAT_R8G8B8A8_UNORM; + srv.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; + srv.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + srv.Texture2D.MipLevels = 1; + return srv; +} + +// 1: one SRV in a shader-visible heap, never overwritten. +bool case1_single_view(Context& c, bool on, GuestHeap& visible) +{ + Res& T = c.make_committed("T1"); + if (!c.fill_desktop(T.guest.Get(), 1)) return false; + const auto srv = texture_view(); + invoke(c.guest, 18, T.guest.Get(), &srv, visible.cpu); + if (!c.slot_is(visible, 0, false, "case 1 control: live texture's descriptor") || + Context::token_word(visible, 0, c.increment) != view_token_magic) { + std::puts("FAIL: case 1 control: live texture's view token missing"); + return false; + } + c.release(T); + if (on) { + T.freed = true; + if (!c.settle("T1 freed with its descriptor never overwritten", "T1 kept although only a descriptor names it")) + return false; + if (!c.slot_is(visible, 0, true, "case 1: descriptor after the free")) return false; + if (Context::token_word(visible, 0, c.increment) == view_token_magic) { + std::puts("FAIL: case 1: view token still in title descriptor memory after the free"); + return false; + } + return true; + } + for (int i = 0; i < 8; ++i) + if (!c.stays("T1 released, views switch off", "T1 freed without the views switch")) return false; + return c.slot_is(visible, 0, false, "case 1 control: descriptor with the views switch off"); +} + +// 2: a copy in a second heap, release behind a gated queue. +bool case2_copy_and_gate(Context& c, bool on, GuestHeap& visible, GuestHeap& staging) +{ + Res& T = c.make_committed("T2"); + if (!c.fill_desktop(T.guest.Get(), 2)) return false; + const auto srv = texture_view(); + invoke(c.guest, 18, T.guest.Get(), &srv, visible.cpu + c.increment); + invoke(c.guest, 24, 1u, staging.cpu, visible.cpu + c.increment, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); + ComPtr gate; + if (!require(invoke(c.guest, 36, UINT64{0}, D3D12_FENCE_FLAG_NONE, &__uuidof(ID3D12Fence), gate.GetAddressOf()), "gate") || + !require(invoke(c.gated.queue.Get(), 17, gate.Get(), UINT64{1}), "wait")) + return false; + c.release(T); + for (int i = 0; i < 8; ++i) + if (!c.stays("T2 released behind a closed gate", "T2 freed before the release fences passed")) return false; + if (!c.slot_is(visible, 1, false, "case 2: original descriptor before the gate opens") || + !c.slot_is(staging, 0, false, "case 2: copied descriptor before the gate opens")) + return false; + if (!require(invoke(gate.Get(), 10, UINT64{1}), "signal gate") || !c.sync(c.gated)) return false; + if (!on) { + for (int i = 0; i < 8; ++i) + if (!c.stays("T2 released, views switch off", "T2 freed without the views switch")) return false; + return c.slot_is(staging, 0, false, "case 2 control: copied descriptor with the views switch off"); + } + T.freed = true; + if (!c.settle("T2 freed after the gate opened", "T2 kept after its fences passed")) return false; + return c.slot_is(visible, 1, true, "case 2: original descriptor after the free") && + c.slot_is(staging, 0, true, "case 2: copied descriptor after the free"); +} + +// 3 and 4: lists that name the texture. +bool case3_list_holds(Context& c, bool on, GuestHeap& visible) +{ + Res& T3 = c.make_committed("T3"); + Res& D3 = c.make_committed("D3"); + Res& T4 = c.make_committed("T4"); + Res& D4 = c.make_committed("D4"); + if (!c.fill_desktop(T3.guest.Get(), 3) || !c.fill_desktop(D3.guest.Get(), 99) || !c.fill_desktop(T4.guest.Get(), 4) || + !c.fill_desktop(D4.guest.Get(), 99)) + return false; + const auto srv = texture_view(); + invoke(c.guest, 18, T3.guest.Get(), &srv, visible.cpu + 2 * c.increment); + invoke(c.guest, 18, T4.guest.Get(), &srv, visible.cpu + 3 * c.increment); + GuestList submitted, discarded; + if (!c.make_list(submitted) || !c.make_list(discarded)) return false; + invoke(submitted.list.Get(), 17, D3.guest.Get(), T3.guest.Get()); + invoke(discarded.list.Get(), 17, D4.guest.Get(), T4.guest.Get()); + if (!c.close(submitted) || !c.close(discarded)) return false; + c.release(T3); + c.release(T4); + for (int i = 0; i < 8; ++i) + if (!c.stays("T3/T4 released behind closed lists", "a texture left the budget while a closed list names it")) + return false; + if (on && (!c.slot_is(visible, 2, true, "case 3: descriptor of the listed texture T3") || + !c.slot_is(visible, 3, true, "case 4: descriptor of the listed texture T4"))) + return false; + ComPtr gate; + if (!require(invoke(c.guest, 36, UINT64{0}, D3D12_FENCE_FLAG_NONE, &__uuidof(ID3D12Fence), gate.GetAddressOf()), "gate3") || + !require(invoke(c.gated.queue.Get(), 17, gate.Get(), UINT64{1}), "wait3")) + return false; + c.execute(c.gated, submitted); + if (!SUCCEEDED(c.reset_list(submitted))) return false; + for (int i = 0; i < 8; ++i) + if (!c.stays("T3 held by a gated submission", "T3 left the budget while its submission is in flight")) return false; + if (!SUCCEEDED(c.reset_list(discarded))) return false; // discards the recording that was never submitted + if (on) T4.freed = true; + if (!c.settle("T4 freed after its recording was discarded", "T4 kept after its recording was discarded")) return false; + if (!require(invoke(gate.Get(), 10, UINT64{1}), "signal gate3") || !c.sync(c.gated)) return false; + if (on) T3.freed = true; + if (!c.settle("T3 freed after its submission's fence", "T3 kept after its submission's fence passed")) return false; + // The copy ran against the live texels, not against anything freed or nulled. + return c.holds(D3.guest.Get(), 3, "D3 copy of T3 recorded before the release"); +} + +// 5: a live texture is never touched. +bool case5_live_control(Context& c, GuestHeap& visible) +{ + Res& T = c.make_committed("T5"); + if (!c.fill_desktop(T.guest.Get(), 5)) return false; + const auto srv = texture_view(); + invoke(c.guest, 18, T.guest.Get(), &srv, visible.cpu + 4 * c.increment); + for (int i = 0; i < 8; ++i) + if (!c.stays("T5 live", "a live texture left the budget")) return false; + return c.slot_is(visible, 4, false, "case 5: descriptor of a live texture"); +} + +} // namespace + +int main(int argc, char** argv) +{ + if (argc < 2 || argc > 3 || (std::strcmp(argv[1], "warp") && std::strcmp(argv[1], "hardware")) || + (argc == 3 && std::strcmp(argv[2], "keep"))) + return 2; + ComPtr factory; + if (FAILED(CreateDXGIFactory1(IID_PPV_ARGS(&factory)))) return 3; + const auto adapter = pick_adapter(factory.Get(), std::strcmp(argv[1], "warp") == 0); + if (!adapter) return 77; + char debug_env[2]{}; + const bool debug_on = GetEnvironmentVariableA("X2W_D3D12_DEBUG", debug_env, sizeof(debug_env)) && debug_env[0] == '1'; + if (debug_on) { + ComPtr debug; + if (FAILED(D3D12GetDebugInterface(IID_PPV_ARGS(&debug)))) return 77; + debug->EnableDebugLayer(); + } + ComPtr guest; + ComPtr device; + std::array parameters{}; + if (!require(D3D12XboxCreateDevice(adapter.Get(), parameters.data(), __uuidof(ID3D12Device), + reinterpret_cast(guest.GetAddressOf())), "Xbox device") || + !require(D3D12CreateDevice(adapter.Get(), D3D_FEATURE_LEVEL_12_0, IID_PPV_ARGS(&device)), "desktop device")) + return 3; + ComPtr debug; + if (debug_on && FAILED(device.As(&debug))) return 3; + if (debug) { + D3D12_MESSAGE_SEVERITY severities[] = { + D3D12_MESSAGE_SEVERITY_CORRUPTION, D3D12_MESSAGE_SEVERITY_ERROR, D3D12_MESSAGE_SEVERITY_WARNING}; + D3D12_INFO_QUEUE_FILTER filter{}; + filter.AllowList.NumSeverities = static_cast(std::size(severities)); + filter.AllowList.pSeverityList = severities; + if (FAILED(debug->AddStorageFilterEntries(&filter))) return 3; + debug->ClearStoredMessages(); + } + char value[2]{}; + const bool retire_on = GetEnvironmentVariableA("X2W_D3D12_RELEASE_RETIRED", value, sizeof(value)) == 1 && value[0] == '1'; + value[0] = 0; + const bool views_on = GetEnvironmentVariableA("X2W_D3D12_RELEASE_RETIRED_VIEWS", value, sizeof(value)) == 1 && value[0] == '1'; + const bool keep_mode = argc == 3; + // The effective switch needs both; `keep` runs with either one missing. + if ((retire_on && views_on) == keep_mode) return 2; + const bool on = !keep_mode; + DXGI_ADAPTER_DESC1 adapter_desc{}; + adapter->GetDesc1(&adapter_desc); + std::printf("adapter=%ls debug_layer=%s mode=%s\n", adapter_desc.Description, debug ? "enabled" : "off", keep_mode ? "keep" : "on"); + + Context c{guest.Get(), device.Get()}; + try { + c.desc = {D3D12_RESOURCE_DIMENSION_TEXTURE2D, 0, side, side, 1, 1, DXGI_FORMAT_R8G8B8A8_UNORM, {1, 0}, + D3D12_TEXTURE_LAYOUT_UNKNOWN, D3D12_RESOURCE_FLAG_NONE}; + c.texture_bytes = device->GetResourceAllocationInfo(0, 1, &c.desc).SizeInBytes; + c.increment = device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); + c.event = CreateEventW(nullptr, FALSE, FALSE, nullptr); + const D3D12_COMMAND_QUEUE_DESC direct{}; + const D3D12_HEAP_PROPERTIES upload_heap{D3D12_HEAP_TYPE_UPLOAD}, readback_heap{D3D12_HEAP_TYPE_READBACK}, + default_heap{D3D12_HEAP_TYPE_DEFAULT}; + const D3D12_RESOURCE_DESC buffer{D3D12_RESOURCE_DIMENSION_BUFFER, 0, image_bytes, 1, 1, 1, DXGI_FORMAT_UNKNOWN, {1, 0}, + D3D12_TEXTURE_LAYOUT_ROW_MAJOR, D3D12_RESOURCE_FLAG_NONE}; + D3D12_RESOURCE_DESC out_desc = buffer; + out_desc.Width = 256; + out_desc.Flags = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; + const D3D12_DESCRIPTOR_HEAP_DESC probe_heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 1, + D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, 0}; + if (!c.event || !require(device->CreateCommandQueue(&direct, IID_PPV_ARGS(&c.own_queue)), "own queue") || + !require(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&c.own_allocator)), "own allocator") || + !require(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, c.own_allocator.Get(), nullptr, IID_PPV_ARGS(&c.own_list)), "own list") || + !require(c.own_list->Close(), "own list close") || + !require(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&c.own_fence)), "own fence") || + !require(device->CreateCommittedResource(&upload_heap, D3D12_HEAP_FLAG_NONE, &buffer, D3D12_RESOURCE_STATE_GENERIC_READ, + nullptr, IID_PPV_ARGS(&c.upload)), "upload") || + !require(device->CreateCommittedResource(&readback_heap, D3D12_HEAP_FLAG_NONE, &buffer, D3D12_RESOURCE_STATE_COPY_DEST, + nullptr, IID_PPV_ARGS(&c.readback)), "readback") || + !require(device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &out_desc, + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, nullptr, IID_PPV_ARGS(&c.probe_out)), "probe output") || + !require(device->CreateDescriptorHeap(&probe_heap_desc, IID_PPV_ARGS(&c.probe_heap)), "probe heap")) + return 4; + + // The probe: a compute shader that loads texel (0,0) through descriptor table slot 0. + const D3D12_DESCRIPTOR_RANGE range{D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 1, 0, 0, 0}; + D3D12_ROOT_PARAMETER parameters_root[2]{}; + parameters_root[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; + parameters_root[0].DescriptorTable = {1, &range}; + parameters_root[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_UAV; + parameters_root[1].Descriptor = {0, 0}; + const D3D12_ROOT_SIGNATURE_DESC root_desc{2, parameters_root, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_NONE}; + ComPtr root_blob, errors, code; + if (!require(D3D12SerializeRootSignature(&root_desc, D3D_ROOT_SIGNATURE_VERSION_1, root_blob.GetAddressOf(), + errors.GetAddressOf()), "probe root serialize") || + !require(device->CreateRootSignature(0, root_blob->GetBufferPointer(), root_blob->GetBufferSize(), + IID_PPV_ARGS(&c.probe_root)), "probe root signature") || + !require(D3DCompile(probe_shader, std::strlen(probe_shader), nullptr, nullptr, nullptr, "main", "cs_5_1", 0, 0, + code.GetAddressOf(), errors.ReleaseAndGetAddressOf()), "probe shader")) + return 4; + D3D12_COMPUTE_PIPELINE_STATE_DESC pso{}; + pso.pRootSignature = c.probe_root.Get(); + pso.CS = {code->GetBufferPointer(), code->GetBufferSize()}; + if (!require(device->CreateComputePipelineState(&pso, IID_PPV_ARGS(&c.probe_pso)), "probe pipeline")) return 4; + + if (!c.make_queue(c.direct) || !c.make_queue(c.gated) || !c.make_list(c.drain_list) || !c.close(c.drain_list)) return 4; + if (!x2w_d3d12_budget_snapshot(&c.base, sizeof(c.base))) return 4; + + GuestHeap visible, staging; + if (!c.make_heap(visible, 8, true) || !c.make_heap(staging, 1, false)) return 4; + + if (!case1_single_view(c, on, visible)) return 5; + std::puts("1 single SRV in a shader-visible heap, never overwritten: freed with a null descriptor and a cleared token"); + if (!case2_copy_and_gate(c, on, visible, staging)) return 5; + std::puts("2 copied descriptor behind a closed gate: untouched until the fences pass, then both copies null"); + if (!case3_list_holds(c, on, visible)) return 5; + std::puts("3/4 listed texture: descriptors null, desktop object kept until the submission's fence or the discard"); + if (!case5_live_control(c, visible)) return 5; + std::puts("5 live texture: descriptor untouched"); + } catch (int code) { + return code; + } + const UINT64 errors = debug ? debug->GetNumStoredMessages() : 0; + std::printf("debug_errors_or_warnings=%llu\n", errors); + if (errors || FAILED(device->GetDeviceRemovedReason())) return 4; + std::puts(on ? "release-retired views checks passed" : "views-off control checks passed"); + return 0; +}