From 141f6857573ba1c2f556b842e73a24865ce9923c Mon Sep 17 00:00:00 2001 From: triggered02 <153171514+triggered02@users.noreply.github.com> Date: Wed, 25 Nov 2026 23:05:58 +0530 Subject: [PATCH 1/6] startup: release retired slot-133 title-memory textures and track slot-18 SRV reuse (slice 2) --- CMakeLists.txt | 16 + docs/experiments.md | 13 + docs/startup-runtime.md | 58 ++- src/startup_stubs/d3d12_capture.inl | 44 +- src/startup_stubs/d3d12_draw.inl | 5 +- src/startup_stubs/d3d12_xs_device.cpp | 149 +++++- src/startup_stubs/list_copy.inl | 16 +- src/startup_stubs/list_copy_texture.inl | 12 +- tests/startup_resource_retire.cpp | 5 +- tests/startup_resource_retire_title.cpp | 629 ++++++++++++++++++++++++ 10 files changed, 897 insertions(+), 50 deletions(-) create mode 100644 tests/startup_resource_retire_title.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index ed00bb5c12..3adaa32fa1 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1344,6 +1344,22 @@ 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() +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) +target_link_libraries(startup_resource_retire_title PRIVATE d3d12_xs_shim d3d12 dxgi) +foreach(backend IN ITEMS warp hardware) + foreach(debug IN ITEMS 0 1) + set(retire_title_env "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=${debug}") + add_test(NAME startup_resource_retire_title_${backend}_debug${debug} COMMAND startup_resource_retire_title ${backend}) + set_tests_properties(startup_resource_retire_title_${backend}_debug${debug} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 + ENVIRONMENT "${retire_title_env};X2W_D3D12_RELEASE_RETIRED=1") + endforeach() + add_test(NAME startup_resource_retire_title_off_${backend} COMMAND startup_resource_retire_title ${backend} off) + set_tests_properties(startup_resource_retire_title_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_RESOURCE_INDEX_CHECK=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 3dbacf88a6..d75acbf1cb 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -14822,3 +14822,16 @@ check and requires the old exception to come back: The checks are `tests/startup_gfx2hlsl_handler_arity_check.py`, `…_image_arity_check.py`, `…_operand_count_check.py` and `…_scalar_arity_check.py`. They run on Linux and Windows without D3D12 or game data, because a refusal is observable at the `Stage` entry point. +## Opt-in release of retired slot-133 title-memory textures (Slice 2) + +Building on #2443 (Slice 1), `X2W_D3D12_RELEASE_RETIRED=1` extends desktop object retirement to device slot 133 (`CreatePlacedResourceX`) committed 2D textures with `title_memory` (non-RT/DS/UAV, 1-sample, `DEFAULT` heap), while keeping slot 127 `__XMemAllocationHooks__` resources out of the class: + +- `drain_retired_resources()` erases the retired wrapper from `resource_address_index()` (under `note_lock`), erases its desktop pointer from `texture_uploads()` (under `draw_lock`), and cleans stale `written_textures()` entries whose generation was not bumped by a newer allocation/write at the same title address (also cleared immediately on final `Release` when no view or live sibling shares the address). +- `list_copy_texture.inl` gates `upload_texture()` on `title_memory != nullptr` rather than `!retire_when_idle` and guards `texture_uploads()` accesses in `list_copy.inl` / `list_copy_texture.inl` with `draw_lock`. +- `view_slot<18>` (SRV) tracks descriptor slots via `HeapInfo::shadow` across `note_view`, `note_copy`, and heap destruction (falling back to `retire_leave_class` for untracked slots or slots 19–21), and `draw_translated` holds bound textures with `retire_hold`. + +[`tests/startup_resource_retire_title.cpp`](../tests/startup_resource_retire_title.cpp) (`startup_resource_retire_title_{warp,hardware}_debug0` and `_off_`) verifies slot 133 copy/upload holds and readbacks, same-address slot 70 (`existing_memory_texture`) reuse under `X2W_RESOURCE_INDEX_CHECK=1`, stale `bc7_width` `written_textures` cleanup on RGBA8 reuse, and `CopyDescriptorsSimple` / overwrite / heap-release SRV retirement across WARP (`Microsoft Basic Render Driver`) and `NVIDIA GeForce GTX 1660 SUPER`. + +```powershell +ctest --preset dev --no-tests=error -R '^startup_resource_(retire|budget)' -V +``` diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index 18ccd39a0a..d3c2c339b6 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -1344,33 +1344,47 @@ 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. 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 -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. +`X2W_D3D12_RELEASE_RETIRED=1` ends the retained lifetime for committed +2D textures that have one sample, no render-target, depth-stencil or +unordered-access flag, and live in a default heap without heap flags: +- **Slice 1**: slot 27 and slot 127 textures without title memory (if the title + exports `__XMemAllocationHooks__`, every slot 127 resource gets title memory + and stays out of the class). +- **Slice 2**: slot 133 (`CreatePlacedResourceX`) committed 2D textures with + title memory. Before their desktop `ID3D12Resource` is destroyed, they are + erased from `resource_address_index` and `texture_uploads`, and stale + `written_textures` entries whose generation has not changed are cleared so + reusing the same title address or desktop pointer does not skip uploads or + resolve a retired wrapper. + +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 +created for it (slots 19 to 21, also a refused one), when a slot 18 SRV targets +an untracked descriptor slot or is copied out of tracked heaps, when it is passed +to MakeResident or Evict (slots 34 and 35), or when it is presented. Tracked +slot 18 SRVs (including slot 70 `device_memory_srv`) keep the resource retained +while any descriptor slot in `HeapInfo::shadow` names it (updated across +`note_view`, `CopyDescriptors*`, and heap `Release`), and translated draws hold +bound textures via `retire_hold`. 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 +passed, all tracked slot 18 SRV descriptor refs have dropped to zero, and no +recorded list or submission still holds it. A copy (list slot 17), texture copy (16), +resolve destination (19), or translated draw SRV bind 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. +release is not supported with the switch. 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, @@ -1386,8 +1400,12 @@ 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. The fixture-only export +render target, viewed texture (while its slot-18 SRV stays live), resident texture and +presented texture that must stay retained, alongside slot 133 title-memory textures. +`startup_resource_retire_title_{warp,hardware}_debug{0,1}` additionally test slot 133 +`CopyTextureRegion`/`CopyResource` upload holds, same-address slot 70 (`existing_memory_texture`) +reuse with `X2W_RESOURCE_INDEX_CHECK=1`, stale `written_textures` `bc7_width` cleanup, +and slot-18 SRV `CopyDescriptorsSimple` / overwrite / heap-release lifetime. 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 diff --git a/src/startup_stubs/d3d12_capture.inl b/src/startup_stubs/d3d12_capture.inl index 6b40d70a2a..879f71f8e1 100644 --- a/src/startup_stubs/d3d12_capture.inl +++ b/src/startup_stubs/d3d12_capture.inl @@ -311,7 +311,17 @@ void note_view(int slot, u64 resource, u64 counter, const void* desc, std::size_ view_ids()[hash] = record.id; ++views_distinct; } - if (std::uint32_t* slot = shadow_slot(dest_desktop)) *slot = record.id + 1; + if (std::uint32_t* slot_ptr = shadow_slot(dest_desktop)) { + const std::uint32_t prev = *slot_ptr; + *slot_ptr = record.id + 1; + if (prev != record.id + 1) { + if (slot == 18 && resource && materialized) retire_add_view_ref(reinterpret_cast(resource)); + if (prev && prev - 1 < view_records().size() && view_records()[prev - 1].slot == 18 && view_materialized()[prev - 1]) + retire_release_view_ref(reinterpret_cast(view_records()[prev - 1].resource)); + } + } else if (slot == 18 && resource) { + retire_leave_class(reinterpret_cast(resource)); + } ReleaseSRWLockExclusive(¬e_lock); const std::size_t token_bytes = slot == 22 ? x2w_startup::title_sampler_stride : 32u; if (dest_title != dest_desktop && title_backed(dest_title, token_bytes) && @@ -329,8 +339,36 @@ void note_copy(u64 dest_title, u64 src_title, u64 dest_desktop, u64 src_desktop, std::uint32_t* to = shadow_slot(dest_desktop, &dest_room); const std::uint32_t* from = shadow_slot(src_desktop, &src_room); if (to && count <= dest_room) { - if (from && count <= src_room) std::memmove(to, from, u64{count} * 4); - else std::memset(to, 0, u64{count} * 4); + if (from && count <= src_room) { + for (UINT i = 0; i < count; ++i) { + 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_add_view_ref(reinterpret_cast(view_records()[src_id - 1].resource)); + } + for (UINT i = 0; i < count; ++i) { + const std::uint32_t old_id = to[i]; + if (old_id && old_id - 1 < view_records().size() && + view_records()[old_id - 1].slot == 18 && view_materialized()[old_id - 1]) + retire_release_view_ref(reinterpret_cast(view_records()[old_id - 1].resource)); + } + std::memmove(to, from, u64{count} * 4); + } else { + for (UINT i = 0; i < count; ++i) { + const std::uint32_t old_id = to[i]; + if (old_id && old_id - 1 < view_records().size() && + view_records()[old_id - 1].slot == 18 && view_materialized()[old_id - 1]) + retire_release_view_ref(reinterpret_cast(view_records()[old_id - 1].resource)); + } + std::memset(to, 0, u64{count} * 4); + } + } else if (from && count <= src_room) { + for (UINT i = 0; i < count; ++i) { + 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)); + } } ReleaseSRWLockExclusive(¬e_lock); const UINT stride = title_descriptor_stride(dest_title, increment); diff --git a/src/startup_stubs/d3d12_draw.inl b/src/startup_stubs/d3d12_draw.inl index 70019fe004..f63c83f839 100644 --- a/src/startup_stubs/d3d12_draw.inl +++ b/src/startup_stubs/d3d12_draw.inl @@ -2033,7 +2033,10 @@ bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UI return false; } if (texture && !upload_texture(self, resource, texture)) texture = nullptr; - if (texture) require_state(self, texture, sampled_state(self, texture)); + if (texture) { + require_state(self, texture, sampled_state(self, texture)); + if (resource && !resource->own().tiled_address_srv) retire_hold(self, resource); + } const bool had_texture = texture != nullptr; bool mismatched = false; static LONG shown; diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index 5df3194f4e..8acedf79de 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -156,6 +156,9 @@ struct alignas(16) WrapperOwn { bool tiled_address_srv; // Resource backed by 4 KiB tiled guest memory for translated draws. 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. + 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. 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 @@ -775,15 +778,18 @@ 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 (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. +// flags. Slot 27 and non-hooked slot 127 have no title memory; slot 133 committed 2D textures with title memory are +// included (cleaned from resource_address_index, texture_uploads and written_textures on retirement), while slot 127 +// 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) + const void* title_memory, bool allow_title_memory = false) { 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; + (desc.Flags & ~D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE) == D3D12_RESOURCE_FLAG_NONE && + (!title_memory || allow_title_memory); } template @@ -906,6 +912,10 @@ 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_add_view_ref(const void* object); +void retire_release_view_ref(const void* object); +void retire_drop_heap_views(Wrapper* heap); +void retire_note_title_release(Wrapper* w); void retire_hold(Wrapper* list, Wrapper* resource); void retire_drop_recording(Wrapper* list); void retire_discard_holds(Wrapper* list); @@ -919,9 +929,11 @@ ULONG __stdcall release(Wrapper* self) if (!refs) { if (self->own().budget) self->own().budget->end_use(); if (self->own().backing_budget) self->own().backing_budget->end_use(); + if (self->own().kind == descriptor_heap_kind) retire_drop_heap_views(self); if (self->own().kind == resource_kind && self->own().title_memory) { drop_mesh_lease_owner(self); retire_placement(self); + if (self->own().retire_when_idle) retire_note_title_release(self); } if (self->own().kind == list_kind && self->own().real) { discard_mesh_lease_recording(static_cast(self->own().real)); @@ -3842,13 +3854,17 @@ 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)); + // 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)); 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]) return 0; + if (!args[D]) { + if constexpr (N == 18) retire_leave_class(reinterpret_cast(a)); + return 0; + } const auto record_view = [&](bool materialized) { const u64 raw[4] = {a, b, c, d}; const int described = N == 19 ? 2 : (N == 17 || N == 22) ? 0 : 1; @@ -4167,6 +4183,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); *out = w; return S_OK; } @@ -4328,6 +4345,73 @@ void retire_leave_class(const void* object) if (Wrapper* w = as_wrapper(object)) w->own().retire_when_idle = false; } +void retire_add_view_ref(const void* object) +{ + if (!release_retired_enabled()) return; + if (Wrapper* w = as_wrapper(object); w && w->own().kind == resource_kind) + InterlockedIncrement(&w->own().retire_view_refs); +} + +void retire_release_view_ref(const void* object) +{ + if (!release_retired_enabled()) return; + if (Wrapper* w = as_wrapper(object); w && w->own().kind == resource_kind) + InterlockedDecrement(&w->own().retire_view_refs); +} + +void retire_drop_heap_views(Wrapper* heap) +{ + if (!release_retired_enabled() || !heap) return; + AcquireSRWLockExclusive(¬e_lock); + for (HeapInfo& h : heap_infos()) { + if (h.wrapper != reinterpret_cast(heap) || !h.shadow) continue; + for (std::uint32_t i = 0; i < h.count; ++i) { + const std::uint32_t id = h.shadow[i]; + if (!id) continue; + h.shadow[i] = 0; + if (id - 1 < view_records().size() && view_records()[id - 1].slot == 18 && view_materialized()[id - 1]) + retire_release_view_ref(reinterpret_cast(view_records()[id - 1].resource)); + } + } + ReleaseSRWLockExclusive(¬e_lock); +} + +bool retire_address_has_live_user(u64 address, const Wrapper* skip) +{ + bool other_live = false; + AcquireSRWLockShared(¬e_lock); + resource_address_index().for_each_reaching(address, 1, [&](const Wrapper* wrapper) { + if (wrapper == skip || reinterpret_cast(wrapper->own().title_memory) != address) return false; + if (InterlockedCompareExchange(const_cast(&wrapper->own().refs), 0, 0) > 0) { + other_live = true; + return true; + } + return false; + }); + ReleaseSRWLockShared(¬e_lock); + if (other_live) return true; + std::lock_guard lock(tiled_srv_mutex); + return tiled_srv_addresses.count(address) != 0; +} + +void retire_note_title_release(Wrapper* w) +{ + const u64 address = reinterpret_cast(w->own().title_memory); + if (!address) return; + const bool shared_addr = retire_address_has_live_user(address, w); + const bool no_views = InterlockedCompareExchange(&w->own().retire_view_refs, 0, 0) == 0; + AcquireSRWLockExclusive(&written_lock); + if (const auto found = written_textures().find(address); found != written_textures().end()) { + if (!shared_addr && no_views) { + written_textures().erase(found); + } else { + w->own().retire_has_written_gen = true; + w->own().retire_written_gen = found->second.generation; + } + } + ReleaseSRWLockExclusive(&written_lock); +} + // 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 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. @@ -4457,15 +4541,26 @@ void drain_retired_resources() { if (!InterlockedCompareExchange(&retire_pending, 0, 0)) return; constexpr std::size_t batch = 256; - std::vector dropped; + struct RetiredDrop { + Wrapper* wrapper; + ID3D12Resource* resource; + }; + std::vector dropped; + std::vector> dropped_flights; try { dropped.reserve(batch); + dropped_flights.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]; + Wrapper* w = item.wrapper; + if (InterlockedCompareExchange(&w->own().retire_view_refs, 0, 0) > 0) { + ++i; + continue; + } 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]; @@ -4473,10 +4568,9 @@ void drain_retired_resources() ++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)); + dropped.push_back({w, static_cast(w->own().real)}); w->own().real = nullptr; } else { InterlockedIncrement64(&retire_kept); // referenced again after its final Release @@ -4485,24 +4579,47 @@ void drain_retired_resources() retired_resources.pop_back(); InterlockedDecrement(&retire_pending); } - for (std::size_t i = 0; i < retire_flights.size() && dropped.size() < batch;) { + for (std::size_t i = 0; i < retire_flights.size() && dropped_flights.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()); + dropped_flights.push_back(std::move(flight.resources)); 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(); + for (const RetiredDrop& drop : dropped) { + if (drop.wrapper->own().title_memory) { + const u64 address = reinterpret_cast(drop.wrapper->own().title_memory); + { + x2w_startup::ExclusiveNoteLock guard(note_lock); + resource_address_index().erase(address, drop.wrapper); + } + if (drop.wrapper->own().retire_has_written_gen && !retire_address_has_live_user(address, drop.wrapper)) { + AcquireSRWLockExclusive(&written_lock); + if (const auto found = written_textures().find(address); + found != written_textures().end() && found->second.generation == drop.wrapper->own().retire_written_gen) + written_textures().erase(found); + ReleaseSRWLockExclusive(&written_lock); + } + } + AcquireSRWLockExclusive(&draw_lock); + texture_uploads().erase(drop.resource); + ReleaseSRWLockExclusive(&draw_lock); + drop.resource->Release(); const LONG64 total = InterlockedIncrement64(&retire_freed); if (total <= 8 || total % 1000 == 0) log("x2w-d3d12 retire: %lld desktop references dropped", total); } + for (const auto& resources : dropped_flights) { + for (ID3D12Resource* resource : resources) { + 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 diff --git a/src/startup_stubs/list_copy.inl b/src/startup_stubs/list_copy.inl index 7f5fa07aa8..a0ea8f77a2 100644 --- a/src/startup_stubs/list_copy.inl +++ b/src/startup_stubs/list_copy.inl @@ -83,12 +83,18 @@ bool sync_title_source(Wrapper* self, const CopyEndpoint& source) if (desc.Dimension != D3D12_RESOURCE_DIMENSION_BUFFER) { // A target or UAV holds what the GPU wrote; its title memory is never uploaded. if (desc.Flags & (D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET | D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL | D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS)) return true; - const auto written = texture_uploads().find(source.resource); if (list_wrote(self, source.resource)) return true; - if (written != texture_uploads().end() && written->second.gpu_written) return true; - if (!upload_texture(self, source.wrapper, source.resource)) return false; - const auto found = texture_uploads().find(source.resource); - return found != texture_uploads().end() && found->second.staged; + AcquireSRWLockExclusive(&draw_lock); + const auto written = texture_uploads().find(source.resource); + bool ok = false; + if (written != texture_uploads().end() && written->second.gpu_written) { + ok = true; + } else if (upload_texture(self, source.wrapper, source.resource)) { + const auto found = texture_uploads().find(source.resource); + ok = found != texture_uploads().end() && found->second.staged; + } + ReleaseSRWLockExclusive(&draw_lock); + return ok; } const auto* info = resource_info(source.wrapper); return info && info->placement == Placement::aliased_buffer; diff --git a/src/startup_stubs/list_copy_texture.inl b/src/startup_stubs/list_copy_texture.inl index 57ffaaf7c2..0727949da2 100644 --- a/src/startup_stubs/list_copy_texture.inl +++ b/src/startup_stubs/list_copy_texture.inl @@ -147,11 +147,17 @@ 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. - // 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) + // A resource without title memory has nothing to upload and leaves no texture_uploads() entry behind. + if (side_src.kind == x2w_list_copy_texture::Kind::subresource && src_wrapper->own().title_memory) { + AcquireSRWLockExclusive(&draw_lock); upload_texture(self, src_wrapper, real_src); - if (side_dst.kind == x2w_list_copy_texture::Kind::subresource && !dst_wrapper->own().retire_when_idle) + ReleaseSRWLockExclusive(&draw_lock); + } + if (side_dst.kind == x2w_list_copy_texture::Kind::subresource && dst_wrapper->own().title_memory) { + AcquireSRWLockExclusive(&draw_lock); upload_texture(self, dst_wrapper, real_dst); + ReleaseSRWLockExclusive(&draw_lock); + } 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; diff --git a/tests/startup_resource_retire.cpp b/tests/startup_resource_retire.cpp index 3eeb50f6f7..2787867a04 100644 --- a/tests/startup_resource_retire.cpp +++ b/tests/startup_resource_retire.cpp @@ -675,7 +675,7 @@ bool classes(Context& c, bool on) 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"}, + {&B, "a buffer was freed"}, {&G, "a render target 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) { @@ -685,8 +685,9 @@ bool classes(Context& c, bool on) } c.release(Z127); c.release(Z27); + c.release(T); 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 (on) Z127.freed = Z27.freed = T.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; diff --git a/tests/startup_resource_retire_title.cpp b/tests/startup_resource_retire_title.cpp new file mode 100644 index 0000000000..0f98c6f8a2 --- /dev/null +++ b/tests/startup_resource_retire_title.cpp @@ -0,0 +1,629 @@ +// X2W_D3D12_RELEASE_RETIRED=1 (Slice 2, Refs #2379): slot 133 (CreatePlacedResourceX) committed 2D textures with +// title_memory retire once no recorded list, submission, release-time fence, or tracked slot-18 SRV descriptor slot +// still refers to them, and are cleaned from resource_address_index, texture_uploads and written_textures before +// their desktop ID3D12Resource is destroyed. +// +// startup_resource_retire_title [off] +// +// Cases: +// 1 slot 133 title_memory texture upload/copy (CopyTextureRegion + CopyResource): held behind closed list and +// gated second submission, read back after copy, then retired to baseline. +// 2 resource_address_index + slot 70 (existing_memory_texture) same-address reuse while T1 is pending behind a +// held fence, with X2W_RESOURCE_INDEX_CHECK=1 verifying live index consistency. +// 3 written_textures stale bc7_width cleanup on address reuse (BC7 retired -> RGBA8 at same address uploads +// fresh CPU texels; newer generation preserved when a live view keeps an older resource pending). +// 4 descriptor & view reuse: view_slot<18> + CopyDescriptorsSimple + heap release + descriptor overwrite; +// stays retained while any tracked slot holds the SRV, retires once overwritten/freed and fences complete. +#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; + unsigned list_states; + unsigned list_holds; +}; +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*); +extern "C" __declspec(dllimport) void x2w_d3d12_bc7_4k_s_written(void*, UINT, UINT); + +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; + +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 = ""; + Category category = texture; + 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 MemorySrvInput { + D3D12_SHADER_RESOURCE_VIEW_DESC view; + UINT64 address; +}; +static_assert(offsetof(MemorySrvInput, address) == 0x28); + +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, 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, DXGI_FORMAT fmt = DXGI_FORMAT_R8G8B8A8_UNORM, + UINT width = side) const + { + D3D12_TEXTURE_COPY_LOCATION location{buffer, D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, {}}; + location.PlacedFootprint.Footprint = {fmt, width, side, 1, pitch}; + return location; + } + 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, D3D12_RESOURCE_FLAGS flags = D3D12_RESOURCE_FLAG_NONE) + { + const D3D12_HEAP_PROPERTIES heap{D3D12_HEAP_TYPE_DEFAULT}; + D3D12_RESOURCE_DESC d = desc; + d.Flags = flags; + 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; + } + Res& make_slot133(const char* name, void* address, DXGI_FORMAT fmt = DXGI_FORMAT_R8G8B8A8_UNORM, UINT width = side) + { + D3D12_RESOURCE_DESC d = desc; + d.Width = width; + d.Format = fmt; + Res& r = pool.emplace_back(); + r.name = name; + r.bytes = device->GetResourceAllocationInfo(0, 1, &d).SizeInBytes; + if (!require(invoke(guest, 133, address, &d, D3D12_RESOURCE_STATE_COMMON, 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(); + } + D3D12_TEXTURE_COPY_LOCATION footprint_tex(ID3D12Resource* tex) const + { + return {tex, D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, {0}}; + } + bool holds(IUnknown* resource, int seed, const char* what, DXGI_FORMAT fmt = DXGI_FORMAT_R8G8B8A8_UNORM, + UINT width = side) + { + 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(), fmt, width), 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); + const UINT row_bytes = fmt == DXGI_FORMAT_R8_UNORM ? width : width * 4; + UINT mismatches = 0; + for (UINT y = 0; y < side; ++y) + for (UINT x = 0; x < row_bytes; ++x) { + const UINT i = y * pitch + x; + if (src[i] != pattern_byte(seed, i)) ++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_b = base.live[texture].bytes, ret_b = base.retained[texture].bytes; + UINT64 live_n = base.live[texture].objects, ret_n = base.retained[texture].objects; + for (const Res& r : pool) { + if (r.category != texture) continue; + 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); + } +}; + +void fill_title_memory(void* address, int seed) +{ + auto* dst = static_cast(address); + for (UINT i = 0; i < image_bytes; ++i) dst[i] = pattern_byte(seed, i); +} + +// 1: slot 133 title_memory texture upload & copy lifetime across closed list and gated submission. +bool case1_slot133_copy_and_upload(Context& c, bool on, void* title_mem) +{ + fill_title_memory(title_mem, 5); + Res& T1 = c.make_slot133("T1", title_mem); + Res& D1 = c.make_committed("D1"); + Res& D2 = c.make_committed("D2"); + if (!c.fill_desktop(D1.guest.Get(), 99) || !c.fill_desktop(D2.guest.Get(), 99)) return false; + GuestList L1, L2; + if (!c.make_list(L1) || !c.make_list(L2)) return false; + const D3D12_TEXTURE_COPY_LOCATION to1{static_cast(static_cast(D1.guest.Get())), + D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, {0}}; + const D3D12_TEXTURE_COPY_LOCATION to2{static_cast(static_cast(D2.guest.Get())), + D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, {0}}; + const D3D12_TEXTURE_COPY_LOCATION from{static_cast(static_cast(T1.guest.Get())), + D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, {0}}; + invoke(L1.list.Get(), 16, &to1, 0u, 0u, 0u, &from, static_cast(nullptr)); + invoke(L2.list.Get(), 17, D2.guest.Get(), T1.guest.Get()); + if (!c.close(L1) || !c.close(L2)) return false; + // texture_uploads()[T1->real] must be populated when T1 has title_memory. + RetireProbe probe = {}; + if (on && (!x2w_d3d12_retire_probe(T1.guest.Get(), L1.list.Get(), &probe) || probe.cache_entries == 0)) { + std::printf("FAIL: slot 133 CopyTextureRegion did not populate texture_uploads (cache_entries=%u)\n", probe.cache_entries); + return false; + } + c.release(T1); + if (!c.sync(c.direct) || !c.sync(c.gated)) return false; + if (!c.stays("slot 133 released behind closed lists", "early release of slot 133 texture")) return false; + c.execute(c.direct, L1); + if (!c.sync(c.direct) || !c.holds(D1.guest.Get(), 5, "D1 CopyTextureRegion from slot 133")) return false; + if (!SUCCEEDED(c.reset_list(L1))) return false; + if (!c.stays("slot 133 still held by L2", "early release while L2 closed")) return false; + ComPtr gate; + if (!require(invoke(c.guest, 36, UINT64{0}, D3D12_FENCE_FLAG_NONE, &__uuidof(ID3D12Fence), gate.GetAddressOf()), "gate1") || + !require(invoke(c.gated.queue.Get(), 17, gate.Get(), UINT64{1}), "wait1")) + return false; + c.execute(c.gated, L2); + if (!SUCCEEDED(c.reset_list(L2))) return false; + if (!c.stays("slot 133 held by gated submission", "early release while gated submission in flight")) return false; + if (!require(invoke(gate.Get(), 10, UINT64{1}), "signal1") || !c.sync(c.gated)) return false; + if (on) T1.freed = true; + if (!c.settle("slot 133 retired", "slot 133 texture kept after fences passed")) return false; + return c.holds(D2.guest.Get(), 5, "D2 CopyResource from slot 133"); +} + +// 2: resource_address_index + slot 70 existing_memory_texture + same-address reuse while T1 is pending behind fence. +bool case2_same_address_and_slot70_reuse(Context& c, bool on, void* title_mem) +{ + fill_title_memory(title_mem, 11); + Res& T1 = c.make_slot133("T_addr1", title_mem, DXGI_FORMAT_R8_UNORM, pitch); + ComPtr gate; + if (!require(invoke(c.guest, 36, UINT64{0}, D3D12_FENCE_FLAG_NONE, &__uuidof(ID3D12Fence), gate.GetAddressOf()), "gate2") || + !require(invoke(c.gated.queue.Get(), 17, gate.Get(), UINT64{1}), "wait2")) + return false; + c.release(T1); + if (!c.stays("T_addr1 pending behind gate", "early release behind gate2")) return false; + // Reuse the exact same title_memory address while T1 is in retired_resources. + fill_title_memory(title_mem, 22); + Res& T2 = c.make_slot133("T_addr2", title_mem, DXGI_FORMAT_R8_UNORM, pitch); + const struct { + D3D12_DESCRIPTOR_HEAP_DESC desc; + UINT64 backing, bytes; + } heap_desc{{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 2}, 0, 0}; + ComPtr heap; + if (!require(invoke(c.guest, 14, &heap_desc, &__uuidof(ID3D12DescriptorHeap), heap.GetAddressOf()), "slot70 heap")) return false; + const UINT inc = c.device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); + const UINT64 h0 = invoke(heap.Get(), 9); + const UINT64 h1 = h0 + inc; + D3D12_RESOURCE_DESC r8_desc = c.desc; + r8_desc.Width = pitch; + r8_desc.Format = DXGI_FORMAT_R8_UNORM; + MemorySrvInput srv_in{}; + srv_in.address = reinterpret_cast(title_mem); + srv_in.view.Format = DXGI_FORMAT_R8_UNORM; + srv_in.view.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; + srv_in.view.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + srv_in.view.Texture2D.MipLevels = 1; + // Slot 70 exercises check_resource_address_index() (X2W_RESOURCE_INDEX_CHECK=1) and existing_memory_texture(). + invoke(c.guest, 70, &r8_desc, &srv_in, h0); + // Unblock T1: T1 retires cleanly, while T2 (held by slot 70 -> slot 18 SRV in heap[0]) remains live. + if (!require(invoke(gate.Get(), 10, UINT64{1}), "signal2") || !c.sync(c.gated)) return false; + if (on) T1.freed = true; + if (!c.settle("T_addr1 retired while T_addr2 live", "T_addr1 did not retire")) return false; + // Verify T2 still uploads seed 22 properly after T1 retired. + const D3D12_HEAP_PROPERTIES def_heap{D3D12_HEAP_TYPE_DEFAULT}; + Res& D = c.pool.emplace_back(); + D.name = "D_addr2"; + D.bytes = c.device->GetResourceAllocationInfo(0, 1, &r8_desc).SizeInBytes; + if (!require(invoke(c.guest, 127, &def_heap, D3D12_HEAP_FLAG_NONE, &r8_desc, D3D12_RESOURCE_STATE_COMMON, nullptr, + nullptr, 0u, nullptr, &c.iid_resource[0], D.guest.GetAddressOf()), "D_addr2")) + return false; + GuestList L; + if (!c.make_list(L)) return false; + const D3D12_TEXTURE_COPY_LOCATION to{static_cast(static_cast(D.guest.Get())), + D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, {0}}; + const D3D12_TEXTURE_COPY_LOCATION from{static_cast(static_cast(T2.guest.Get())), + D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, {0}}; + invoke(L.list.Get(), 16, &to, 0u, 0u, 0u, &from, static_cast(nullptr)); + if (!c.close(L)) return false; + c.execute(c.direct, L); + if (!c.sync(c.direct) || + !c.holds(D.guest.Get(), 22, "T_addr2 after T_addr1 retired", DXGI_FORMAT_R8_UNORM, pitch)) + return false; + if (!SUCCEEDED(c.reset_list(L))) return false; + // Also exercise slot 70 once more after T1 retired, then release heap and T2. + invoke(c.guest, 70, &r8_desc, &srv_in, h1); + c.release(T2); + if (!c.stays("T_addr2 kept while slot70 SRV live", "T_addr2 freed while SRV slots live")) return false; + heap.Reset(); + if (on) T2.freed = true; + return c.settle("T_addr2 retired after heap released", "T_addr2 kept after heap released"); +} + +// 3: written_textures stale bc7_width cleanup on address reuse, and preservation of a newer generation. +bool case3_written_textures_cleanup(Context& c, bool on, void* title_mem, void* fallback_mem) +{ + x2w_d3d12_bc7_4k_s_written(title_mem, side, side); + Res& Tb = c.make_slot133("T_bc7", title_mem, DXGI_FORMAT_BC7_UNORM); + c.release(Tb); + if (!c.sync(c.direct) || !c.sync(c.gated)) return false; + if (on) Tb.freed = true; + if (!c.settle("T_bc7 retired", "T_bc7 kept")) return false; + + // When retire is on, reusing title_mem for plain RGBA8 (no XG call) must upload fresh texels instead of + // skipping on stale bc7_width; in off mode Tb stayed retained at title_mem so use fallback_mem. + void* rgba_mem = on ? title_mem : fallback_mem; + fill_title_memory(rgba_mem, 33); + Res& Tc = c.make_slot133("T_rgba_after_bc7", rgba_mem, DXGI_FORMAT_R8G8B8A8_UNORM); + Res& Dc = c.make_committed("D_rgba_after_bc7"); + if (!c.fill_desktop(Dc.guest.Get(), 99)) return false; + GuestList L; + if (!c.make_list(L)) return false; + const D3D12_TEXTURE_COPY_LOCATION to{static_cast(static_cast(Dc.guest.Get())), + D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, {0}}; + const D3D12_TEXTURE_COPY_LOCATION from{static_cast(static_cast(Tc.guest.Get())), + D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, {0}}; + invoke(L.list.Get(), 16, &to, 0u, 0u, 0u, &from, static_cast(nullptr)); + if (!c.close(L)) return false; + c.execute(c.direct, L); + if (!c.sync(c.direct) || !c.holds(Dc.guest.Get(), 33, "RGBA8 reuse after BC7 retirement")) return false; + if (!SUCCEEDED(c.reset_list(L))) return false; + c.release(Tc); + if (on) Tc.freed = true; + return c.settle("T_rgba_after_bc7 retired", "T_rgba_after_bc7 kept"); +} + +// 4: descriptor & view reuse (slot 18 SRV + CopyDescriptorsSimple + heap release + descriptor overwrite). +bool case4_descriptor_and_view_reuse(Context& c, bool on, void* mem1, void* mem2) +{ + fill_title_memory(mem1, 44); + fill_title_memory(mem2, 55); + Res& Tv1 = c.make_slot133("Tv1", mem1); + Res& Tv2 = c.make_slot133("Tv2", mem2); + const struct { + D3D12_DESCRIPTOR_HEAP_DESC desc; + UINT64 backing, bytes; + } heap_desc{{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 2}, 0, 0}; + ComPtr heap1, heap2; + if (!require(invoke(c.guest, 14, &heap_desc, &__uuidof(ID3D12DescriptorHeap), heap1.GetAddressOf()), "heap1") || + !require(invoke(c.guest, 14, &heap_desc, &__uuidof(ID3D12DescriptorHeap), heap2.GetAddressOf()), "heap2")) + return false; + const UINT64 h1 = invoke(heap1.Get(), 9); + const UINT64 h2 = invoke(heap2.Get(), 9); + 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, Tv1.guest.Get(), &srv, h1); + invoke(c.guest, 24, 1u, h2, h1, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); + c.release(Tv1); + if (!c.stays("Tv1 held by heap1 and heap2", "Tv1 freed while two SRV descriptors hold it")) return false; + heap1.Reset(); + if (!c.stays("Tv1 held by heap2 copy", "Tv1 freed while copied SRV in heap2 holds it")) return false; + // Overwrite heap2[0] with Tv2: Tv1's last tracked descriptor ref drops to 0 and Tv1 retires. + invoke(c.guest, 18, Tv2.guest.Get(), &srv, h2); + if (on) Tv1.freed = true; + if (!c.settle("Tv1 retired after descriptor overwrite", "Tv1 kept after all SRV descriptors overwritten")) return false; + c.release(Tv2); + if (!c.stays("Tv2 held by overwritten heap2[0]", "Tv2 freed while SRV descriptor holds it")) return false; + heap2.Reset(); + if (on) Tv2.freed = true; + return c.settle("Tv2 retired after heap2 released", "Tv2 kept after heap2 released"); +} + +} // 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) return 2; + const bool on = !off_mode; + std::printf("adapter=%ls debug_layer=%s mode=%s\n", adapter_desc.Description, debug ? "enabled" : "off", off_mode ? "off" : "on"); + + constexpr SIZE_T page = D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT; + auto* mem1 = VirtualAlloc(nullptr, page, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); + auto* mem2 = VirtualAlloc(nullptr, page, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); + if (!mem1 || !mem2) return 4; + + 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.texture_bytes = device->GetResourceAllocationInfo(0, 1, &c.desc).SizeInBytes; + 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.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; + + if (!case1_slot133_copy_and_upload(c, on, mem1)) return 5; + std::puts("1 slot 133 copy and upload: held across closed list and gated submit, readback ok, retired"); + if (!case2_same_address_and_slot70_reuse(c, on, mem1)) return 5; + std::puts("2 same-address and slot 70 reuse: existing_memory_texture + resource_address_index ok"); + if (!case3_written_textures_cleanup(c, on, mem1, mem2)) return 5; + std::puts("3 written_textures cleanup: stale bc7_width cleared on address reuse"); + if (!case4_descriptor_and_view_reuse(c, on, mem1, mem2)) return 5; + std::puts("4 descriptor and view reuse: tracked slot-18 SRV holds and retires on overwrite/heap release"); + } catch (int code) { + VirtualFree(mem1, 0, MEM_RELEASE); + VirtualFree(mem2, 0, MEM_RELEASE); + return code; + } + VirtualFree(mem1, 0, MEM_RELEASE); + VirtualFree(mem2, 0, MEM_RELEASE); + 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 title checks passed" : "switch-off title checks passed"); + return 0; +} From 0b80b4d5e85992af7532594afdac9b1cecc24ccc Mon Sep 17 00:00:00 2001 From: triggered02 Date: Wed, 25 Nov 2026 23:44:35 +0530 Subject: [PATCH 2/6] startup: guard the retire-class upload gate, hold lock and view recording (review follow-up) --- src/startup_stubs/d3d12_xs_device.cpp | 84 ++++++++++++++++++++++--- src/startup_stubs/list_copy_texture.inl | 10 ++- 2 files changed, 84 insertions(+), 10 deletions(-) diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index 8acedf79de..7e9a794a37 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -156,6 +156,8 @@ struct alignas(16) WrapperOwn { bool tiled_address_srv; // Resource backed by 4 KiB tiled guest memory for translated draws. 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 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. 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. @@ -3929,8 +3931,20 @@ __declspec(noinline) u64 view_slot(Wrapper* self, u64 a, u64 b, u64 c, u64 d) args[1] = reinterpret_cast(&null_rtv); } const u64 result = method_of(self->own().real, N)(self->own().real, args[0], args[1], args[2], args[3], 0, 0, 0, 0); - record_view(true); - if ((N == 20 || N == 21) && args[0]) note_view_target(args[D], reinterpret_cast(args[0]), N); + // A desktop view creation returns void, so the only failure it reports is a removed device. Only a created view + // may keep the resource: on failure the slot is recorded unmaterialized, which releases the slot's previous view + // reference and adds none. + const HRESULT removed = removal_device ? removal_device->GetDeviceRemovedReason() : S_OK; + const bool created = SUCCEEDED(removed); + record_view(created); + if (!created) { + static LONG failed; + if (first_calls(failed, 6)) + log("x2w-d3d12 Device::slot%d view not created: device removed, reason 0x%08lx", N, + static_cast(removed)); + } + if ((N == 20 || N == 21) && args[0] && created) + note_view_target(args[D], reinterpret_cast(args[0]), N); check_device("Device view", N); static LONG calls; if (first_calls(calls)) @@ -4418,10 +4432,12 @@ void retire_note_title_release(Wrapper* w) 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; + AcquireSRWLockExclusive(&retire_lock); + // own().real is cleared by drain_retired_resources under this lock, so the read and the AddRef happen under it + // (retire_lock is a leaf: nothing else is taken inside). + auto* real = static_cast(resource->own().real); 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()) { @@ -4435,10 +4451,14 @@ void retire_hold(Wrapper* list, Wrapper* resource) } } 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; + if (!held) { + // 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_hold_missed = true; + } + ReleaseSRWLockExclusive(&retire_lock); } void retire_discard_holds(Wrapper* list) @@ -4557,6 +4577,15 @@ void drain_retired_resources() for (std::size_t i = 0; i < retired_resources.size() && dropped.size() < batch;) { RetiredResource& item = retired_resources[i]; Wrapper* w = item.wrapper; + if (w->own().retire_hold_missed) { + // retire_hold could not record a list's use of this resource: keep its desktop object for the process, + // like a submission that could not be fenced, and drop only the retire bookkeeping. + InterlockedIncrement64(&retire_kept); + if (i + 1 != retired_resources.size()) item = std::move(retired_resources.back()); + retired_resources.pop_back(); + InterlockedDecrement(&retire_pending); + continue; + } if (InterlockedCompareExchange(&w->own().retire_view_refs, 0, 0) > 0) { ++i; continue; @@ -4657,6 +4686,47 @@ extern "C" __declspec(dllexport) BOOL x2w_d3d12_retire_probe(void* resource, voi return TRUE; } +// Fixture probes (startup_resource_retire_title) for state the retire bookkeeping maintains for one resource. They read +// the same maps the shim reads and never change them; the address index and the upload cache exist with and without +// the switch, so these answer in both modes. +extern "C" __declspec(dllexport) BOOL x2w_d3d12_resource_index_probe(void* resource) +{ + Wrapper* w = as_wrapper(resource); + if (!w || w->own().kind != resource_kind) return FALSE; + const u64 base = reinterpret_cast(w->own().title_memory); + if (!base) return FALSE; + AcquireSRWLockShared(¬e_lock); + const bool indexed = resource_address_index().contains(base, static_cast(w)); + ReleaseSRWLockShared(¬e_lock); + return indexed ? TRUE : FALSE; +} + +// The desktop pointer is not dereferenced: the fixture keeps its own desktop reference to a retired resource. +extern "C" __declspec(dllexport) BOOL x2w_d3d12_texture_upload_probe(void* desktop_resource) +{ + if (!desktop_resource) return FALSE; + AcquireSRWLockExclusive(&draw_lock); + const bool cached = texture_uploads().count(static_cast(desktop_resource)) != 0; + ReleaseSRWLockExclusive(&draw_lock); + return cached ? TRUE : FALSE; +} + +extern "C" __declspec(dllexport) BOOL x2w_d3d12_written_probe(void* address, unsigned long long* generation, unsigned* bc7_width, + unsigned* desktop_rows) +{ + if (!address) return FALSE; + AcquireSRWLockShared(&written_lock); + const auto found = written_textures().find(reinterpret_cast(address)); + const bool present = found != written_textures().end(); + if (present) { + if (generation) *generation = found->second.generation; + if (bc7_width) *bc7_width = found->second.bc7_width; + if (desktop_rows) *desktop_rows = found->second.desktop_rows ? 1u : 0u; + } + ReleaseSRWLockShared(&written_lock); + return present ? TRUE : FALSE; +} + // 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 diff --git a/src/startup_stubs/list_copy_texture.inl b/src/startup_stubs/list_copy_texture.inl index 0727949da2..4f2ca279b5 100644 --- a/src/startup_stubs/list_copy_texture.inl +++ b/src/startup_stubs/list_copy_texture.inl @@ -147,13 +147,17 @@ 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. - // A resource without title memory has nothing to upload and leaves no texture_uploads() entry behind. - if (side_src.kind == x2w_list_copy_texture::Kind::subresource && src_wrapper->own().title_memory) { + // A resource of the retire class that has no title memory has nothing to upload and leaves no texture_uploads() + // entry behind; every other resource uploads exactly as it did before the switch (switch off: nothing changes). + const auto needs_upload = [](const Wrapper* wrapper) { + return !wrapper->own().retire_when_idle || wrapper->own().title_memory; + }; + if (side_src.kind == x2w_list_copy_texture::Kind::subresource && needs_upload(src_wrapper)) { AcquireSRWLockExclusive(&draw_lock); upload_texture(self, src_wrapper, real_src); ReleaseSRWLockExclusive(&draw_lock); } - if (side_dst.kind == x2w_list_copy_texture::Kind::subresource && dst_wrapper->own().title_memory) { + if (side_dst.kind == x2w_list_copy_texture::Kind::subresource && needs_upload(dst_wrapper)) { AcquireSRWLockExclusive(&draw_lock); upload_texture(self, dst_wrapper, real_dst); ReleaseSRWLockExclusive(&draw_lock); From 05bd5dc5e1d44cc6c85b46ea4be04cfe9f77bbf2 Mon Sep 17 00:00:00 2001 From: triggered02 Date: Wed, 25 Nov 2026 23:44:35 +0530 Subject: [PATCH 3/6] tests: cover the retire-class upload gate, newer written generations and retire bookkeeping --- tests/startup_resource_retire_title.cpp | 144 +++++++++++++++++++++++- 1 file changed, 142 insertions(+), 2 deletions(-) diff --git a/tests/startup_resource_retire_title.cpp b/tests/startup_resource_retire_title.cpp index 0f98c6f8a2..bf379a47ed 100644 --- a/tests/startup_resource_retire_title.cpp +++ b/tests/startup_resource_retire_title.cpp @@ -11,9 +11,14 @@ // 2 resource_address_index + slot 70 (existing_memory_texture) same-address reuse while T1 is pending behind a // held fence, with X2W_RESOURCE_INDEX_CHECK=1 verifying live index consistency. // 3 written_textures stale bc7_width cleanup on address reuse (BC7 retired -> RGBA8 at same address uploads -// fresh CPU texels; newer generation preserved when a live view keeps an older resource pending). +// fresh CPU texels). // 4 descriptor & view reuse: view_slot<18> + CopyDescriptorsSimple + heap release + descriptor overwrite; // stays retained while any tracked slot holds the SRV, retires once overwritten/freed and fences complete. +// 5 switch-off control: an ordinary committed texture (no slot 133, no title memory) copied as a subresource still +// records its upload, as before the switch (case runs with the switch off, which is what selects the control). +// 6 written_textures generation keeping: a live view keeps the older generation's entry, and a newer generation of +// the same address survives the older generation's retirement (case runs with the switch on, which is what +// retires resources). #include "startup_stubs/resource_budget.h" #include @@ -38,7 +43,11 @@ struct RetireProbe { 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*); +extern "C" __declspec(dllimport) BOOL x2w_d3d12_resource_index_probe(void*); +extern "C" __declspec(dllimport) BOOL x2w_d3d12_texture_upload_probe(void*); +extern "C" __declspec(dllimport) BOOL x2w_d3d12_written_probe(void*, unsigned long long*, unsigned*, unsigned*); extern "C" __declspec(dllimport) void x2w_d3d12_bc7_4k_s_written(void*, UINT, UINT); +extern "C" __declspec(dllimport) void x2w_d3d12_list_copy_texture_stats(LONG*, LONG*); namespace { using namespace x2w_budget; @@ -352,6 +361,15 @@ bool case1_slot133_copy_and_upload(Context& c, bool on, void* title_mem) { fill_title_memory(title_mem, 5); Res& T1 = c.make_slot133("T1", title_mem); + auto t1_desktop = desktop_object(c.guest, c.device, T1.guest.Get()); + if (!t1_desktop) { + std::puts("FAIL: slot 133 texture has no desktop object"); + return false; + } + // The raw pointer only keys the upload cache after retirement: a COM reference here would keep the budget ticket + // of a retired desktop object alive (the fixture's expected retained count would then not drop). + ID3D12Resource* const t1_real = t1_desktop.Get(); + t1_desktop.Reset(); Res& D1 = c.make_committed("D1"); Res& D2 = c.make_committed("D2"); if (!c.fill_desktop(D1.guest.Get(), 99) || !c.fill_desktop(D2.guest.Get(), 99)) return false; @@ -374,6 +392,10 @@ bool case1_slot133_copy_and_upload(Context& c, bool on, void* title_mem) } c.release(T1); if (!c.sync(c.direct) || !c.sync(c.gated)) return false; + if (!x2w_d3d12_texture_upload_probe(t1_real)) { + std::puts("FAIL: slot 133 CopyTextureRegion recorded no texture_uploads entry for T1"); + return false; + } if (!c.stays("slot 133 released behind closed lists", "early release of slot 133 texture")) return false; c.execute(c.direct, L1); if (!c.sync(c.direct) || !c.holds(D1.guest.Get(), 5, "D1 CopyTextureRegion from slot 133")) return false; @@ -389,6 +411,12 @@ bool case1_slot133_copy_and_upload(Context& c, bool on, void* title_mem) if (!require(invoke(gate.Get(), 10, UINT64{1}), "signal1") || !c.sync(c.gated)) return false; if (on) T1.freed = true; if (!c.settle("slot 133 retired", "slot 133 texture kept after fences passed")) return false; + // The texture_uploads() entry the copy recorded leaves with the desktop object; without the switch nothing + // retires and the entry stays, as before the switch existed. + if ((x2w_d3d12_texture_upload_probe(t1_real) != FALSE) == on) { + std::printf("FAIL: texture_uploads entry for retired T1 is %s\n", on ? "still present" : "missing"); + return false; + } return c.holds(D2.guest.Get(), 5, "D2 CopyResource from slot 133"); } @@ -397,6 +425,8 @@ bool case2_same_address_and_slot70_reuse(Context& c, bool on, void* title_mem) { fill_title_memory(title_mem, 11); Res& T1 = c.make_slot133("T_addr1", title_mem, DXGI_FORMAT_R8_UNORM, pitch); + // The wrapper outlives its guest Release (the registry keeps it), so the raw pointer can be probed afterwards. + IUnknown* const t1_guest = T1.guest.Get(); ComPtr gate; if (!require(invoke(c.guest, 36, UINT64{0}, D3D12_FENCE_FLAG_NONE, &__uuidof(ID3D12Fence), gate.GetAddressOf()), "gate2") || !require(invoke(c.gated.queue.Get(), 17, gate.Get(), UINT64{1}), "wait2")) @@ -430,6 +460,16 @@ bool case2_same_address_and_slot70_reuse(Context& c, bool on, void* title_mem) if (!require(invoke(gate.Get(), 10, UINT64{1}), "signal2") || !c.sync(c.gated)) return false; if (on) T1.freed = true; if (!c.settle("T_addr1 retired while T_addr2 live", "T_addr1 did not retire")) return false; + // Retirement drops T1's resource_address_index entry (the canonical record stays); without the switch T1 stays + // live, so its index entry stays too. T2's own entry must be there in both modes. + if (!x2w_d3d12_resource_index_probe(T2.guest.Get())) { + std::puts("FAIL: T_addr2 has no resource_address_index entry"); + return false; + } + if ((x2w_d3d12_resource_index_probe(t1_guest) != FALSE) == on) { + std::printf("FAIL: resource_address_index entry for retired T_addr1 is %s\n", on ? "still present" : "missing"); + return false; + } // Verify T2 still uploads seed 22 properly after T1 retired. const D3D12_HEAP_PROPERTIES def_heap{D3D12_HEAP_TYPE_DEFAULT}; Res& D = c.pool.emplace_back(); @@ -532,6 +572,96 @@ bool case4_descriptor_and_view_reuse(Context& c, bool on, void* mem1, void* mem2 return c.settle("Tv2 retired after heap2 released", "Tv2 kept after heap2 released"); } +// 5: switch-off control. An ordinary committed texture (slot 127, no title memory, not a slot 133 resource) copied as +// a subresource must still record its upload exactly as before the switch: upload_texture() is gated on the retire +// class, not on title memory. The observable is the per-desktop-object texture_uploads() entry the no-title-memory +// path records (a probe over the same map), plus the forwarded counter of the copy itself. +bool case5_ordinary_upload_switch_off(Context& c) +{ + Res& source = c.make_committed("U_src"); + Res& dest = c.make_committed("U_dst"); + const auto source_real = desktop_object(c.guest, c.device, source.guest.Get()); + const auto dest_real = desktop_object(c.guest, c.device, dest.guest.Get()); + if (!source_real || !dest_real) { + std::puts("FAIL: an ordinary committed texture has no desktop object"); + return false; + } + LONG forwarded_before = 0, refused_before = 0; + x2w_d3d12_list_copy_texture_stats(&forwarded_before, &refused_before); + GuestList L; + if (!c.make_list(L)) return false; + const D3D12_TEXTURE_COPY_LOCATION to{static_cast(static_cast(dest.guest.Get())), + D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, {0}}; + const D3D12_TEXTURE_COPY_LOCATION from{static_cast(static_cast(source.guest.Get())), + D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, {0}}; + invoke(L.list.Get(), 16, &to, 0u, 0u, 0u, &from, static_cast(nullptr)); + if (!c.close(L)) return false; + c.execute(c.direct, L); + if (!c.sync(c.direct)) return false; + LONG forwarded_after = 0, refused_after = 0; + x2w_d3d12_list_copy_texture_stats(&forwarded_after, &refused_after); + if (forwarded_after != forwarded_before + 1 || refused_after != refused_before) { + std::printf("FAIL: ordinary texture copy forwarded %ld refused %ld, expected one more forwarded and none refused\n", + forwarded_after - forwarded_before, refused_after - refused_before); + return false; + } + const bool source_cached = x2w_d3d12_texture_upload_probe(source_real.Get()) != FALSE; + const bool dest_cached = x2w_d3d12_texture_upload_probe(dest_real.Get()) != FALSE; + if (!source_cached || !dest_cached) { + std::printf("FAIL: ordinary texture copy recorded no upload (source=%d destination=%d); " + "upload_texture is gated on title memory instead of the retire class\n", source_cached, dest_cached); + return false; + } + return true; +} + +// 6: written_textures() generation keeping (switch on). A live slot-18 SRV keeps the older resource's entry while it +// is pending; a newer generation of the same address then arrives and must survive the older generation's retirement +// (the snapshot-generation check), so the newer write is not mistaken for the older one's stale state. +bool case6_written_generation_preserved(Context& c, void* title_mem) +{ + x2w_d3d12_bc7_4k_s_written(title_mem, side, side); // generation 1 of this address + Res& Told = c.make_slot133("T_gen_old", title_mem); + const struct { + D3D12_DESCRIPTOR_HEAP_DESC desc; + UINT64 backing, bytes; + } heap_desc{{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 1}, 0, 0}; + ComPtr heap; + if (!require(invoke(c.guest, 14, &heap_desc, &__uuidof(ID3D12DescriptorHeap), heap.GetAddressOf()), "generation heap")) + return false; + const UINT64 handle = invoke(heap.Get(), 9); + 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, Told.guest.Get(), &srv, handle); + c.release(Told); + // The live view keeps the entry: only its generation is snapshotted, the entry is not erased. + unsigned long long generation = 0; + unsigned bc7_width = 0; + if (!x2w_d3d12_written_probe(title_mem, &generation, &bc7_width, nullptr) || generation != 1 || + bc7_width != side) { + std::printf("FAIL: a live view did not keep written_textures entry (found=%d generation=%llu bc7_width=%u)\n", + x2w_d3d12_written_probe(title_mem, nullptr, nullptr, nullptr), generation, bc7_width); + return false; + } + // A newer generation of the same address while the older resource is still pending behind its view. + x2w_d3d12_bc7_4k_s_written(title_mem, side, side); + heap.Reset(); // drops the view reference: the older resource can retire now + Told.freed = true; + if (!c.settle("older generation retired", "older generation kept after its view was released")) return false; + unsigned long long kept_generation = 0; + unsigned kept_bc7_width = 0; + const BOOL found = x2w_d3d12_written_probe(title_mem, &kept_generation, &kept_bc7_width, nullptr); + if (!found || kept_generation != 2 || kept_bc7_width != side) { + std::printf("FAIL: retiring the older generation released the newer written generation " + "(found=%d generation=%llu bc7_width=%u)\n", found, kept_generation, kept_bc7_width); + return false; + } + return true; +} + } // namespace int main(int argc, char** argv) @@ -581,7 +711,8 @@ int main(int argc, char** argv) constexpr SIZE_T page = D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT; auto* mem1 = VirtualAlloc(nullptr, page, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); auto* mem2 = VirtualAlloc(nullptr, page, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); - if (!mem1 || !mem2) return 4; + auto* mem3 = VirtualAlloc(nullptr, page, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); + if (!mem1 || !mem2 || !mem3) return 4; Context c{guest.Get(), device.Get(), debug.Get()}; try { @@ -614,13 +745,22 @@ int main(int argc, char** argv) std::puts("3 written_textures cleanup: stale bc7_width cleared on address reuse"); if (!case4_descriptor_and_view_reuse(c, on, mem1, mem2)) return 5; std::puts("4 descriptor and view reuse: tracked slot-18 SRV holds and retires on overwrite/heap release"); + if (!on) { + if (!case5_ordinary_upload_switch_off(c)) return 5; + std::puts("5 switch-off ordinary texture copy: upload still recorded for a resource outside the retire class"); + } else { + if (!case6_written_generation_preserved(c, mem3)) return 5; + std::puts("6 written_textures generation: newer generation of an address kept by the older one's retirement"); + } } catch (int code) { VirtualFree(mem1, 0, MEM_RELEASE); VirtualFree(mem2, 0, MEM_RELEASE); + VirtualFree(mem3, 0, MEM_RELEASE); return code; } VirtualFree(mem1, 0, MEM_RELEASE); VirtualFree(mem2, 0, MEM_RELEASE); + VirtualFree(mem3, 0, MEM_RELEASE); const UINT64 errors = debug ? debug->GetNumStoredMessages() : 0; std::printf("debug_errors_or_warnings=%llu\n", errors); if (errors || FAILED(device->GetDeviceRemovedReason())) return 4; From 61b208931c58badff1896d6a8fe051a6f681d649 Mon Sep 17 00:00:00 2001 From: triggered02 Date: Wed, 25 Nov 2026 23:50:46 +0530 Subject: [PATCH 4/6] docs: record the retire upload gate, view recording and hold fallback (review follow-up) --- docs/experiments.md | 5 +++-- docs/startup-runtime.md | 23 +++++++++++++++++------ 2 files changed, 20 insertions(+), 8 deletions(-) diff --git a/docs/experiments.md b/docs/experiments.md index d75acbf1cb..fc788875ac 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -14827,10 +14827,11 @@ data, because a refusal is observable at the `Stage` entry point. Building on #2443 (Slice 1), `X2W_D3D12_RELEASE_RETIRED=1` extends desktop object retirement to device slot 133 (`CreatePlacedResourceX`) committed 2D textures with `title_memory` (non-RT/DS/UAV, 1-sample, `DEFAULT` heap), while keeping slot 127 `__XMemAllocationHooks__` resources out of the class: - `drain_retired_resources()` erases the retired wrapper from `resource_address_index()` (under `note_lock`), erases its desktop pointer from `texture_uploads()` (under `draw_lock`), and cleans stale `written_textures()` entries whose generation was not bumped by a newer allocation/write at the same title address (also cleared immediately on final `Release` when no view or live sibling shares the address). -- `list_copy_texture.inl` gates `upload_texture()` on `title_memory != nullptr` rather than `!retire_when_idle` and guards `texture_uploads()` accesses in `list_copy.inl` / `list_copy_texture.inl` with `draw_lock`. +- `list_copy_texture.inl` calls `upload_texture()` for a subresource copy only when the resource is not in the retire class or has title memory (`!retire_when_idle || title_memory`), so with the switch off every resource uploads exactly as before; `texture_uploads()` accesses in `list_copy.inl` / `list_copy_texture.inl` are guarded with `draw_lock`. +- `view_slot` records a view only when the desktop created it: desktop view creation returns `void`, so a removed device is the only failure it reports, and a failed slot is recorded unmaterialized (releasing its previous view reference and adding none). `retire_hold` reads the wrapper's desktop pointer under the retire lock and marks a use it cannot record, which makes the drain keep that desktop object for the process instead of dropping one a list still names. - `view_slot<18>` (SRV) tracks descriptor slots via `HeapInfo::shadow` across `note_view`, `note_copy`, and heap destruction (falling back to `retire_leave_class` for untracked slots or slots 19–21), and `draw_translated` holds bound textures with `retire_hold`. -[`tests/startup_resource_retire_title.cpp`](../tests/startup_resource_retire_title.cpp) (`startup_resource_retire_title_{warp,hardware}_debug0` and `_off_`) verifies slot 133 copy/upload holds and readbacks, same-address slot 70 (`existing_memory_texture`) reuse under `X2W_RESOURCE_INDEX_CHECK=1`, stale `bc7_width` `written_textures` cleanup on RGBA8 reuse, and `CopyDescriptorsSimple` / overwrite / heap-release SRV retirement across WARP (`Microsoft Basic Render Driver`) and `NVIDIA GeForce GTX 1660 SUPER`. +[`tests/startup_resource_retire_title.cpp`](../tests/startup_resource_retire_title.cpp) (`startup_resource_retire_title_{warp,hardware}_debug0` and `_off_`) verifies slot 133 copy/upload holds and readbacks, same-address slot 70 (`existing_memory_texture`) reuse under `X2W_RESOURCE_INDEX_CHECK=1`, stale `bc7_width` `written_textures` cleanup on RGBA8 reuse, `CopyDescriptorsSimple` / overwrite / heap-release SRV retirement, the switch-off control that an ordinary committed texture (no title memory) copy still records its upload, and that a newer `written_textures` generation survives the older generation's retirement across WARP (`Microsoft Basic Render Driver`) and `NVIDIA GeForce GTX 1660 SUPER`. ```powershell ctest --preset dev --no-tests=error -R '^startup_resource_(retire|budget)' -V diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index d3c2c339b6..ee3f0695a5 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -1362,7 +1362,10 @@ 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 created for it (slots 19 to 21, also a refused one), when a slot 18 SRV targets an untracked descriptor slot or is copied out of tracked heaps, when it is passed -to MakeResident or Evict (slots 34 and 35), or when it is presented. Tracked +to MakeResident or Evict (slots 34 and 35), or when it is presented. A slot 18 +SRV keeps the resource only when the desktop created the view: desktop view +creation returns `void`, so a removed device is the only failure it reports, and +a slot whose creation failed is recorded without a reference. Tracked slot 18 SRVs (including slot 70 `device_memory_srv`) keep the resource retained while any descriptor slot in `HeapInfo::shadow` names it (updated across `note_view`, `CopyDescriptors*`, and heap `Release`), and translated draws hold @@ -1380,8 +1383,12 @@ source and destination, until the list is Reset, fails to Close or is destroyed. 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. +submission fence that cannot be recorded, keep the resource retained. A use that +`retire_hold` cannot record (no desktop object left, or no room for the entry) +leaves the class and marks the resource so the drain keeps its desktop object for +the process, as an unfenced submission is kept, instead of dropping an object a +list still names. 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. Slot 18 (`CopyTiles`) is not forwarded at all and is outside this change. @@ -1405,9 +1412,13 @@ presented texture that must stay retained, alongside slot 133 title-memory textu `startup_resource_retire_title_{warp,hardware}_debug{0,1}` additionally test slot 133 `CopyTextureRegion`/`CopyResource` upload holds, same-address slot 70 (`existing_memory_texture`) reuse with `X2W_RESOURCE_INDEX_CHECK=1`, stale `written_textures` `bc7_width` cleanup, -and slot-18 SRV `CopyDescriptorsSimple` / overwrite / heap-release lifetime. The fixture-only export -`x2w_d3d12_retire_probe` returns FALSE without the switch, like -`x2w_d3d12_budget_snapshot`. `startup_resource_retire_off_*` +slot-18 SRV `CopyDescriptorsSimple` / overwrite / heap-release lifetime, and, with the +switch on, a newer `written_textures` generation kept when the older generation retires; +the `_off_` case checks that an ordinary committed texture (no title memory) still +records its upload. The fixture-only exports `x2w_d3d12_retire_probe`, +`x2w_d3d12_resource_index_probe`, `x2w_d3d12_texture_upload_probe` and +`x2w_d3d12_written_probe` read the bookkeeping the shim keeps; the 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, and the debug-layer cases report 77 where the debug layer is not installed. From 1ef07a64fb1dcb58806752e01e0a1595e37df8d9 Mon Sep 17 00:00:00 2001 From: triggered02 <153171514+triggered02@users.noreply.github.com> Date: Thu, 26 Nov 2026 00:09:35 +0530 Subject: [PATCH 5/6] tests: cover the translated draw hold and SRV token resolution in the retire fixture (B1) startup_resource_retire_title had no draw path, so draw_translated's retire_hold and the slot-133 view-token resolution were untested. Case 7 samples a slot 133 title-memory texture through a descriptor table with a host-built translated pipeline and asserts the exact readback (including a clear sentinel row and column). The closed recording must keep the released texture retained until it is dropped, which is the hold; a skipped token resolve binds no view and fails the readback. --- CMakeLists.txt | 2 +- docs/experiments.md | 2 +- docs/startup-runtime.md | 9 +- tests/startup_resource_retire_title.cpp | 302 ++++++++++++++++++++++++ 4 files changed, 310 insertions(+), 5 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 3adaa32fa1..57e76d1c46 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1347,7 +1347,7 @@ 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) -target_link_libraries(startup_resource_retire_title PRIVATE d3d12_xs_shim d3d12 dxgi) +target_link_libraries(startup_resource_retire_title PRIVATE d3d12_xs_shim d3d12 dxgi d3dcompiler) foreach(backend IN ITEMS warp hardware) foreach(debug IN ITEMS 0 1) set(retire_title_env "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=${debug}") diff --git a/docs/experiments.md b/docs/experiments.md index fc788875ac..64888a7e21 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -14831,7 +14831,7 @@ Building on #2443 (Slice 1), `X2W_D3D12_RELEASE_RETIRED=1` extends desktop objec - `view_slot` records a view only when the desktop created it: desktop view creation returns `void`, so a removed device is the only failure it reports, and a failed slot is recorded unmaterialized (releasing its previous view reference and adding none). `retire_hold` reads the wrapper's desktop pointer under the retire lock and marks a use it cannot record, which makes the drain keep that desktop object for the process instead of dropping one a list still names. - `view_slot<18>` (SRV) tracks descriptor slots via `HeapInfo::shadow` across `note_view`, `note_copy`, and heap destruction (falling back to `retire_leave_class` for untracked slots or slots 19–21), and `draw_translated` holds bound textures with `retire_hold`. -[`tests/startup_resource_retire_title.cpp`](../tests/startup_resource_retire_title.cpp) (`startup_resource_retire_title_{warp,hardware}_debug0` and `_off_`) verifies slot 133 copy/upload holds and readbacks, same-address slot 70 (`existing_memory_texture`) reuse under `X2W_RESOURCE_INDEX_CHECK=1`, stale `bc7_width` `written_textures` cleanup on RGBA8 reuse, `CopyDescriptorsSimple` / overwrite / heap-release SRV retirement, the switch-off control that an ordinary committed texture (no title memory) copy still records its upload, and that a newer `written_textures` generation survives the older generation's retirement across WARP (`Microsoft Basic Render Driver`) and `NVIDIA GeForce GTX 1660 SUPER`. +[`tests/startup_resource_retire_title.cpp`](../tests/startup_resource_retire_title.cpp) (`startup_resource_retire_title_{warp,hardware}_debug0` and `_off_`) verifies slot 133 copy/upload holds and readbacks, same-address slot 70 (`existing_memory_texture`) reuse under `X2W_RESOURCE_INDEX_CHECK=1`, stale `bc7_width` `written_textures` cleanup on RGBA8 reuse, `CopyDescriptorsSimple` / overwrite / heap-release SRV retirement, the switch-off control that an ordinary committed texture (no title memory) copy still records its upload, and that a newer `written_textures` generation survives the older generation's retirement across WARP (`Microsoft Basic Render Driver`) and `NVIDIA GeForce GTX 1660 SUPER`. Case 7 closes the fixture's draw-path gap (review finding B1): a host-built translated pixel shader samples a slot 133 title-memory texture through a descriptor table, its view token must resolve to that texture (a skipped resolve binds a null view and the readback reports `pixel (0,0) got 00000000`), and `retire_hold` in the draw keeps the released texture retained while the closed recording names it (removed, the budget reports `retained=0/0 expected=65536/1` before the recording is dropped); the readback holds the exact sampled words plus a clear sentinel row and column throughout, including after the texture leaves the budget. ```powershell ctest --preset dev --no-tests=error -R '^startup_resource_(retire|budget)' -V diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index ee3f0695a5..7bd9e05e9c 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -1413,9 +1413,12 @@ presented texture that must stay retained, alongside slot 133 title-memory textu `CopyTextureRegion`/`CopyResource` upload holds, same-address slot 70 (`existing_memory_texture`) reuse with `X2W_RESOURCE_INDEX_CHECK=1`, stale `written_textures` `bc7_width` cleanup, slot-18 SRV `CopyDescriptorsSimple` / overwrite / heap-release lifetime, and, with the -switch on, a newer `written_textures` generation kept when the older generation retires; -the `_off_` case checks that an ordinary committed texture (no title memory) still -records its upload. The fixture-only exports `x2w_d3d12_retire_probe`, +switch on, a newer `written_textures` generation kept when the older generation retires +and a translated draw that samples such a texture through a descriptor table (the view +token's resolution and the draw's `retire_hold`: the readback holds the sampled texels and +a clear sentinel corner, and the texture leaves the budget only after the closed draw +recording is dropped); the `_off_` case checks that an ordinary committed texture (no +title memory) still records its upload. The fixture-only exports `x2w_d3d12_retire_probe`, `x2w_d3d12_resource_index_probe`, `x2w_d3d12_texture_upload_probe` and `x2w_d3d12_written_probe` read the bookkeeping the shim keeps; the retire probe returns FALSE without the switch, like `x2w_d3d12_budget_snapshot`. `startup_resource_retire_off_*` diff --git a/tests/startup_resource_retire_title.cpp b/tests/startup_resource_retire_title.cpp index bf379a47ed..9dc77ffd3c 100644 --- a/tests/startup_resource_retire_title.cpp +++ b/tests/startup_resource_retire_title.cpp @@ -19,9 +19,14 @@ // 6 written_textures generation keeping: a live view keeps the older generation's entry, and a newer generation of // the same address survives the older generation's retirement (case runs with the switch on, which is what // retires resources). +// 7 draw path (review finding B1): a translated pixel shader samples a slot 133 title-memory texture through a +// descriptor table. The readback must hold the sampled texels and a clear sentinel corner, the draw must record +// a retire hold (so removing it fails here), and after the final Release and the descriptor overwrite the +// texture leaves the budget only when the closed draw recording is dropped (case runs with the switch on). #include "startup_stubs/resource_budget.h" #include +#include #include #include @@ -31,6 +36,7 @@ #include #include #include +#include #include using Microsoft::WRL::ComPtr; @@ -356,6 +362,185 @@ void fill_title_memory(void* address, int seed) for (UINT i = 0; i < image_bytes; ++i) dst[i] = pattern_byte(seed, i); } +// Case 7 (reviewer JB2WIN, finding B1): the fixture had no draw path, so retire_hold() in the translated draw and +// the view-token resolution that picks the sampled texture were untested. The case samples a slot 133 +// title-memory texture through a descriptor table with a host-built translated pipeline: the draw must bind the +// texture the token names, the closed recording must hold it (so its final Release cannot drop it from the budget +// before the recording is dropped), and the readback must hold the exact texel content throughout. +constexpr UINT draw_side = 4; // 4x4 R8G8B8A8_UNORM target +constexpr UINT draw_covered = 3; // scissor leaves the last row and column untouched as the sentinel +constexpr int draw_seed = 77; +constexpr UINT draw_clear_pixel = 0xffff00ffu; // ClearRenderTargetView({1, 0, 1, 1}) in R8G8B8A8_UNORM +constexpr char draw_revision[] = "x2w-startup-shader-14"; // d3d12_draw.inl cached_translation + +constexpr char draw_vertex_shader[] = R"( +struct Varying { float4 position : SV_Position; }; +Varying main(uint id : SV_VertexID) +{ + Varying result; + result.position = float4(id == 1 ? 3.0 : -1.0, id == 2 ? 3.0 : -1.0, 0.0, 1.0); + return result; +} +)"; + +// Samples the texture the title's descriptor table names at the pixel it covers, so an unresolved or wrongly +// resolved view token shows up as wrong texels rather than as a draw that silently binds nothing. +constexpr char draw_pixel_shader[] = R"( +Texture2D sampled : register(t0); +float4 main(float4 position : SV_Position) : SV_Target +{ + return sampled.Load(int3(uint2(position.xy), 0)); +} +)"; + +constexpr char draw_manifest[] = + "x2w-manifest 1\nud 1\nudsrc 0 rect\nsrv 0 tex2d table 0 0\nparams 0\ntargets 0\n"; + +std::uint64_t fnv_bytes(const void* data, std::size_t bytes, std::uint64_t hash = 1469598103934665603ull) +{ + const auto* p = static_cast(data); + for (std::size_t i = 0; i < bytes; ++i) hash = (hash ^ p[i]) * 1099511628211ull; + return hash; +} + +bool write_file(const std::wstring& path, const void* data, std::size_t bytes) +{ + HANDLE file = CreateFileW(path.c_str(), GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr); + if (file == INVALID_HANDLE_VALUE) return false; + DWORD written = 0; + const bool complete = WriteFile(file, data, static_cast(bytes), &written, nullptr) && written == bytes; + CloseHandle(file); + return complete; +} + +ComPtr compile_stage(const char* source, const char* entry, const char* profile) +{ + ComPtr code, errors; + const HRESULT hr = D3DCompile(source, std::strlen(source), nullptr, nullptr, nullptr, entry, profile, 0, 0, + code.GetAddressOf(), errors.GetAddressOf()); + if (FAILED(hr)) { + std::printf("FAIL: %s %s compile 0x%08lx%s%s\n", entry, profile, static_cast(hr), + errors ? ": " : "", errors ? static_cast(errors->GetBufferPointer()) : ""); + return nullptr; + } + return code; +} + +// Writes the source-built translation the shim looks up by the hash of the pipeline's two code blobs and its root +// signature (d3d12_draw.inl cached_translation), and creates the guest root signature and placeholder pipeline +// that name it. The shim loads the .vs/.ps bytecode and builds the desktop pipeline itself. +bool prepare_draw_translation(Context& c, ComPtr& root, ComPtr& pipeline) +{ + wchar_t temporary[MAX_PATH]{}; + if (!GetTempPathW(MAX_PATH, temporary)) return false; + const std::wstring directory = + std::wstring(temporary) + L"x2w-retire-title-" + std::to_wstring(GetCurrentProcessId()); + if (!CreateDirectoryW(directory.c_str(), nullptr) && GetLastError() != ERROR_ALREADY_EXISTS) return false; + if (!SetEnvironmentVariableW(L"X2W_SHADER_CACHE", directory.c_str())) return false; + + const D3D12_DESCRIPTOR_RANGE range{D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 1, 0, 0, 0}; + D3D12_ROOT_PARAMETER parameter{}; + parameter.ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; + parameter.DescriptorTable = {1, &range}; + parameter.ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL; + const D3D12_ROOT_SIGNATURE_DESC descriptor{1, ¶meter, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_NONE}; + ComPtr blob, errors; + if (!require(D3D12SerializeRootSignature(&descriptor, D3D_ROOT_SIGNATURE_VERSION_1, blob.GetAddressOf(), + errors.GetAddressOf()), + "draw root serialize")) + return false; + if (!require(invoke(c.guest, 16, UINT{0}, blob->GetBufferPointer(), blob->GetBufferSize(), + &__uuidof(ID3D12RootSignature), root.GetAddressOf()), + "draw root signature")) + return false; + + const auto vertex = compile_stage(draw_vertex_shader, "main", "vs_5_1"); + const auto pixel = compile_stage(draw_pixel_shader, "main", "ps_5_1"); + if (!vertex || !pixel) return false; + // The opaque guest programs only identify the cache entry: the shim hashes these bytes with the root blob. + static std::uint32_t vertex_key[] = {0x7a1b0001, 0x2c3d4e5f}; + static std::uint32_t pixel_key[] = {0x7a1b0002, 0x5e4d3c2b}; + std::uint64_t key = fnv_bytes(draw_revision, sizeof(draw_revision) - 1); + key = fnv_bytes(vertex_key, sizeof(vertex_key), key); + key = fnv_bytes(pixel_key, sizeof(pixel_key), key); + key = fnv_bytes(blob->GetBufferPointer(), blob->GetBufferSize(), key); + wchar_t stem[64]{}; + swprintf(stem, 64, L"\\%016llx", static_cast(key)); + const std::wstring prefix = directory + stem; + if (!write_file(prefix + L".txt", draw_manifest, sizeof(draw_manifest) - 1) || + !write_file(prefix + L".vs.cso", vertex->GetBufferPointer(), vertex->GetBufferSize()) || + !write_file(prefix + L".ps.cso", pixel->GetBufferPointer(), pixel->GetBufferSize())) + return false; + + std::array description{}; + description[0] = reinterpret_cast(root.Get()); + description[5] = reinterpret_cast(vertex_key); + description[6] = sizeof(vertex_key); + description[9] = reinterpret_cast(pixel_key); + description[10] = sizeof(pixel_key); + return require(invoke(c.guest, 57, description.data(), &__uuidof(ID3D12PipelineState), pipeline.GetAddressOf()), + "draw pipeline"); +} + +// Reads a desktop target through the fixture's own desktop queue and readback buffer, as holds() does. +bool read_target(Context& c, ID3D12Resource* target, const D3D12_RESOURCE_DESC& desc, std::uint8_t* bytes, + UINT& row_pitch) +{ + D3D12_PLACED_SUBRESOURCE_FOOTPRINT footprint{}; + UINT64 total = 0; + c.device->GetCopyableFootprints(&desc, 0, 1, 0, &footprint, nullptr, nullptr, &total); + if (!total || total > image_bytes) { + std::puts("FAIL: target readback does not fit the fixture's readback buffer"); + return false; + } + if (!require(c.own_allocator->Reset(), "target allocator") || + !require(c.own_list->Reset(c.own_allocator.Get(), nullptr), "target list")) + return false; + D3D12_RESOURCE_BARRIER barrier{D3D12_RESOURCE_BARRIER_TYPE_TRANSITION, D3D12_RESOURCE_BARRIER_FLAG_NONE, {}}; + barrier.Transition = {target, D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, D3D12_RESOURCE_STATE_COMMON, + D3D12_RESOURCE_STATE_COPY_SOURCE}; + c.own_list->ResourceBarrier(1, &barrier); + D3D12_TEXTURE_COPY_LOCATION to{c.readback.Get(), D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, {}}; + to.PlacedFootprint = footprint; + D3D12_TEXTURE_COPY_LOCATION from{target, D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, {0}}; + c.own_list->CopyTextureRegion(&to, 0, 0, 0, &from, nullptr); + barrier.Transition.StateBefore = D3D12_RESOURCE_STATE_COPY_SOURCE; + barrier.Transition.StateAfter = D3D12_RESOURCE_STATE_COMMON; + c.own_list->ResourceBarrier(1, &barrier); + if (!c.own_run()) return false; + void* mapped = nullptr; + const D3D12_RANGE all{0, static_cast(total)}; + if (!require(c.readback->Map(0, &all, &mapped), "target readback map")) return false; + std::memcpy(bytes, mapped, static_cast(total)); + c.readback->Unmap(0, nullptr); + row_pitch = footprint.Footprint.RowPitch; + return true; +} + +std::uint32_t expected_target_pixel(UINT x, UINT y) +{ + if (x >= draw_covered || y >= draw_covered) return draw_clear_pixel; + std::uint32_t word = 0; + for (UINT byte = 0; byte < 4; ++byte) + word |= std::uint32_t{pattern_byte(draw_seed, y * pitch + x * 4 + byte)} << (8 * byte); + return word; +} + +bool check_target(const char* stage, const std::uint8_t* bytes, UINT row_pitch) +{ + for (UINT y = 0; y < draw_side; ++y) + for (UINT x = 0; x < draw_side; ++x) { + std::uint32_t got = 0; + std::memcpy(&got, bytes + y * row_pitch + x * 4, sizeof(got)); + const std::uint32_t want = expected_target_pixel(x, y); + if (got == want) continue; + std::printf("FAIL: %s: pixel (%u,%u) got %08lx want %08lx\n", stage, x, y, + static_cast(got), static_cast(want)); + return false; + } + return true; +} + // 1: slot 133 title_memory texture upload & copy lifetime across closed list and gated submission. bool case1_slot133_copy_and_upload(Context& c, bool on, void* title_mem) { @@ -662,6 +847,121 @@ bool case6_written_generation_preserved(Context& c, void* title_mem) return true; } +// 7 (B1): a translated draw samples a slot 133 title-memory texture through a descriptor table. The draw's view +// token must resolve to that texture (a broken resolution binds the wrong view and the readback disagrees), and +// the recording holds it so its final Release cannot drop it from the budget before the recording is dropped. +bool case7_draw_samples_slot133_texture(Context& c, void* title_mem) +{ + ComPtr root, pipeline; + if (!prepare_draw_translation(c, root, pipeline)) return false; + + fill_title_memory(title_mem, draw_seed); + // No COM reference to the desktop object here: it would keep the budget ticket of the retired texture alive. + Res& T = c.make_slot133("T_draw", title_mem); + + D3D12_RESOURCE_DESC target_desc = c.desc; + target_desc.Width = target_desc.Height = draw_side; + target_desc.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET; + const D3D12_HEAP_PROPERTIES default_heap{D3D12_HEAP_TYPE_DEFAULT}; + ComPtr target; + if (!require(c.device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &target_desc, + D3D12_RESOURCE_STATE_COMMON, nullptr, IID_PPV_ARGS(&target)), + "draw target")) + return false; + const struct { + D3D12_DESCRIPTOR_HEAP_DESC desc; + UINT64 backing, bytes; + } rtv_heap_desc{{D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 1}, 0, 0}; + ComPtr rtv_heap; + if (!require(invoke(c.guest, 14, &rtv_heap_desc, &__uuidof(ID3D12DescriptorHeap), rtv_heap.GetAddressOf()), + "draw rtv heap")) + return false; + const UINT64 rtv = invoke(rtv_heap.Get(), 9); + invoke(c.guest, 20, target.Get(), static_cast(nullptr), rtv); + + const struct { + D3D12_DESCRIPTOR_HEAP_DESC desc; + UINT64 backing, bytes; + } view_heap_desc{{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 1, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE}, 0, 0}; + ComPtr views; + if (!require(invoke(c.guest, 14, &view_heap_desc, &__uuidof(ID3D12DescriptorHeap), views.GetAddressOf()), + "draw view heap")) + return false; + const UINT64 view_cpu = invoke(views.Get(), 9); + const UINT64 view_gpu = invoke(views.Get(), 10); + 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, T.guest.Get(), &srv, view_cpu); + + GuestList L; + if (!c.make_list(L)) return false; + const D3D12_CPU_DESCRIPTOR_HANDLE target_view{static_cast(rtv)}; + const float clear[4] = {1.0f, 0.0f, 1.0f, 1.0f}; + const D3D12_VIEWPORT viewport{0, 0, static_cast(draw_side), static_cast(draw_side), 0, 1}; + const D3D12_RECT scissor{0, 0, draw_covered, draw_covered}; // the last row and column stay clear + invoke(L.list.Get(), 52, rtv, clear, 0u, static_cast(nullptr)); + invoke(L.list.Get(), 50, 1u, &target_view, FALSE, static_cast(nullptr)); + invoke(L.list.Get(), 25, pipeline.Get()); + invoke(L.list.Get(), 34, root.Get()); + IUnknown* heaps[] = {views.Get()}; + invoke(L.list.Get(), 32, 1u, heaps); + invoke(L.list.Get(), 36, 0u, view_gpu); + invoke(L.list.Get(), 20, static_cast(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST)); + invoke(L.list.Get(), 21, 1u, &viewport); + invoke(L.list.Get(), 22, 1u, &scissor); + invoke(L.list.Get(), 12, 3u, 1u, 0u, 0u); + if (!c.close(L)) return false; + c.execute(c.direct, L); + if (!c.sync(c.direct)) return false; + + std::array target_bytes{}; + UINT row_pitch = 0; + if (!read_target(c, target.Get(), target_desc, target_bytes.data(), row_pitch)) return false; + if (!check_target("slot 133 texture sampled by a translated draw", target_bytes.data(), row_pitch)) return false; + + // The draw path records the bind as a hold on the list, so the closed recording keeps the texture alive. The + // wrapper outlives its guest release, so the raw pointer still probes the list's holds afterwards. + IUnknown* const t_guest = T.guest.Get(); + + // Release the guest resource, then drop the descriptor that holds its slot 18 SRV reference by overwriting it + // with a view of the target. Only the draw's hold is left. + c.release(T); + D3D12_SHADER_RESOURCE_VIEW_DESC replaced = srv; + invoke(c.guest, 18, target.Get(), &replaced, view_cpu); + + // Draining while the closed list still names the texture keeps it retained, after its final Release too. + for (int i = 0; i < 8; ++i) { + c.drain_once(); + if (!c.sync(c.direct)) return false; + } + if (!c.expect("slot 133 texture held by the closed draw list", + "slot 133 texture left the budget before its draw recording was dropped")) + return false; + + RetireProbe held{}; + if (!x2w_d3d12_retire_probe(t_guest, L.list.Get(), &held) || held.list_holds == 0) { + std::printf("FAIL: translated draw recorded no retire hold on the slot 133 texture (list_holds=%u)\n", + held.list_holds); + return false; + } + + // The readback is still the sampled texel content after the release and the drains. + if (!read_target(c, target.Get(), target_desc, target_bytes.data(), row_pitch)) return false; + if (!check_target("readback after the guest release and drain", target_bytes.data(), row_pitch)) return false; + + // Dropping the recording releases the hold; only then may the texture leave the budget. + if (!SUCCEEDED(c.reset_list(L))) return false; + T.freed = true; + if (!c.settle("slot 133 draw hold dropped", "slot 133 texture kept after its draw recording was dropped")) + return false; + + if (!read_target(c, target.Get(), target_desc, target_bytes.data(), row_pitch)) return false; + return check_target("readback after the texture left the budget", target_bytes.data(), row_pitch); +} + } // namespace int main(int argc, char** argv) @@ -751,6 +1051,8 @@ int main(int argc, char** argv) } else { if (!case6_written_generation_preserved(c, mem3)) return 5; std::puts("6 written_textures generation: newer generation of an address kept by the older one's retirement"); + if (!case7_draw_samples_slot133_texture(c, mem1)) return 5; + std::puts("7 translated draw: slot 133 texture sampled through a descriptor table, held until the recording drained"); } } catch (int code) { VirtualFree(mem1, 0, MEM_RELEASE); From e29b1a7bcf121cc58e52bd1340a46b8edded2e08 Mon Sep 17 00:00:00 2001 From: Royoo <3230853833@qq.com> Date: Thu, 26 Nov 2026 03:30:47 +0800 Subject: [PATCH 6/6] runtime: preserve write metadata for same-address live SRVs --- src/startup_stubs/d3d12_xs_device.cpp | 3 ++- tests/startup_resource_retire_title.cpp | 17 ++++++++++++++--- 2 files changed, 16 insertions(+), 4 deletions(-) diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index 7e9a794a37..cf64c23314 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -4396,7 +4396,8 @@ bool retire_address_has_live_user(u64 address, const Wrapper* skip) AcquireSRWLockShared(¬e_lock); resource_address_index().for_each_reaching(address, 1, [&](const Wrapper* wrapper) { if (wrapper == skip || reinterpret_cast(wrapper->own().title_memory) != address) return false; - if (InterlockedCompareExchange(const_cast(&wrapper->own().refs), 0, 0) > 0) { + if (InterlockedCompareExchange(const_cast(&wrapper->own().refs), 0, 0) > 0 || + InterlockedCompareExchange(const_cast(&wrapper->own().retire_view_refs), 0, 0) > 0) { other_live = true; return true; } diff --git a/tests/startup_resource_retire_title.cpp b/tests/startup_resource_retire_title.cpp index 9dc77ffd3c..756a9015f7 100644 --- a/tests/startup_resource_retire_title.cpp +++ b/tests/startup_resource_retire_title.cpp @@ -800,9 +800,8 @@ bool case5_ordinary_upload_switch_off(Context& c) return true; } -// 6: written_textures() generation keeping (switch on). A live slot-18 SRV keeps the older resource's entry while it -// is pending; a newer generation of the same address then arrives and must survive the older generation's retirement -// (the snapshot-generation check), so the newer write is not mistaken for the older one's stale state. +// 6: A live slot-18 SRV keeps the current format metadata even after both same-address guest wrappers are released. +// The older wrapper's eventual retirement must also leave the newer generation intact. bool case6_written_generation_preserved(Context& c, void* title_mem) { x2w_d3d12_bc7_4k_s_written(title_mem, side, side); // generation 1 of this address @@ -833,6 +832,18 @@ bool case6_written_generation_preserved(Context& c, void* title_mem) } // A newer generation of the same address while the older resource is still pending behind its view. x2w_d3d12_bc7_4k_s_written(title_mem, side, side); + Res& Tnew = c.make_slot133("T_gen_new", title_mem); + c.release(Tnew); + if (!x2w_d3d12_written_probe(title_mem, &generation, &bc7_width, nullptr) || generation != 2 || bc7_width != side) { + std::puts("FAIL: releasing the newer wrapper erased metadata used by the older wrapper's live SRV"); + return false; + } + Tnew.freed = true; + if (!c.settle("newer wrapper retired with older SRV live", "newer wrapper kept or older SRV retired")) return false; + if (!x2w_d3d12_written_probe(title_mem, &generation, &bc7_width, nullptr) || generation != 2 || bc7_width != side) { + std::puts("FAIL: draining the newer wrapper erased metadata used by the older wrapper's live SRV"); + return false; + } heap.Reset(); // drops the view reference: the older resource can retire now Told.freed = true; if (!c.settle("older generation retired", "older generation kept after its view was released")) return false;