From b4d77999ac19ee5436492e43f9ff5d350bbe9157 Mon Sep 17 00:00:00 2001 From: JB2WIN Date: Wed, 25 Nov 2026 16:59:43 +0100 Subject: [PATCH 1/2] startup: opt-in release of retired committed 2D textures (X2W_D3D12_RELEASE_RETIRED) With X2W_D3D12_RELEASE_RETIRED=1, a committed 2D texture of one narrow class (slot 27 or 127, one sample, no render-target/depth/UAV flag, default heap, no title memory) gives up its desktop object after its final guest Release, but only when the release-time fence of every queue has passed and no recorded list or submission still names it. Lists hold the resource across copy, texture copy and resolve until Reset or destruction (an unsubmitted list is discarded without any submission); each submission holds it until a fence signalled behind it passes. Views, MakeResident/Evict and Present take a resource out of the class. Unset, nothing changes. The fixture startup_resource_retire uses the budget retained column as oracle and reads results back through its own desktop queue. AI-assisted (Claude Code) Co-Authored-By: Claude Opus 5.5 Refs #2379 --- CMakeLists.txt | 19 + docs/experiments.md | 8 + docs/startup-runtime.md | 40 ++ src/startup_stubs/d3d12_xs_device.cpp | 345 +++++++++- src/startup_stubs/list_copy.inl | 3 + src/startup_stubs/list_copy_texture.inl | 9 +- tests/startup_resource_retire.cpp | 824 ++++++++++++++++++++++++ 7 files changed, 1243 insertions(+), 5 deletions(-) create mode 100644 tests/startup_resource_retire.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 417d155511..9338ab204a 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1324,6 +1324,25 @@ foreach(backend IN ITEMS warp hardware) endforeach() endforeach() +# X2W_D3D12_RELEASE_RETIRED=1 frees the desktop object of a committed 2D texture only when no recorded list, no submission +# and no release-time fence still refers to it (docs/startup-runtime.md#d3d12-resource-budget). The `off` case runs +# without the switch and expects the lifetime of the budget fixture: every released resource stays retained. +add_executable(startup_resource_retire tests/startup_resource_retire.cpp) +target_include_directories(startup_resource_retire PRIVATE src) +target_compile_features(startup_resource_retire PRIVATE cxx_std_17) +target_link_libraries(startup_resource_retire PRIVATE d3d12_xs_shim d3d12 dxgi) +foreach(backend IN ITEMS warp hardware) + foreach(debug IN ITEMS 0 1) + set(retire_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_${backend}_debug${debug} COMMAND startup_resource_retire ${backend}) + set_tests_properties(startup_resource_retire_${backend}_debug${debug} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 + ENVIRONMENT "${retire_env};X2W_D3D12_RELEASE_RETIRED=1") + endforeach() + add_test(NAME startup_resource_retire_off_${backend} COMMAND startup_resource_retire ${backend} off) + set_tests_properties(startup_resource_retire_off_${backend} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 + ENVIRONMENT "X2W_D3D12_BUDGET=1;X2W_D3D12_PERMISSIVE=1;X2W_D3D12_LIST_NOOP=1;X2W_D3D12_RENDER=1;X2W_D3D12_DEBUG=0") +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/experiments.md b/docs/experiments.md index efca64a674..b740a1b655 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -36,6 +36,14 @@ cmake --build --preset release --target startup_resource_budget -j 2 ctest --preset release --no-tests=error -j 1 -R '^startup_resource_budget_' -V ``` +`startup_resource_retire` covers `X2W_D3D12_RELEASE_RETIRED=1` +([class and fences](startup-runtime.md#d3d12-resource-budget)): + +```powershell +cmake --build --preset release --target startup_resource_retire -j 2 +ctest --preset release --no-tests=error -j 1 -R '^startup_resource_retire_' -V +``` + The test runs on WARP and hardware with the debug layer on and off. The [budget heartbeat](startup-runtime.md#d3d12-resource-budget) correlates these counts with DXGI usage. The fixture measures the accounting and retirement diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index 043429b30c..a3e3d79cb0 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -1265,6 +1265,7 @@ ctest --preset dev --no-tests=error -R '^startup_trap_header(_prefix_control|_pr | `X2W_SHADER_CACHE=` | translation cache: the runtime writes source requests `req_.{a,b,root}`, when needed RTV variants `req_.rtv`, and for device slot 67 compute pipelines `req_.{desc,sa,sb,data,root,c67}` (see [Compute pipeline requests](#compute-pipeline-requests)). A console pipeline that an `ExecuteIndirect` draw (list slot 61) refuses writes the same request as a direct draw, once per pipeline, and draws nothing (`startup_indirect_requests_warp`). Only direct draws poll for its manifest, so such a pipeline stays in the `missing` count until a direct draw uses it; the `x2w-render totals` line counts `pipelines first looked up by ExecuteIndirect N`. This is a per-process lookup count. Check for the ready marker `req_.a` to confirm a complete request is available. Run `tools/startup/gfx2hlsl.py --pending ` while the process is running, or start the run with `run.ps1 -Translate` (see [Translating shaders during a run](#translating-shaders-during-a-run)). Active draws poll for an absent manifest at most once per second per pipeline and use the published translation on a subsequent draw. The translator compiles `.vs.cso` and `.ps.cso` with `fxc.exe`: `X2W_FXC`, else the Windows SDK 10.0.26100.0 copy, else the newest `Windows Kits\10\bin\\x64`, else `PATH`. When none exists it writes `.fail` naming `X2W_FXC` without publishing a new manifest. `X2W_FXC=` (empty) publishes the manifest alone. Rerun `--pending` with compilation enabled to fill in missing bytecode for an existing manifest. | | `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: 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_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) | @@ -1327,11 +1328,50 @@ those lifetimes intact. `unmeasured` counts tracking failures. DXGI usage can also include allocations outside these categories, such as swap chain and descriptor heap backing. +`X2W_D3D12_RELEASE_RETIRED=1` ends the retained lifetime for one class: a +texture created by device slot 27 or 127 that is two-dimensional, has one +sample, no render-target, depth-stencil or unordered-access flag, lives in a +default heap without heap flags and has no title memory. Every other resource +keeps the lifetime described above. A resource leaves the class for good when a +view is created for it (slots 18 to 21, also a refused one), when it is passed +to MakeResident or Evict (slots 34 and 35), or when it is presented. Only +wrappers can be in the class; a raw desktop pointer never is. Sampler feedback +is not checked: no device slot of the stand-in reaches it. + +The final guest release signals a private desktop fence on every queue the +stand-in created. The desktop object is released when all of those fences have +passed and nothing else names it. A copy (list slot 17), texture copy (16) or +resolve destination (19) that the stand-in forwards makes the list hold a +desktop reference to each resource of the class it names, source and +destination, until the list is Reset, fails to Close or is destroyed. A list +that is closed and never submitted is thus discarded without any submission. +Each submission holds the same references until its queue passes a fence +signalled behind it. A release with no registered queue, and a hold, marker or +submission fence that cannot be recorded, keep the resource retained. Nothing +waits: `ExecuteCommandLists` and `Present` check and release without blocking. +The wrapper stays allocated, and a guest that uses a resource after its final +release is not supported with the switch. Buffers, placed and reserved +resources, slot 133 and all resources with title memory are not in the class. +Slot 18 (`CopyTiles`) is not forwarded at all and is outside this change. + The source-built fixture reads the process-wide counters through `x2w_d3d12_budget_snapshot` and checks allocation sizes, final guest release, and slot 148 page retirement after queue completion. See [D3D12 budget accounting](experiments.md#d3d12-budget-accounting) for the test command. +`startup_resource_retire_{warp,hardware}_debug{0,1}` use the retained column as +the oracle that a desktop object is destroyed, and read results back through +their own desktop queue. They cover two closed lists on one texture that are +submitted separately after the release, a Reset or destroyed list with no +submission (the destination stays unchanged), a second submission held behind +its own fence, a destination released after recording (slots 17, 16 and 19), a +list destroyed while its submission is held, a copy queue, an open list that +D3D12 refuses to Reset and one that is destroyed, a release that no list +refers to behind a held queue, and, in one run with the class, a buffer, +render target, title-memory texture, viewed texture, resident texture and +presented texture that must stay retained. `startup_resource_retire_off_*` +runs the same steps without the switch. The hardware cases report 77 without a +physical adapter. ## Input script diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index 00f1b36fc6..3c2a8382a9 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -153,6 +153,7 @@ struct alignas(16) WrapperOwn { ID3D12Resource* list_scratch; // Current recording's rectangle-list argument scratch, owned by its desktop allocator. bool list_close_failed; // Desktop Reset repeats a failed Close result indefinitely. bool tiled_address_srv; // Resource backed by 4 KiB tiled guest memory for translated draws. + bool retire_when_idle; // Resource: member of the retire class (X2W_D3D12_RELEASE_RETIRED), cleared by any other use. bool list_ready; // CommandList (render mode): closed with recorded work, not yet submitted bool compute_pipeline; // PipelineState: a desktop compute pipeline u64 compute_trace_key; // Opt-in trace: selected slot 62 container hash @@ -764,6 +765,24 @@ D3D12_RESOURCE_DESC sanitized(const D3D12_RESOURCE_DESC& desc) return copy; } +bool release_retired_enabled() +{ + static const bool on = x2w_local::env_on("X2W_D3D12_RELEASE_RETIRED"); + 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, that has no title memory. Every use of such a resource reaches the shim through the handlers that +// retire_hold covers 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) +{ + 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; +} + template __declspec(noinline) u64 create_slot(Wrapper* self, u64 a, u64 b, u64 c, u64 d, u64 e, u64 f, u64 g, u64 h) { @@ -788,6 +807,11 @@ __declspec(noinline) u64 create_slot(Wrapper* self, u64 a, u64 b, u64 c, u64 d, if (Desc >= 0 && kind == resource_kind && requested_format != DXGI_FORMAT_UNKNOWN) x2w_startup::mark_packed_stand_in(static_cast(*out), requested_format); 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); + } if constexpr (K == device_kind && (N == 27 || N == 28 || N == 29)) { if (x2w_budget::enabled()) { using Microsoft::WRL::ComPtr; @@ -872,8 +896,18 @@ HRESULT __stdcall query_interface(Wrapper* self, const GUID* iid, void** out) return hr; } ULONG __stdcall add_ref(Wrapper* self) { return static_cast(InterlockedIncrement(&self->own().refs)); } -// The wrappers and their desktop objects stay alive for the process (experiment scope). +// The wrappers and their desktop objects stay alive for the process (experiment scope). The one exception is +// X2W_D3D12_RELEASE_RETIRED=1: the desktop object of a resource of the retire class is freed once nothing refers to it. +// The wrapper stays. 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_hold(Wrapper* list, Wrapper* resource); +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(); void drop_mesh_lease_owner(Wrapper* w); void discard_mesh_lease_recording(ID3D12CommandList* list); ULONG __stdcall release(Wrapper* self) @@ -886,8 +920,11 @@ ULONG __stdcall release(Wrapper* self) drop_mesh_lease_owner(self); retire_placement(self); } - if (self->own().kind == list_kind && self->own().real) + if (self->own().kind == list_kind && self->own().real) { discard_mesh_lease_recording(static_cast(self->own().real)); + retire_drop_recording(self); + } + if (self->own().retire_when_idle) retire_resource(self); } return static_cast(refs); } @@ -916,6 +953,7 @@ HRESULT __stdcall device_create_command_queue(Wrapper* self, const D3D12_COMMAND desc->Priority, desc->Flags, desc->NodeMask, text, static_cast(hr)); if (FAILED(hr)) return hr; *out = wrap(queue, queue_kind); + register_retire_queue(static_cast(*out)); return S_OK; } @@ -939,6 +977,7 @@ HRESULT __stdcall device_create_command_queue_x(Wrapper* self, const D3D12_COMMA desc->Type, desc->Priority, desc->Flags, desc->NodeMask, text, static_cast(hr)); if (FAILED(hr)) return hr; *out = wrap(queue, queue_kind); + register_retire_queue(static_cast(*out)); return S_OK; } @@ -1165,7 +1204,10 @@ template HRESULT __stdcall device_residency(Wrapper* self, UINT count, void* const* objects) { std::vector real(count); - for (UINT i = 0; i < count; ++i) real[i] = reinterpret_cast(unwrap(reinterpret_cast(objects[i]))); + for (UINT i = 0; i < count; ++i) { + retire_leave_class(objects[i]); // 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()); } @@ -1560,6 +1602,7 @@ HRESULT __stdcall list_reset(Wrapper* self, void* allocator) discard_draw_sampler_heaps(previous); discard_address_uploads(previous); discard_mesh_lease_recording(previous); + retire_drop_recording(self); if (draw_dump_frame()) draw_dumps().discard(previous); discard_red_producer(previous); } @@ -1597,6 +1640,7 @@ HRESULT __stdcall list_close(Wrapper* self) discard_draw_sampler_heaps(list); discard_address_uploads(list); discard_mesh_lease_recording(list); + retire_drop_recording(self); if (draw_dump_frame()) draw_dumps().discard(list); discard_red_producer(list); static LONG failures; @@ -2351,6 +2395,16 @@ void release_targets(Wrapper* self) pass = Pass{}; } +// A dropped recording (Reset, or its list destroyed) names no resource any more. The raw pointers the pass keeps for +// Close go first, then the holds that kept those resources alive (X2W_D3D12_RELEASE_RETIRED). Without the switch +// nothing changes. +void retire_drop_recording(Wrapper* list) +{ + if (!release_retired_enabled()) return; + if (list->own().pass) pass_of(list).states.clear(); + retire_discard_holds(list); +} + // A reset list has no viewport or scissor and uses the default stencil reference. void reset_list_dynamic_state(Wrapper* self) { @@ -3318,6 +3372,7 @@ void __stdcall queue_execute(Wrapper* self, UINT count, void* const* lists) { X2W_ZONE("ExecuteCommandLists"); static LONG calls; + drain_retired_resources(); if (render_mode()) { // A closed list stays submittable until its next Reset, as on the desktop. std::vector ready; @@ -3346,6 +3401,7 @@ void __stdcall queue_execute(Wrapper* self, UINT count, void* const* lists) retire_address_uploads(queue, native_lists); retire_draw_sampler_heaps(queue, native_lists); note_submits(queue, wrappers); + retire_note_submission(queue, wrappers); for (Wrapper* w : wrappers) commit_list_gpu_writes(w); InterlockedIncrement(&render_executes); }; @@ -3709,6 +3765,9 @@ template __declspec(noinline) u64 view_slot(Wrapper* self, u64 a, u64 b, u64 c, u64 d) { Timed timed(time_view); + // A view keeps the resource's old lifetime, whether or not the view is created (X2W_D3D12_RELEASE_RETIRED). + if constexpr (N >= 18 && N <= 21) retire_leave_class(reinterpret_cast(a)); + if constexpr (N == 19) retire_leave_class(reinterpret_cast(b)); u64 args[4] = {unwrap(a), unwrap(b), unwrap(c), unwrap(d)}; const u64 title_dest = args[D]; args[D] = desktop_cpu_handle(args[D]); @@ -4136,6 +4195,278 @@ HRESULT __stdcall device_place_resource_x(Wrapper* self, void* address, const D3 #include "d3d12_memory_srv.inl" #include "startup_stubs/list_copy.inl" +// X2W_D3D12_RELEASE_RETIRED=1 (opt-in; docs/startup-runtime.md#d3d12-resource-budget). The desktop object of a resource +// of the retire class (retire_class) is released after its final guest Release, once both hold: +// - Release-time fences: every queue the shim created owns a private desktop fence. The final Release signals each of +// them, so the recorded values lie behind everything already submitted, and the drain compares them. A release with +// no registered queue, or one whose fence failed, retires nothing. +// - No use is left: a list that recorded a copy, texture copy or resolve of the resource holds a desktop reference +// until the list is Reset, closed with an error or destroyed (an unsubmitted list is discarded without any +// submission), and every submission of such a list holds one until its queue passes a fence signalled right behind it. +// Nothing waits. The drain runs at the start of ExecuteCommandLists and Present and only try-locks retire_lock; +// desktop references are dropped after the lock is released. A hold, marker or submission fence that cannot be recorded +// leaves the resource retained for the process, which is the lifetime without the switch. The wrapper itself stays. +constexpr LONG retired_refs = -0x40000000; +SRWLOCK retire_lock = SRWLOCK_INIT; // a leaf: taken after draw_lock and allocator_lock, nothing is taken under it +struct RetireQueue { + ID3D12CommandQueue* queue; + ID3D12Fence* fence; // null: no marker for this queue, so nothing retires + UINT64 signaled; +}; +struct RetiredResource { + Wrapper* wrapper; + std::vector targets; // per RetireQueue that existed at the Release +}; +struct RetireFlight { + std::size_t queue; + UINT64 value; + std::vector resources; // one desktop reference each +}; +std::vector retire_queues; +std::vector retired_resources; +std::vector retire_flights; +std::unordered_map> retire_list_holds; // one desktop reference per entry +volatile LONG retire_pending; // retired_resources and retire_flights, read without the lock +volatile LONG retire_holds; // entries of retire_list_holds, read without the lock +volatile LONG64 retire_freed, retire_kept; + +void register_retire_queue(Wrapper* queue) +{ + if (!release_retired_enabled() || !queue || !queue->own().real) return; + auto* real = static_cast(queue->own().real); + ID3D12Fence* fence = nullptr; + ID3D12Device* device = nullptr; + if (SUCCEEDED(real->GetDevice(IID_PPV_ARGS(&device)))) { + if (FAILED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence)))) fence = nullptr; + device->Release(); + } + AcquireSRWLockExclusive(&retire_lock); + try { + retire_queues.push_back({real, fence, 0}); + } catch (const std::bad_alloc&) { + if (fence) fence->Release(); + } + ReleaseSRWLockExclusive(&retire_lock); +} + +// 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) +{ + if (!release_retired_enabled()) return; + if (Wrapper* w = as_wrapper(object)) w->own().retire_when_idle = false; +} + +// After a copy, texture copy or resolve was forwarded to the desktop list: the list keeps a desktop reference to the +// resource until its recording is dropped. Only wrappers can be members of the class, so a raw desktop pointer is +// never held (and never retired). +void retire_hold(Wrapper* list, Wrapper* resource) +{ + if (!resource || !resource->own().retire_when_idle) return; + auto* real = static_cast(resource->own().real); + bool held = false; + if (real) { + AcquireSRWLockExclusive(&retire_lock); + try { + auto& held_by_list = retire_list_holds[list]; + if (std::find(held_by_list.begin(), held_by_list.end(), real) != held_by_list.end()) { + held = true; + } else { + held_by_list.reserve(held_by_list.size() + 1); + real->AddRef(); + held_by_list.push_back(real); + InterlockedIncrement(&retire_holds); + held = true; + } + } catch (const std::bad_alloc&) { + } + ReleaseSRWLockExclusive(&retire_lock); + } + // The guest still references the resource in this call, so it cannot be retired yet: leave the class instead. + if (!held) resource->own().retire_when_idle = false; +} + +void retire_discard_holds(Wrapper* list) +{ + if (!InterlockedCompareExchange(&retire_holds, 0, 0)) return; + std::vector dropped; + AcquireSRWLockExclusive(&retire_lock); + if (const auto found = retire_list_holds.find(list); found != retire_list_holds.end()) { + dropped = std::move(found->second); + retire_list_holds.erase(found); + InterlockedAdd(&retire_holds, -static_cast(dropped.size())); + } + ReleaseSRWLockExclusive(&retire_lock); + for (ID3D12Resource* resource : dropped) resource->Release(); +} + +// Right after ExecuteCommandLists: the lists' held resources stay referenced until the queue passes a fence signalled +// behind the submission. If that fence cannot be recorded or signalled the references are kept for the process. +void retire_note_submission(ID3D12CommandQueue* queue, const std::vector& lists) +{ + if (!InterlockedCompareExchange(&retire_holds, 0, 0)) return; + std::vector named; + AcquireSRWLockExclusive(&retire_lock); + bool room = true; + try { + for (Wrapper* list : lists) { + const auto found = retire_list_holds.find(list); + if (found == retire_list_holds.end()) continue; + for (ID3D12Resource* resource : found->second) + if (std::find(named.begin(), named.end(), resource) == named.end()) named.push_back(resource); + } + retire_flights.reserve(retire_flights.size() + 1); + } catch (const std::bad_alloc&) { + room = false; + } + bool recorded = false; + if (room && !named.empty()) { + std::size_t index = 0; + while (index < retire_queues.size() && retire_queues[index].queue != queue) ++index; + if (index < retire_queues.size() && retire_queues[index].fence) { + RetireQueue& q = retire_queues[index]; + for (ID3D12Resource* resource : named) resource->AddRef(); + if (SUCCEEDED(queue->Signal(q.fence, q.signaled + 1))) { + ++q.signaled; + retire_flights.push_back({index, q.signaled, std::move(named)}); + InterlockedIncrement(&retire_pending); + recorded = true; + } + } + } + if (!recorded && (!room || !named.empty())) { + // Keep everything the lists name for the process; no allocation is needed to do so. + for (Wrapper* list : lists) + if (const auto found = retire_list_holds.find(list); found != retire_list_holds.end()) + for (ID3D12Resource* resource : found->second) resource->AddRef(); + InterlockedIncrement64(&retire_kept); + } + ReleaseSRWLockExclusive(&retire_lock); + if (!recorded && (!room || !named.empty())) { + static LONG reported; + if (first_calls(reported, 4)) log("x2w-d3d12 retire: a submission could not be fenced; its resources stay retained"); + } +} + +// Called by the final Release of a resource of the class. +void retire_resource(Wrapper* w) +{ + if (w->own().kind != resource_kind || !w->own().real) return; + RetiredResource item{w, {}}; + bool queued = false; + AcquireSRWLockExclusive(&retire_lock); + try { + // Without a registered queue nothing orders a marker: keep the resource. Every queue needs its fence. + queued = !retire_queues.empty(); + for (const RetireQueue& q : retire_queues) queued = queued && q.fence; + if (queued) { + item.targets.reserve(retire_queues.size()); + retired_resources.reserve(retired_resources.size() + 1); + for (RetireQueue& q : retire_queues) { + if (FAILED(q.queue->Signal(q.fence, q.signaled + 1))) { + queued = false; + break; + } + item.targets.push_back(++q.signaled); + } + } + if (queued) { + retired_resources.push_back(std::move(item)); + InterlockedIncrement(&retire_pending); + } + } catch (const std::bad_alloc&) { + queued = false; + } + ReleaseSRWLockExclusive(&retire_lock); + if (!queued) InterlockedIncrement64(&retire_kept); // stays retained, as without the switch +} + +// 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; + constexpr std::size_t batch = 256; + std::vector dropped; + try { + dropped.reserve(batch); + } catch (const std::bad_alloc&) { + return; + } + if (!TryAcquireSRWLockExclusive(&retire_lock)) return; + for (std::size_t i = 0; i < retired_resources.size() && dropped.size() < batch;) { + RetiredResource& item = retired_resources[i]; + 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]; + if (!reached) { + ++i; + continue; + } + Wrapper* w = item.wrapper; + // Claim the reference count so that a late AddRef cannot bring the wrapper back while its object goes. + if (InterlockedCompareExchange(&w->own().refs, retired_refs, 0) == 0) { + dropped.push_back(static_cast(w->own().real)); + w->own().real = nullptr; + } else { + InterlockedIncrement64(&retire_kept); // referenced again after its final Release + } + if (i + 1 != retired_resources.size()) item = std::move(retired_resources.back()); + retired_resources.pop_back(); + InterlockedDecrement(&retire_pending); + } + for (std::size_t i = 0; i < retire_flights.size() && dropped.size() < batch;) { + RetireFlight& flight = retire_flights[i]; + if (retire_queues[flight.queue].fence->GetCompletedValue() < flight.value) { + ++i; + continue; + } + // A flight holds at most a list's resources; it may overshoot the batch by that much. + dropped.insert(dropped.end(), flight.resources.begin(), flight.resources.end()); + if (i + 1 != retire_flights.size()) flight = std::move(retire_flights.back()); + retire_flights.pop_back(); + InterlockedDecrement(&retire_pending); + } + ReleaseSRWLockExclusive(&retire_lock); + for (ID3D12Resource* resource : dropped) { + resource->Release(); + const LONG64 total = InterlockedIncrement64(&retire_freed); + if (total <= 8 || total % 1000 == 0) log("x2w-d3d12 retire: %lld desktop references dropped", total); + } +} + +// 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 { + unsigned cache_entries; + unsigned list_states; + unsigned list_holds; +}; +extern "C" __declspec(dllexport) BOOL x2w_d3d12_retire_probe(void* resource, void* list, RetireProbe* out) +{ + if (!out) return FALSE; + *out = {}; + if (Wrapper* r = as_wrapper(resource); r && r->own().kind == resource_kind && r->own().real) { + auto* real = static_cast(r->own().real); + AcquireSRWLockExclusive(&draw_lock); + out->cache_entries += static_cast(texture_uploads().count(real)); + ReleaseSRWLockExclusive(&draw_lock); + AcquireSRWLockShared(&target_lock); + for (const auto& view : view_targets()) out->cache_entries += view.second.resource == real; + ReleaseSRWLockShared(&target_lock); + AcquireSRWLockShared(&pending_writes_lock); + for (const auto& writes : pending_gpu_writes()) + out->cache_entries += static_cast(std::count(writes.second.begin(), writes.second.end(), real)); + ReleaseSRWLockShared(&pending_writes_lock); + } + if (Wrapper* l = as_wrapper(list); l && l->own().kind == list_kind) { + if (l->own().pass) out->list_states = static_cast(pass_of(l).states.size()); + AcquireSRWLockShared(&retire_lock); + if (const auto found = retire_list_holds.find(l); found != retire_list_holds.end()) + out->list_holds = static_cast(found->second.size()); + ReleaseSRWLockShared(&retire_lock); + } + return TRUE; +} + // The title exports __XMemAllocationHooks__ = {alloc(size, attributes), free(ptr, attributes), ...}. // Its alloc routine selects a hook chain by allocatorId (attribute bits 16-23). Around the creation // of its two display render targets the title pushes a bump allocator for allocatorId 0x80 that @@ -4467,6 +4798,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); note_resource(w, desc, info.SizeInBytes != ~0ull ? info.SizeInBytes : 0); *out = w; return S_OK; @@ -4666,6 +4998,13 @@ void report_budget(ID3D12CommandQueue* queue) // console present. Nothing is shown yet; frames are counted and a heartbeat is logged. HRESULT __stdcall queue_present(Wrapper* self, UINT planes, const void* plane_parameters, const void* present_parameters) { + // First, before anything reads or copies the surface: a presented resource keeps its old lifetime. + 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])); + } + drain_retired_resources(); Timed timed(time_present); X2W_ZONE("Present"); X2W_FRAME_MARK; diff --git a/src/startup_stubs/list_copy.inl b/src/startup_stubs/list_copy.inl index fd78ce8dc5..7f5fa07aa8 100644 --- a/src/startup_stubs/list_copy.inl +++ b/src/startup_stubs/list_copy.inl @@ -234,6 +234,8 @@ void __stdcall list_copy_resource(Wrapper* self, u64 destination, u64 source) require_copy_state(self, from.resource, D3D12_RESOURCE_STATE_COPY_SOURCE); require_copy_state(self, to.resource, D3D12_RESOURCE_STATE_COPY_DEST); static_cast(self->own().real)->CopyResource(to.resource, from.resource); + retire_hold(self, to.wrapper); + retire_hold(self, from.wrapper); if (to_desc.Dimension == D3D12_RESOURCE_DIMENSION_BUFFER) { note_mesh_xmem_write(self, to.wrapper, 0, to_desc.Width); note_copy_gpu_range(self, to.resource, 0, to_desc.Width, false); @@ -263,6 +265,7 @@ void __stdcall list_resolve_subresource(Wrapper* self, u64 destination, UINT des require_copy_state(self, to.resource, D3D12_RESOURCE_STATE_RESOLVE_DEST); static_cast(self->own().real) ->ResolveSubresource(to.resource, destination_subresource, from.resource, source_subresource, plan.format); + retire_hold(self, to.wrapper); // the source is multisampled, so never a member of the retire class mark_gpu_written(self, to); InterlockedIncrement(&list_resolves); } diff --git a/src/startup_stubs/list_copy_texture.inl b/src/startup_stubs/list_copy_texture.inl index 3d9a4c31cf..57ffaaf7c2 100644 --- a/src/startup_stubs/list_copy_texture.inl +++ b/src/startup_stubs/list_copy_texture.inl @@ -147,14 +147,19 @@ void __stdcall list_copy_texture(Wrapper* self, const D3D12_TEXTURE_COPY_LOCATIO } // Bring a texture's desktop copy up to date with its guest backing before the copy reads or partly overwrites it, // and record that upload so a later sample does not replace the copied texels. - if (side_src.kind == x2w_list_copy_texture::Kind::subresource) upload_texture(self, src_wrapper, real_src); - if (side_dst.kind == x2w_list_copy_texture::Kind::subresource) upload_texture(self, dst_wrapper, real_dst); + // A resource of the retire class has no title memory, so there is nothing to upload and no cache entry to leave behind. + if (side_src.kind == x2w_list_copy_texture::Kind::subresource && !src_wrapper->own().retire_when_idle) + upload_texture(self, src_wrapper, real_src); + if (side_dst.kind == x2w_list_copy_texture::Kind::subresource && !dst_wrapper->own().retire_when_idle) + upload_texture(self, dst_wrapper, real_dst); if (!src_fixed) require_state(self, real_src, D3D12_RESOURCE_STATE_COPY_SOURCE); if (!dst_fixed) require_state(self, real_dst, D3D12_RESOURCE_STATE_COPY_DEST); D3D12_TEXTURE_COPY_LOCATION to = *dst, from = *src; to.pResource = real_dst; from.pResource = real_src; static_cast(self->own().real)->CopyTextureRegion(&to, x, y, z, &from, box ? box : nullptr); + retire_hold(self, dst_wrapper); + retire_hold(self, src_wrapper); InterlockedIncrement(&list_copy_texture_forwarded); } diff --git a/tests/startup_resource_retire.cpp b/tests/startup_resource_retire.cpp new file mode 100644 index 0000000000..c10b02f50f --- /dev/null +++ b/tests/startup_resource_retire.cpp @@ -0,0 +1,824 @@ +// X2W_D3D12_RELEASE_RETIRED=1: a committed 2D texture of the retire class (docs/startup-runtime.md#d3d12-resource-budget) +// gives up its desktop object only when no recorded list and no submission still refers to it and the release-time +// fence of every queue has passed. The retained column of the budget snapshot is the oracle for "the desktop object +// is destroyed": a ticket leaves it when its object dies. Readbacks go through the fixture's own desktop queue. +// +// startup_resource_retire [off] +// (X2W_D3D12_BUDGET=1 X2W_D3D12_PERMISSIVE=1 X2W_D3D12_LIST_NOOP=1 X2W_D3D12_RENDER=1, and +// X2W_D3D12_RELEASE_RETIRED=1 unless the argument is "off") +// +// Cases with the switch on (each failure prints one "FAIL: ..." line and exits 5): +// 1 two lists record a copy of R, both closed and not submitted; R is released, every queue's release-time fence +// passes: R stays; the lists are submitted one by one and both readbacks are right. +// 2 a list that is Reset, or destroyed, without a submission drops its hold and invents nothing. +// 3 a second submission waits on its own fence; its list is Reset; R stays until the fence has passed. +// 4 a destination released after recording (slots 17, 16, 19), a list destroyed while its submission is held, a copy queue. +// 5 an open recording: D3D12 refuses its Reset (the holds stay); a list destroyed while open drops its state first. +// 6 a release that no list names waits for the release-time fence of a held queue. +// 7 buffer, render target, title memory, a view, MakeResident and Present keep the old lifetime next to ones that retire. +// "off" runs the same steps without the switch: nothing is ever freed. +#include "startup_stubs/resource_budget.h" + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +using Microsoft::WRL::ComPtr; + +struct RetireProbe { + unsigned cache_entries; // texture_uploads, pending_gpu_writes and view_targets entries naming the resource + unsigned list_states; // resources the open recording of the list moved out of COMMON + unsigned list_holds; // resources the list's recordings hold +}; +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); +extern "C" __declspec(dllimport) BOOL x2w_d3d12_retire_probe(void*, void*, RetireProbe*); + +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; // bounded drains, no sleeping +constexpr int seed_source = 3, seed_sentinel = 9; + +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) +{ + // Same temporary private-data bridge as startup_resource_budget. The bridge reference is dropped on return. + 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; +} + +// A guest resource and what the budget must say about it. +struct Res { + ComPtr guest; + const char* name = ""; + Category category = texture; + UINT64 bytes = 0; + bool released = false; // the guest dropped its last reference: the ticket sits in the retained column + bool freed = false; // the desktop object is destroyed: the ticket is gone +}; + +struct GuestList { + ComPtr allocator, list; +}; + +// A guest queue with a completion fence the host can wait on. +struct GuestQueue { + ComPtr queue, done; + ComPtr done_real; + UINT64 value = 0; +}; + +struct Context { + IUnknown* guest; + ID3D12Device* device; + ID3D12InfoQueue* debug; + ComPtr own_queue; + ComPtr own_allocator; + ComPtr own_list; + ComPtr own_fence; + UINT64 own_value = 0; + HANDLE event = nullptr; + ComPtr upload, readback; + Snapshot base{}; + std::deque pool; + GuestQueue direct, other, gated, copy; // submissions, drains, held submissions, a copy queue + 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: the fixture's own queue did not finish"); + return false; + } + void own_barrier(ID3D12Resource* resource, D3D12_RESOURCE_STATES from, D3D12_RESOURCE_STATES to) + { + D3D12_RESOURCE_BARRIER barrier{}; + barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; + barrier.Transition = {resource, D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, from, to}; + own_list->ResourceBarrier(1, &barrier); + } + D3D12_TEXTURE_COPY_LOCATION footprint(ID3D12Resource* buffer) const + { + D3D12_TEXTURE_COPY_LOCATION location{buffer, D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT}; + location.PlacedFootprint = {0, {DXGI_FORMAT_R8G8B8A8_UNORM, side, side, 1, pitch}}; + return location; + } + // Writes the pattern of `seed` into a guest texture, through the desktop object that stands behind it. + bool fill(IUnknown* texture_object, int seed) + { + const auto real = desktop_object(guest, device, texture_object); + if (!real) return false; + void* mapped = nullptr; + if (!require(upload->Map(0, nullptr, &mapped), "upload map")) return false; + for (UINT i = 0; i < image_bytes; ++i) static_cast(mapped)[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_barrier(real.Get(), D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_DEST); + const D3D12_TEXTURE_COPY_LOCATION to{real.Get(), D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, {0}}; + const auto from = footprint(upload.Get()); + own_list->CopyTextureRegion(&to, 0, 0, 0, &from, nullptr); + own_barrier(real.Get(), D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_COMMON); + return own_run(); + } + // True when the guest texture holds the pattern of `seed`. + bool holds(IUnknown* texture_object, int seed, const char* what) + { + const auto real = desktop_object(guest, device, texture_object); + if (!real) return false; + if (!require(own_allocator->Reset(), "own allocator") || !require(own_list->Reset(own_allocator.Get(), nullptr), "own list")) return false; + own_barrier(real.Get(), D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_SOURCE); + const D3D12_TEXTURE_COPY_LOCATION from{real.Get(), D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, {0}}; + const auto to = footprint(readback.Get()); + own_list->CopyTextureRegion(&to, 0, 0, 0, &from, nullptr); + own_barrier(real.Get(), D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_COMMON); + 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; + UINT wrong = image_bytes; + for (UINT i = 0; i < image_bytes; ++i) + if (static_cast(mapped)[i] != pattern_byte(seed, i)) { wrong = i; break; } + const std::uint8_t got = wrong < image_bytes ? static_cast(mapped)[wrong] : 0; + readback->Unmap(0, nullptr); + if (wrong < image_bytes) std::printf("FAIL: readback of %s differs at byte %u: got %02x want %02x\n", what, wrong, got, pattern_byte(seed, wrong)); + return wrong == image_bytes; + } + + // ---- guest objects ---- + Res& make_texture(const char* name, D3D12_RESOURCE_FLAGS flags = D3D12_RESOURCE_FLAG_NONE, bool through_slot_27 = false) + { + D3D12_RESOURCE_DESC d = desc; + d.Flags = flags; + const D3D12_HEAP_PROPERTIES heap{D3D12_HEAP_TYPE_DEFAULT}; + Res& r = pool.emplace_back(); + r.name = name; + 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, name)) pool.pop_back(), throw 4; + return r; + } + Res& make_buffer(const char* name) + { + 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}; + const D3D12_HEAP_PROPERTIES heap{D3D12_HEAP_TYPE_DEFAULT}; + Res& r = pool.emplace_back(); + r.name = name; + r.category = buffer; + r.bytes = device->GetResourceAllocationInfo(0, 1, &d).SizeInBytes; + if (!require(invoke(guest, 27, &heap, D3D12_HEAP_FLAG_NONE, &d, D3D12_RESOURCE_STATE_COMMON, nullptr, &iid_resource[0], + r.guest.GetAddressOf()), name)) pool.pop_back(), throw 4; + return r; + } + void release(Res& r) + { + r.guest.Reset(); + r.released = true; + } + bool make_queue(GuestQueue& q, D3D12_COMMAND_LIST_TYPE type = D3D12_COMMAND_LIST_TYPE_DIRECT) + { + const D3D12_COMMAND_QUEUE_DESC d{type}; + ComPtr fence; + if (!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")) + return false; + q.done_real = desktop_object(guest, device, q.done.Get()); + return q.done_real != nullptr; + } + // Everything the queue was given so far, including the release-time markers, has passed once this returns. + 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 make_list(GuestList& l, D3D12_COMMAND_LIST_TYPE type = D3D12_COMMAND_LIST_TYPE_DIRECT) + { + const unsigned list_desc[] = {static_cast(type), 2, 1, 0}; + return require(invoke(guest, 9, type, &__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"); + } + // Reset onto a new allocator, as a frame loop does. Returns the HRESULT of the Reset. + HRESULT reset_list(GuestList& l, D3D12_COMMAND_LIST_TYPE type = D3D12_COMMAND_LIST_TYPE_DIRECT) + { + ComPtr next; + if (!require(invoke(guest, 9, type, &__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; + } + 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); + } + // ExecuteCommandLists on the second queue runs the retire drain; its empty list does nothing else. + void drain() { execute(other, drain_list); } + + // ---- the oracle ---- + Snapshot expected() const + { + Snapshot e = base; + for (const Res& r : pool) { + if (r.freed) continue; + Counts& c = r.released ? e.retained[r.category] : e.live[r.category]; + c.bytes += r.bytes; + ++c.objects; + } + return e; + } + static bool same(Counts a, Counts b) { return a.bytes == b.bytes && a.objects == b.objects; } + bool counts_match(Snapshot* actual_out = nullptr) const + { + Snapshot actual{}; + if (!x2w_d3d12_budget_snapshot(&actual, sizeof(actual))) return false; + if (actual_out) *actual_out = actual; + const Snapshot e = expected(); + bool pass = e.unmeasured == actual.unmeasured; + for (unsigned i = 0; i < category_count; ++i) pass = pass && same(e.live[i], actual.live[i]) && same(e.retained[i], actual.retained[i]); + return pass; + } + // The stage's expectation holds right now. `fail` is the one line a missing protection prints. + bool expect(const char* stage, const char* fail) + { + Snapshot actual{}; + if (counts_match(&actual)) return true; + const Snapshot e = expected(); + std::printf("FAIL: %s\n", fail); + for (unsigned i = 0; i < category_count; ++i) + if (!same(e.live[i], actual.live[i]) || !same(e.retained[i], actual.retained[i])) + std::printf(" stage '%s' %s live=%llu/%llu expected=%llu/%llu retained=%llu/%llu expected=%llu/%llu\n", stage, names[i], + actual.live[i].bytes, actual.live[i].objects, e.live[i].bytes, e.live[i].objects, + actual.retained[i].bytes, actual.retained[i].objects, e.retained[i].bytes, e.retained[i].objects); + if (e.unmeasured != actual.unmeasured) std::printf(" unmeasured=%llu expected=%llu\n", actual.unmeasured, e.unmeasured); + return false; + } + // Drains until the counters equal the expectation, at most settle_limit times, without sleeping. + bool settle(const char* stage, const char* fail) + { + for (int i = 0; i < settle_limit; ++i) { + drain(); + if (counts_match()) return true; + } + return expect(stage, fail); + } + // A few drains in a row never change the counters: nothing may go early. + bool stays(const char* stage, const char* fail) + { + for (int i = 0; i < 4; ++i) drain(); + return expect(stage, fail); + } + RetireProbe probe(const Res* r, const GuestList* l) const + { + RetireProbe p{}; + x2w_d3d12_retire_probe(r ? r->guest.Get() : nullptr, l ? l->list.Get() : nullptr, &p); + return p; + } +}; + +// ---- stages ---- + +// 1: two closed lists on R, R released while both are unsubmitted, then submitted one by one. +bool closed_lists(Context& c, bool on, Res& R, Res& D1, Res& D2, GuestList& L1, GuestList& L2) +{ + if (!c.make_list(L1) || !c.make_list(L2)) return false; + invoke(L1.list.Get(), 17, D1.guest.Get(), R.guest.Get()); + invoke(L2.list.Get(), 17, D2.guest.Get(), R.guest.Get()); + if (!c.close(L1) || !c.close(L2)) return false; + c.release(R); + if (!c.sync(c.direct) || !c.sync(c.other) || !c.sync(c.gated) || !c.sync(c.copy)) return false; + if (on) { + // The release-time fence of every queue has passed. The lists still name R. + if (!c.stays("closed lists", "early release (closed lists)")) return false; + const RetireProbe p = c.probe(&D1, &L1); + if (p.list_holds != 2 || p.cache_entries) { + std::printf("FAIL: list L1 holds %u resources (expected 2), %u cache entries on a destination\n", p.list_holds, p.cache_entries); + return false; + } + } else if (!c.stays("closed lists, switch off", "switch off changed the lifetime")) return false; + c.execute(c.direct, L1); + if (!c.sync(c.direct) || !c.holds(D1.guest.Get(), seed_source, "D1 after the first submission")) return false; + if (!c.holds(D2.guest.Get(), seed_sentinel, "D2 before its submission")) return false; + if (!c.stays("first list submitted", "early release (first submission)")) return false; + // A Reset on a fresh allocator drops L1's hold; L2 still names R. + if (!SUCCEEDED(c.reset_list(L1))) return false; + return c.stays("first list reset", "early release (second list)"); +} + +// 2: discard by Reset, discard by destroying the list; neither invents a submission. +bool discards(Context& c, bool on, Res& Rb, Res& D3, Res& Rc, Res& D4, GuestList& L3, GuestList& L4) +{ + if (!c.make_list(L3) || !c.make_list(L4)) return false; + invoke(L3.list.Get(), 17, D3.guest.Get(), Rb.guest.Get()); + invoke(L4.list.Get(), 17, D4.guest.Get(), Rc.guest.Get()); + if (!c.close(L3) || !c.close(L4)) return false; + c.release(Rb); + c.release(Rc); + if (!c.sync(c.direct) || !c.sync(c.other) || !c.sync(c.gated) || !c.sync(c.copy)) return false; + if (!c.stays("discard lists recorded", "early release (discard lists)")) return false; + if (!SUCCEEDED(c.reset_list(L3))) return false; // Reset of a closed, never submitted list + if (on) Rb.freed = true; + if (!c.settle("Reset discard", "a Reset list kept its resource")) return false; + L4.list.Reset(); // the guest destroys a closed, never submitted list + if (on) Rc.freed = true; + if (!c.settle("destroy discard", "a destroyed list kept its resource")) return false; + // Nothing was submitted for either list: the destinations still hold the sentinel. + return c.holds(D3.guest.Get(), seed_sentinel, "D3 after a discarded Reset") && + c.holds(D4.guest.Get(), seed_sentinel, "D4 after a discarded destroy"); +} + +// 3: a second submission behind its own fence. +bool second_submission(Context& c, bool on, Res& R, Res& D2, GuestList& L2) +{ + ComPtr gate; + if (!require(invoke(c.guest, 36, UINT64{0}, D3D12_FENCE_FLAG_NONE, &__uuidof(ID3D12Fence), gate.GetAddressOf()), "gate fence")) return false; + if (!require(invoke(c.gated.queue.Get(), 17, gate.Get(), UINT64{1}), "queue wait")) return false; + c.execute(c.gated, L2); + if (!SUCCEEDED(c.reset_list(L2))) return false; // the list's hold falls; only the submission names R + if (!c.stays("held submission", "early release (submission fence)")) return false; + if (!require(invoke(gate.Get(), 10, UINT64{1}), "gate signal") || !c.sync(c.gated)) return false; + if (on) R.freed = true; + if (!c.settle("submission passed", "R kept after its submission passed")) return false; + return c.holds(D2.guest.Get(), seed_source, "D2 after the second submission"); +} + +// 4a: destination released after recording (CopyResource), the destination only; the second copy checks the run. +bool destination_released(Context& c, bool on, Res& Rs, Res& D5, Res& Dout5, GuestList& L5) +{ + if (!c.make_list(L5)) return false; + invoke(L5.list.Get(), 17, D5.guest.Get(), Rs.guest.Get()); + invoke(L5.list.Get(), 17, Dout5.guest.Get(), Rs.guest.Get()); + if (!c.close(L5)) return false; + c.release(D5); + if (!c.sync(c.direct) || !c.sync(c.other) || !c.sync(c.gated) || !c.sync(c.copy)) return false; + if (!c.stays("destination released", "early release (copy destination)")) return false; + c.execute(c.direct, L5); + if (!c.sync(c.direct) || !c.holds(Dout5.guest.Get(), seed_source, "Dout5")) return false; + if (!c.stays("destination submitted", "early release (copy destination, submitted)")) return false; + if (!SUCCEEDED(c.reset_list(L5))) return false; + if (on) D5.freed = true; + return c.settle("destination list reset", "a Reset list kept its destination"); +} + +// 4b: CopyTextureRegion (slot 16): both ends released after recording. +bool texture_region(Context& c, bool on, Res& R10, Res& D10, Res& Dout10, GuestList& L) +{ + if (!c.make_list(L)) return false; + D3D12_TEXTURE_COPY_LOCATION to{static_cast(static_cast(D10.guest.Get())), D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, {0}}; + D3D12_TEXTURE_COPY_LOCATION out{static_cast(static_cast(Dout10.guest.Get())), D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, {0}}; + D3D12_TEXTURE_COPY_LOCATION from{static_cast(static_cast(R10.guest.Get())), D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, {0}}; + invoke(L.list.Get(), 16, &to, 0u, 0u, 0u, &from, static_cast(nullptr)); + invoke(L.list.Get(), 16, &out, 0u, 0u, 0u, &from, static_cast(nullptr)); + if (!c.close(L)) return false; + // The recording must not leave cache entries behind that name these resources by their raw pointer. + unsigned entries = 0; + for (const Res* r : {&R10, &D10, &Dout10}) entries += c.probe(r, &L).cache_entries; + if (on ? entries != 0 : entries == 0) { // switch off: the old upload bookkeeping runs, which shows the probe sees it + std::printf("FAIL: %u cache entries name the resources of a texture copy (switch %s)\n", entries, on ? "on" : "off"); + return false; + } + c.release(R10); + c.release(D10); + if (!c.sync(c.direct) || !c.sync(c.other) || !c.sync(c.gated) || !c.sync(c.copy)) return false; + if (!c.stays("texture region released", "early release (texture copy)")) return false; + c.execute(c.direct, L); + if (!c.sync(c.direct) || !c.holds(Dout10.guest.Get(), seed_source, "Dout10")) return false; + if (!SUCCEEDED(c.reset_list(L))) return false; + if (on) R10.freed = D10.freed = true; + return c.settle("texture region list reset", "a Reset list kept its texture copy resources"); +} + +// 4c: ResolveSubresource (slot 19), destination released after recording. +bool resolve_destination(Context& c, bool on, GuestList& L) +{ + D3D12_RESOURCE_DESC msaa = c.desc; + msaa.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET; + msaa.SampleDesc = {4, 0}; + const D3D12_HEAP_PROPERTIES heap{D3D12_HEAP_TYPE_DEFAULT}; + Res& source = c.pool.emplace_back(); + source.name = "resolve source"; + source.bytes = c.device->GetResourceAllocationInfo(0, 1, &msaa).SizeInBytes; + if (!require(invoke(c.guest, 127, &heap, D3D12_HEAP_FLAG_NONE, &msaa, D3D12_RESOURCE_STATE_COMMON, nullptr, nullptr, 0u, + nullptr, &c.iid_resource[0], source.guest.GetAddressOf()), "msaa source")) return false; + Res& Dr = c.make_texture("resolve destination"); + Res& Dkeep = c.make_texture("resolve destination, kept"); + const struct { + D3D12_DESCRIPTOR_HEAP_DESC desc; + UINT64 backing, bytes; + } rtv_heap{{D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 1}, 0, 0}; + ComPtr heap_object; + if (!require(invoke(c.guest, 14, &rtv_heap, &__uuidof(ID3D12DescriptorHeap), heap_object.GetAddressOf()), "rtv heap")) return false; + const UINT64 handle = invoke(heap_object.Get(), 9); + const D3D12_RENDER_TARGET_VIEW_DESC view{DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_RTV_DIMENSION_TEXTURE2DMS, {}}; + invoke(c.guest, 20, source.guest.Get(), &view, handle); + constexpr float magenta[]{1.0f, 0.0f, 1.0f, 1.0f}; + if (!c.make_list(L)) return false; + invoke(L.list.Get(), 52, handle, magenta, 0u, static_cast(nullptr)); + invoke(L.list.Get(), 19, Dr.guest.Get(), 0u, source.guest.Get(), 0u, static_cast(DXGI_FORMAT_R8G8B8A8_UNORM)); + invoke(L.list.Get(), 19, Dkeep.guest.Get(), 0u, source.guest.Get(), 0u, static_cast(DXGI_FORMAT_R8G8B8A8_UNORM)); + if (!c.close(L)) return false; + { + const RetireProbe p = c.probe(&Dr, &L); + if (p.cache_entries) { + std::printf("FAIL: the resolve destination has %u cache entries\n", p.cache_entries); + return false; + } + } + c.release(Dr); + if (!c.sync(c.direct) || !c.sync(c.other) || !c.sync(c.gated) || !c.sync(c.copy)) return false; + if (!c.stays("resolve destination released", "early release (resolve destination)")) return false; + c.execute(c.direct, L); + if (!c.sync(c.direct)) return false; + // Every pixel of the kept destination is the clear colour: the resolve ran. + const auto real = desktop_object(c.guest, c.device, Dkeep.guest.Get()); + if (!real) return false; + if (!require(c.own_allocator->Reset(), "own allocator") || !require(c.own_list->Reset(c.own_allocator.Get(), nullptr), "own list")) return false; + c.own_barrier(real.Get(), D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_SOURCE); + const D3D12_TEXTURE_COPY_LOCATION from{real.Get(), D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, {0}}; + const auto to = c.footprint(c.readback.Get()); + c.own_list->CopyTextureRegion(&to, 0, 0, 0, &from, nullptr); + c.own_barrier(real.Get(), D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_COMMON); + if (!c.own_run()) return false; + void* mapped = nullptr; + const D3D12_RANGE all{0, image_bytes}; + if (!require(c.readback->Map(0, &all, &mapped), "readback map")) return false; + bool uniform = true; + for (UINT i = 0; i < image_bytes; i += 4) { + const auto* p = static_cast(mapped) + i; + uniform = uniform && p[0] == 255 && p[1] == 0 && p[2] == 255 && p[3] == 255; + } + c.readback->Unmap(0, nullptr); + if (!uniform) { + std::puts("FAIL: the resolved destination is not the clear colour"); + return false; + } + if (!SUCCEEDED(c.reset_list(L))) return false; + if (on) Dr.freed = true; + return c.settle("resolve list reset", "a Reset list kept its resolve destination"); +} + +// 5: a list destroyed while its submission is still held, and a copy queue. +bool in_flight(Context& c, bool on, Res& R, Res& D, Res& Dout, GuestList& L, GuestQueue& queue, D3D12_COMMAND_LIST_TYPE type, + bool destroy_list, const char* fail) +{ + if (!c.make_list(L, type)) return false; + invoke(L.list.Get(), 17, D.guest.Get(), R.guest.Get()); + invoke(L.list.Get(), 17, Dout.guest.Get(), R.guest.Get()); + if (!c.close(L)) return false; + ComPtr gate; + if (!require(invoke(c.guest, 36, UINT64{0}, D3D12_FENCE_FLAG_NONE, &__uuidof(ID3D12Fence), gate.GetAddressOf()), "gate fence") || + !require(invoke(queue.queue.Get(), 17, gate.Get(), UINT64{1}), "queue wait")) + return false; + c.execute(queue, L); + c.release(R); + c.release(D); + if (destroy_list) L.list.Reset(); + else if (!SUCCEEDED(c.reset_list(L, type))) return false; + if (!c.stays("in flight", fail)) return false; + if (!require(invoke(gate.Get(), 10, UINT64{1}), "gate signal") || !c.sync(queue)) return false; + if (on) R.freed = D.freed = true; + if (!c.settle("in flight passed", "resources kept after their submission passed")) return false; + return c.holds(Dout.guest.Get(), seed_source, "output of the held submission"); +} + +// 6: a recording that is still open. D3D12 refuses a Reset of an open list, so that Reset must leave its holds; a list +// destroyed while open drops the recording state that names the resources before their holds fall. +bool open_list(Context& c, bool on, Res& R7, Res& D7, Res& R11, Res& D11, GuestList& L, GuestList& L11) +{ + if (!c.make_list(L)) return false; + invoke(L.list.Get(), 17, D7.guest.Get(), R7.guest.Get()); + { + const RetireProbe p = c.probe(nullptr, &L); + if (p.list_states != 2) { + std::printf("FAIL: the open recording moved %u resources out of COMMON, expected 2\n", p.list_states); + return false; + } + } + c.release(R7); + c.release(D7); + if (!c.sync(c.direct) || !c.sync(c.other) || !c.sync(c.gated) || !c.sync(c.copy)) return false; + if (!c.stays("open list", "early release (open list)")) return false; + const HRESULT hr = c.reset_list(L); + std::printf("Reset of an open list: 0x%08lx\n", static_cast(hr)); + if (SUCCEEDED(hr)) { + const RetireProbe p = c.probe(nullptr, &L); + if (on && (p.list_states != 0 || p.list_holds != 0)) { + std::printf("FAIL: reset kept render state of a dropped recording (%u states, %u holds)\n", p.list_states, p.list_holds); + return false; + } + if (on) R7.freed = D7.freed = true; + if (!c.settle("open list reset", "a Reset open list kept its resources")) return false; + } else if (!c.stays("open list, reset refused", "early release (refused Reset)")) return false; + // The recording closes and runs without touching anything freed. + if (!c.close(L)) return false; + c.execute(c.direct, L); + if (!c.sync(c.direct)) return false; + + if (!c.make_list(L11)) return false; + void* const destroyed = L11.list.Get(); // the wrapper outlives its Release + invoke(L11.list.Get(), 17, D11.guest.Get(), R11.guest.Get()); + { + const RetireProbe p = c.probe(nullptr, &L11); + if (p.list_states != 2 || (on && p.list_holds != 2)) { + std::printf("FAIL: the open recording has %u states and %u holds, expected 2 and 2\n", p.list_states, p.list_holds); + return false; + } + } + c.release(R11); + c.release(D11); + if (!c.sync(c.direct) || !c.sync(c.other) || !c.sync(c.gated) || !c.sync(c.copy)) return false; + if (!c.stays("open list destroyed", "early release (open list, before destroy)")) return false; + L11.list.Reset(); + RetireProbe after{}; + x2w_d3d12_retire_probe(nullptr, destroyed, &after); + if (on && (after.list_states != 0 || after.list_holds != 0)) { + std::printf("FAIL: reset kept render state of a dropped recording (%u states, %u holds)\n", after.list_states, after.list_holds); + return false; + } + if (on) R11.freed = D11.freed = true; + return c.settle("open list destroyed", "a destroyed open list kept its resources"); +} + +// 7: a release with no list at all waits for the release-time fence of a held queue. +bool release_time_fence(Context& c, bool on) +{ + Res& Zg = c.make_texture("Zg"); + 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; + c.release(Zg); + if (!c.sync(c.direct) || !c.sync(c.other) || !c.sync(c.copy)) return false; + if (!c.stays("release-time fence held", "early release (release-time fence)")) return false; + if (!require(invoke(gate.Get(), 10, UINT64{1}), "gate signal") || !c.sync(c.gated)) return false; + if (on) Zg.freed = true; + return c.settle("release-time fence passed", "a resource kept after the release-time fence passed"); +} + +// 8: what keeps the old lifetime, next to what retires. +bool classes(Context& c, bool on) +{ + constexpr SIZE_T page = D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT; + auto* title_memory = static_cast(VirtualAlloc(nullptr, page, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); + if (!title_memory) return false; + Res& Z127 = c.make_texture("Z127"); + Res& Z27 = c.make_texture("Z27", D3D12_RESOURCE_FLAG_NONE, true); + Res& B = c.make_buffer("B (buffer)"); + Res& G = c.make_texture("G (render target)", D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET); + Res& V = c.make_texture("V (view)"); + Res& M = c.make_texture("M (MakeResident)"); + Res& P = c.make_texture("P (presented)"); + Res& T = c.pool.emplace_back(); + T.name = "T (title memory)"; + T.bytes = c.texture_bytes = c.device->GetResourceAllocationInfo(0, 1, &c.desc).SizeInBytes; + if (!require(invoke(c.guest, 133, title_memory, &c.desc, D3D12_RESOURCE_STATE_COMMON, nullptr, &c.iid_resource[0], + T.guest.GetAddressOf()), "slot 133 texture")) return false; + if (!c.expect("classes created", "the control resources are not all live")) return false; + + // A view, MakeResident and Present each take their resource out of the class. + const struct { + D3D12_DESCRIPTOR_HEAP_DESC desc; + UINT64 backing, bytes; + } view_heap{{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 1}, 0, 0}; + ComPtr heap_object; + if (!require(invoke(c.guest, 14, &view_heap, &__uuidof(ID3D12DescriptorHeap), heap_object.GetAddressOf()), "view 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; + invoke(c.guest, 18, V.guest.Get(), &srv, invoke(heap_object.Get(), 9)); + IUnknown* residents[] = {M.guest.Get()}; + if (!require(invoke(c.guest, 34, 1u, residents), "MakeResident")) return false; + void* surface = P.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; + + struct Control { Res* resource; const char* fail; }; + const Control controls[] = { + {&B, "a buffer was freed"}, {&G, "a render target was freed"}, {&T, "a texture with title memory was freed"}, + {&V, "a resource with a view was freed"}, {&M, "a resource passed to MakeResident was freed"}, + {&P, "the presented surface was freed"}}; + for (const Control& control : controls) { + c.release(*control.resource); + if (!c.sync(c.direct) || !c.sync(c.other) || !c.sync(c.gated) || !c.sync(c.copy)) return false; + if (!c.stays(control.resource->name, control.fail)) return false; + } + c.release(Z127); + c.release(Z27); + if (!c.sync(c.direct) || !c.sync(c.other) || !c.sync(c.gated) || !c.sync(c.copy)) return false; + if (on) Z127.freed = Z27.freed = true; + if (!c.settle("class released", "a resource of the class kept its desktop object")) return false; + VirtualFree(title_memory, 0, MEM_RELEASE); + 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"))) 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(); + } + DXGI_ADAPTER_DESC1 adapter_desc{}; + adapter->GetDesc1(&adapter_desc); + char switch_value[2]{}; + const bool switch_on = GetEnvironmentVariableA("X2W_D3D12_RELEASE_RETIRED", switch_value, sizeof(switch_value)) == 1 && + switch_value[0] == '1'; + const bool off_mode = argc == 3; + if (switch_on == off_mode) { + std::puts("FAIL: the X2W_D3D12_RELEASE_RETIRED environment does not match the requested mode"); + return 2; + } + std::printf("adapter=%ls debug_layer=%s mode=%s\n", adapter_desc.Description, debug ? "enabled" : "off", off_mode ? "off" : "on"); + const bool on = !off_mode; + + Context c{guest.Get(), device.Get(), debug.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); + const D3D12_COMMAND_QUEUE_DESC direct{}; + const D3D12_HEAP_PROPERTIES upload_heap{D3D12_HEAP_TYPE_UPLOAD}, readback_heap{D3D12_HEAP_TYPE_READBACK}; + 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}; + 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")) return 4; + if (!c.make_queue(c.direct) || !c.make_queue(c.other) || !c.make_queue(c.gated) || + !c.make_queue(c.copy, D3D12_COMMAND_LIST_TYPE_COPY)) return 4; + if (!c.make_list(c.drain_list) || !c.close(c.drain_list)) return 4; + if (!x2w_d3d12_budget_snapshot(&c.base, sizeof(c.base))) { + std::puts("FAIL: budget snapshot unavailable"); + return 4; + } + + // Resources. Sources carry the source pattern, destinations the sentinel. + Res& R = c.make_texture("R"); + Res& Rb = c.make_texture("Rb"); + Res& Rc = c.make_texture("Rc"); + Res& Rs = c.make_texture("Rs"); + Res& R7 = c.make_texture("R7"); + Res& R8 = c.make_texture("R8"); + Res& R9 = c.make_texture("R9"); + Res& R10 = c.make_texture("R10"); + Res& R11 = c.make_texture("R11"); + Res* sources[] = {&R, &Rb, &Rc, &Rs, &R7, &R8, &R9, &R10, &R11}; + Res& D1 = c.make_texture("D1"); + Res& D2 = c.make_texture("D2"); + Res& D3 = c.make_texture("D3"); + Res& D4 = c.make_texture("D4"); + Res& D5 = c.make_texture("D5"); + Res& Dout5 = c.make_texture("Dout5"); + Res& D7 = c.make_texture("D7"); + Res& D8 = c.make_texture("D8"); + Res& Dout8 = c.make_texture("Dout8"); + Res& D9 = c.make_texture("D9"); + Res& Dout9 = c.make_texture("Dout9"); + Res& D10 = c.make_texture("D10"); + Res& Dout10 = c.make_texture("Dout10"); + Res& D11 = c.make_texture("D11"); + Res* destinations[] = {&D1, &D2, &D3, &D4, &D5, &Dout5, &D7, &D8, &Dout8, &D9, &Dout9, &D10, &Dout10, &D11}; + for (Res* r : sources) if (!c.fill(r->guest.Get(), seed_source)) return 4; + for (Res* r : destinations) if (!c.fill(r->guest.Get(), seed_sentinel)) return 4; + if (!c.expect("allocated", "the resources are not all live")) return 5; + + GuestList L1, L2, L3, L4, L5, L6, L8, L9, L10, L11, L12; + if (!closed_lists(c, on, R, D1, D2, L1, L2)) return 5; + std::puts("1 closed lists: R stays while both lists are unsubmitted, then both readbacks"); + if (!discards(c, on, Rb, D3, Rc, D4, L3, L4)) return 5; + std::puts("2 discard: a Reset list and a destroyed list free their resource without a submission"); + if (!second_submission(c, on, R, D2, L2)) return 5; + std::puts("3 second submission: held behind its own fence, then freed"); + if (!destination_released(c, on, Rs, D5, Dout5, L5)) return 5; + std::puts("4a copy destination released after recording stays until its list drops it"); + if (!texture_region(c, on, R10, D10, Dout10, L10)) return 5; + std::puts("4b CopyTextureRegion: both ends held"); + if (!resolve_destination(c, on, L12)) return 5; + std::puts("4c ResolveSubresource: destination held"); + if (!in_flight(c, on, R8, D8, Dout8, L8, c.gated, D3D12_COMMAND_LIST_TYPE_DIRECT, true, "early release (list destroyed in flight)")) return 5; + std::puts("5a list destroyed while its submission is held"); + if (!in_flight(c, on, R9, D9, Dout9, L9, c.copy, D3D12_COMMAND_LIST_TYPE_COPY, false, "early release (copy queue)")) return 5; + std::puts("5b copy queue"); + if (!open_list(c, on, R7, D7, R11, D11, L6, L11)) return 5; + std::puts("6 open recording: a refused Reset keeps its holds, a destroyed open list drops them"); + if (!release_time_fence(c, on)) return 5; + std::puts("7 release-time fence: a release with no list waits for the held queue"); + if (!classes(c, on)) return 5; + std::puts("8 classes: buffer, render target, title memory, view, MakeResident and Present keep the old lifetime"); + } 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 checks passed" : "switch-off checks passed"); + return 0; +} From 1ecd4cfc1cdcd144432e1bcecc9fa93b5444f839 Mon Sep 17 00:00:00 2001 From: JB2WIN Date: Wed, 25 Nov 2026 17:32:58 +0100 Subject: [PATCH 2/2] startup: tighten the retire-class fixture, docs and comments (review follow-up) - Check the CopyResource destination hold by behaviour first: the fixture no longer asserts the hold count before the destination-released stage. - The retire probe export returns FALSE without the switch. - Document that the switch needs X2W_D3D12_RENDER=1, that a title exporting __XMemAllocationHooks__ leaves slot 127 outside the class, and the debug layer skip. Lists drop their holds on Reset, destruction or a Close that fails. - Take the submission reference only after its fence was signalled; shorten comments. AI-assisted (Claude Code) Co-Authored-By: Claude Opus 5.5 Refs #2379 --- docs/startup-runtime.md | 12 ++++++--- src/startup_stubs/d3d12_xs_device.cpp | 35 +++++++++++++-------------- tests/startup_resource_retire.cpp | 21 ++++++++++------ 3 files changed, 38 insertions(+), 30 deletions(-) diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index a3e3d79cb0..00cd3f1b9e 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -1265,7 +1265,7 @@ ctest --preset dev --no-tests=error -R '^startup_trap_header(_prefix_control|_pr | `X2W_SHADER_CACHE=` | translation cache: the runtime writes source requests `req_.{a,b,root}`, when needed RTV variants `req_.rtv`, and for device slot 67 compute pipelines `req_.{desc,sa,sb,data,root,c67}` (see [Compute pipeline requests](#compute-pipeline-requests)). A console pipeline that an `ExecuteIndirect` draw (list slot 61) refuses writes the same request as a direct draw, once per pipeline, and draws nothing (`startup_indirect_requests_warp`). Only direct draws poll for its manifest, so such a pipeline stays in the `missing` count until a direct draw uses it; the `x2w-render totals` line counts `pipelines first looked up by ExecuteIndirect N`. This is a per-process lookup count. Check for the ready marker `req_.a` to confirm a complete request is available. Run `tools/startup/gfx2hlsl.py --pending ` while the process is running, or start the run with `run.ps1 -Translate` (see [Translating shaders during a run](#translating-shaders-during-a-run)). Active draws poll for an absent manifest at most once per second per pipeline and use the published translation on a subsequent draw. The translator compiles `.vs.cso` and `.ps.cso` with `fxc.exe`: `X2W_FXC`, else the Windows SDK 10.0.26100.0 copy, else the newest `Windows Kits\10\bin\\x64`, else `PATH`. When none exists it writes `.fail` naming `X2W_FXC` without publishing a new manifest. `X2W_FXC=` (empty) publishes the manifest alone. Rerun `--pending` with compilation enabled to fill in missing bytecode for an existing manifest. | | `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: 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=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_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) | @@ -1331,7 +1331,9 @@ descriptor heap backing. `X2W_D3D12_RELEASE_RETIRED=1` ends the retained lifetime for one class: a texture created by device slot 27 or 127 that is two-dimensional, has one sample, no render-target, depth-stencil or unordered-access flag, lives in a -default heap without heap flags and has no title memory. Every other resource +default heap without heap flags and has no title memory. If the title exports +`__XMemAllocationHooks__`, every slot 127 resource gets title memory and none is in the class; the fixture runs +without that export. Every other resource keeps the lifetime described above. A resource leaves the class for good when a view is created for it (slots 18 to 21, also a refused one), when it is passed to MakeResident or Evict (slots 34 and 35), or when it is presented. Only @@ -1369,9 +1371,11 @@ list destroyed while its submission is held, a copy queue, an open list that D3D12 refuses to Reset and one that is destroyed, a release that no list refers to behind a held queue, and, in one run with the class, a buffer, render target, title-memory texture, viewed texture, resident texture and -presented texture that must stay retained. `startup_resource_retire_off_*` +presented texture that must stay retained. The fixture-only export +`x2w_d3d12_retire_probe` returns FALSE without the switch, like +`x2w_d3d12_budget_snapshot`. `startup_resource_retire_off_*` runs the same steps without the switch. The hardware cases report 77 without a -physical adapter. +physical adapter, and the debug-layer cases report 77 where the debug layer is not installed. ## Input script diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index 3c2a8382a9..b5b868e50e 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -153,7 +153,8 @@ struct alignas(16) WrapperOwn { ID3D12Resource* list_scratch; // Current recording's rectangle-list argument scratch, owned by its desktop allocator. bool list_close_failed; // Desktop Reset repeats a failed Close result indefinitely. bool tiled_address_srv; // Resource backed by 4 KiB tiled guest memory for translated draws. - bool retire_when_idle; // Resource: member of the retire class (X2W_D3D12_RELEASE_RETIRED), cleared by any other use. + bool retire_when_idle; // Resource: in the retire class (X2W_D3D12_RELEASE_RETIRED); cleared by any other use. Plain + // accesses: a race needs the guest to use a resource across its own final Release. bool list_ready; // CommandList (render mode): closed with recorded work, not yet submitted bool compute_pipeline; // PipelineState: a desktop compute pipeline u64 compute_trace_key; // Opt-in trace: selected slot 62 container hash @@ -773,8 +774,9 @@ bool release_retired_enabled() // 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, that has no title memory. Every use of such a resource reaches the shim through the handlers that -// retire_hold covers or that clear the flag; see docs/startup-runtime.md#d3d12-resource-budget. +// flags, that has no title memory (with the title's __XMemAllocationHooks__ export every slot 127 resource gets title +// memory, so none is in the class then). Every use reaches the shim through handlers that retire_hold covers 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) { @@ -3433,6 +3435,7 @@ void __stdcall queue_execute(Wrapper* self, UINT count, void* const* lists) if (first_calls(calls)) log("x2w-d3d12 CommandQueue::ExecuteCommandLists count=%u -> not submitted (noop lists)", count); return; } + // No hold or flight is recorded here: the copy handlers that create holds exist only in render mode. std::vector real(count); for (UINT i = 0; i < count; ++i) real[i] = reinterpret_cast(unwrap(reinterpret_cast(lists[i]))); static_cast(self->own().real)->ExecuteCommandLists(count, real.data()); @@ -4195,21 +4198,16 @@ HRESULT __stdcall device_place_resource_x(Wrapper* self, void* address, const D3 #include "d3d12_memory_srv.inl" #include "startup_stubs/list_copy.inl" -// X2W_D3D12_RELEASE_RETIRED=1 (opt-in; docs/startup-runtime.md#d3d12-resource-budget). The desktop object of a resource -// of the retire class (retire_class) is released after its final guest Release, once both hold: -// - Release-time fences: every queue the shim created owns a private desktop fence. The final Release signals each of -// them, so the recorded values lie behind everything already submitted, and the drain compares them. A release with -// no registered queue, or one whose fence failed, retires nothing. -// - No use is left: a list that recorded a copy, texture copy or resolve of the resource holds a desktop reference -// until the list is Reset, closed with an error or destroyed (an unsubmitted list is discarded without any -// submission), and every submission of such a list holds one until its queue passes a fence signalled right behind it. -// Nothing waits. The drain runs at the start of ExecuteCommandLists and Present and only try-locks retire_lock; -// desktop references are dropped after the lock is released. A hold, marker or submission fence that cannot be recorded -// leaves the resource retained for the process, which is the lifetime without the switch. The wrapper itself stays. +// X2W_D3D12_RELEASE_RETIRED=1 (docs/startup-runtime.md#d3d12-resource-budget): the desktop object of a retire class +// member is released after its final guest Release once (1) the release-time fence of every queue has passed (each queue +// owns a private fence that the Release signals) and (2) no list or submission names it: a list holds a desktop +// reference from a forwarded copy until it is Reset, fails to Close or is destroyed, and each submission holds one until +// its queue passes a fence signalled behind it. Nothing waits; the drain only try-locks and drops references outside +// the lock. What cannot be recorded stays retained for the process, the lifetime without the switch. constexpr LONG retired_refs = -0x40000000; SRWLOCK retire_lock = SRWLOCK_INIT; // a leaf: taken after draw_lock and allocator_lock, nothing is taken under it struct RetireQueue { - ID3D12CommandQueue* queue; + ID3D12CommandQueue* queue; // no reference: release() never frees a queue object ID3D12Fence* fence; // null: no marker for this queue, so nothing retires UINT64 signaled; }; @@ -4257,8 +4255,8 @@ void retire_leave_class(const void* object) } // After a copy, texture copy or resolve was forwarded to the desktop list: the list keeps a desktop reference to the -// resource until its recording is dropped. Only wrappers can be members of the class, so a raw desktop pointer is -// never held (and never retired). +// resource until its recording is dropped. Only wrappers are members of the class, so a raw desktop pointer is never +// held. Assumption, not proven: the guest has no raw pointer to the desktop object of a class member. void retire_hold(Wrapper* list, Wrapper* resource) { if (!resource || !resource->own().retire_when_idle) return; @@ -4324,8 +4322,8 @@ void retire_note_submission(ID3D12CommandQueue* queue, const std::vectorAddRef(); if (SUCCEEDED(queue->Signal(q.fence, q.signaled + 1))) { + for (ID3D12Resource* resource : named) resource->AddRef(); ++q.signaled; retire_flights.push_back({index, q.signaled, std::move(named)}); InterlockedIncrement(&retire_pending); @@ -4444,6 +4442,7 @@ extern "C" __declspec(dllexport) BOOL x2w_d3d12_retire_probe(void* resource, voi { if (!out) return FALSE; *out = {}; + if (!release_retired_enabled()) return FALSE; // like x2w_d3d12_budget_snapshot: nothing to report without the switch if (Wrapper* r = as_wrapper(resource); r && r->own().kind == resource_kind && r->own().real) { auto* real = static_cast(r->own().real); AcquireSRWLockExclusive(&draw_lock); diff --git a/tests/startup_resource_retire.cpp b/tests/startup_resource_retire.cpp index c10b02f50f..3eeb50f6f7 100644 --- a/tests/startup_resource_retire.cpp +++ b/tests/startup_resource_retire.cpp @@ -16,7 +16,9 @@ // 5 an open recording: D3D12 refuses its Reset (the holds stay); a list destroyed while open drops its state first. // 6 a release that no list names waits for the release-time fence of a held queue. // 7 buffer, render target, title memory, a view, MakeResident and Present keep the old lifetime next to ones that retire. -// "off" runs the same steps without the switch: nothing is ever freed. +// "off" runs the same steps without the switch: nothing is ever freed, and the probe export reports nothing. +// Present opens the output window of the stand-in, as the other present fixtures do; without a desktop session the +// window presenter fails quietly and the case still holds, since the resource leaves the class before any window work. #include "startup_stubs/resource_budget.h" #include @@ -341,10 +343,12 @@ struct Context { for (int i = 0; i < 4; ++i) drain(); return expect(stage, fail); } + // Without the switch the export reports nothing (FALSE, zeros). + mutable bool probe_available = false; RetireProbe probe(const Res* r, const GuestList* l) const { RetireProbe p{}; - x2w_d3d12_retire_probe(r ? r->guest.Get() : nullptr, l ? l->list.Get() : nullptr, &p); + probe_available = x2w_d3d12_retire_probe(r ? r->guest.Get() : nullptr, l ? l->list.Get() : nullptr, &p) != FALSE; return p; } }; @@ -364,8 +368,8 @@ bool closed_lists(Context& c, bool on, Res& R, Res& D1, Res& D2, GuestList& L1, // The release-time fence of every queue has passed. The lists still name R. if (!c.stays("closed lists", "early release (closed lists)")) return false; const RetireProbe p = c.probe(&D1, &L1); - if (p.list_holds != 2 || p.cache_entries) { - std::printf("FAIL: list L1 holds %u resources (expected 2), %u cache entries on a destination\n", p.list_holds, p.cache_entries); + if (p.cache_entries) { + std::printf("FAIL: %u cache entries on a copy destination\n", p.cache_entries); return false; } } else if (!c.stays("closed lists, switch off", "switch off changed the lifetime")) return false; @@ -446,8 +450,9 @@ bool texture_region(Context& c, bool on, Res& R10, Res& D10, Res& Dout10, GuestL // The recording must not leave cache entries behind that name these resources by their raw pointer. unsigned entries = 0; for (const Res* r : {&R10, &D10, &Dout10}) entries += c.probe(r, &L).cache_entries; - if (on ? entries != 0 : entries == 0) { // switch off: the old upload bookkeeping runs, which shows the probe sees it - std::printf("FAIL: %u cache entries name the resources of a texture copy (switch %s)\n", entries, on ? "on" : "off"); + if (entries != 0 || c.probe_available != on) { + std::printf("FAIL: %u cache entries name the resources of a texture copy (switch %s, probe %s)\n", entries, + on ? "on" : "off", c.probe_available ? "available" : "off"); return false; } c.release(R10); @@ -562,7 +567,7 @@ bool open_list(Context& c, bool on, Res& R7, Res& D7, Res& R11, Res& D11, GuestL invoke(L.list.Get(), 17, D7.guest.Get(), R7.guest.Get()); { const RetireProbe p = c.probe(nullptr, &L); - if (p.list_states != 2) { + if (on && p.list_states != 2) { std::printf("FAIL: the open recording moved %u resources out of COMMON, expected 2\n", p.list_states); return false; } @@ -592,7 +597,7 @@ bool open_list(Context& c, bool on, Res& R7, Res& D7, Res& R11, Res& D11, GuestL invoke(L11.list.Get(), 17, D11.guest.Get(), R11.guest.Get()); { const RetireProbe p = c.probe(nullptr, &L11); - if (p.list_states != 2 || (on && p.list_holds != 2)) { + if (on && (p.list_states != 2 || p.list_holds != 2)) { std::printf("FAIL: the open recording has %u states and %u holds, expected 2 and 2\n", p.list_states, p.list_holds); return false; }