diff --git a/CMakePresets.json b/CMakePresets.json index 8fff29df28..91ff65237c 100644 --- a/CMakePresets.json +++ b/CMakePresets.json @@ -34,7 +34,7 @@ "xmem_run_break_readers_check", "xmem_run_break_readers_control", "xmem_cross_call_merge_check", "xmem_placeholder_split_check", "xmem_map_split_first_check", "startup_dstorage_break_window_check", "xmem_page_runs_device_check", "linear_buffer_backing_check", - "bcpack_formats_check", "startup_stub_consumer" + "bcpack_formats_check", "startup_stub_consumer", "startup_inline_retire", "startup_resource_retire_title" ] }, { "name": "release", "configurePreset": "release" }, @@ -48,7 +48,7 @@ "displayName": "Windows pull request smoke tests", "filter": { "include": { - "name": "^(bcpack_all_formats(_golden_control)?|startup_bcpack_storage|desktop_root_signature|era_heap_(allocation|failure)|xmem_shim_mapped_pages|cpu_aot_fuzz_smoke|cpu_archive_texture_gpu_warp|dual_uav_warp|spirv_.*_warp|static_exe_intake|descriptor_heap_paging(_swapped)?_warp|startup_launch|startup_tools_lint|startup_gfx2hlsl_cvt_off_f32_i4_controls|startup_gfx2hlsl_sad_hi_msad_controls|startup_indirect_(dispatch|count_split|draw(_indexed)?|mesh(_xmem_arguments(_skip_wait)?)?|counts_control)_warp|startup_indirect_mesh_lease_warp_dual(-trace(-disabled)?)?|startup_shader_cache_key|startup_present_readback|xmem_(run_break_readers|cross_call_merge|placeholder_split|map_split_first)(_[a-z_]+)?|startup_dstorage_break_window(_[a-z_]+)?|xmem_page_runs_device(_join)?_warp|linear_buffer_backing_share_warp|startup_stage_package)$" + "name": "^(bcpack_all_formats(_golden_control)?|startup_bcpack_storage|desktop_root_signature|era_heap_(allocation|failure)|xmem_shim_mapped_pages|cpu_aot_fuzz_smoke|cpu_archive_texture_gpu_warp|dual_uav_warp|spirv_.*_warp|static_exe_intake|descriptor_heap_paging(_swapped)?_warp|startup_launch|startup_tools_lint|startup_gfx2hlsl_cvt_off_f32_i4_controls|startup_gfx2hlsl_sad_hi_msad_controls|startup_indirect_(dispatch|count_split|draw(_indexed)?|mesh(_xmem_arguments(_skip_wait)?)?|counts_control)_warp|startup_indirect_(dispatch|constants|count)_inline_warp|startup_inline_retire_(on|control)_warp|startup_resource_retire_title_inline_warp_debug0|startup_indirect_mesh_lease_warp_dual(-trace(-disabled)?)?|startup_shader_cache_key|startup_present_readback|xmem_(run_break_readers|cross_call_merge|placeholder_split|map_split_first)(_[a-z_]+)?|startup_dstorage_break_window(_[a-z_]+)?|xmem_page_runs_device(_join)?_warp|linear_buffer_backing_share_warp|startup_stage_package)$" } } }, diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index ecf3ba26d3..bcae1516e4 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -1661,6 +1661,7 @@ ctest --preset dev --no-tests=error -R '^startup_hook_(window|overlap)$' -V | `X2W_D3D12_QUERY_SLOTS=1` | diagnostic, in render mode: binds command-list slots 28 to 30 to the confirmed `BeginQuery`, `EndQuery` and `ResolveQueryData` methods (see [Occlusion queries](#occlusion-queries)). The bindings remain diagnostic because the forwarding behavior is not a console runtime oracle. Unset, the three slots stay no-ops | | `X2W_D3D12_BUDGET=1` | adds [video memory budget and allocation counts](#d3d12-resource-budget) to the D3D12 heartbeat | | `X2W_D3D12_RELEASE_RETIRED=1` | opt-in, effective with `X2W_D3D12_RENDER=1` only (the list handlers that record holds exist only there): frees the desktop object of a released committed 2D texture of one narrow class once no recorded list, submission or release-time fence refers to it ([details](#d3d12-resource-budget)). Unset, nothing changes | +| `X2W_D3D12_INLINE_DESCRIPTORS=1` | opt-in: leaves byte +0x18 of the guest device at 0, so the title writes constant buffer views and copies CBV/SRV/UAV descriptors itself instead of calling device slots 17 and 24 (sampler copies still arrive through slot 24); with `X2W_D3D12_RELEASE_RETIRED=1`, a retired resource is then freed once its release fences pass ([details](#d3d12-inline-descriptors)). Unset, nothing changes | | `X2W_D3D12_RELEASE_RETIRED_VIEWS=1` | legacy diagnostic. Logs that clearing live slots is disabled and enables the existing retirement breakdown when base retirement and budgets are on ([details](#d3d12-resource-budget)) | | `X2W_D3D12_RETIRE_REASONS=1` | diagnostic only, effective with `X2W_D3D12_RELEASE_RETIRED=1` and `X2W_D3D12_BUDGET=1`: adds one `x2w-retire held:` line to the heartbeat that counts final-released resources whose desktop object is still alive, by reason ([details](#d3d12-resource-budget)). Unset, nothing is recorded | | `X2W_D3D12_VIEW_DEFAULTS=all` or `=off` | `all` is experimental: UAV, RTV and DSV descriptions with `ViewDimension` 0 also get the resource's default view, which drops their requested format and component mapping. `off` skips the measured SRV case too. Unset, only SRVs of typed non-depth textures get the default view ([details](#unknown-and-mismatched-view-dimensions)) | @@ -1940,6 +1941,36 @@ FALSE without the switch, like `x2w_d3d12_budget_snapshot`. `startup_resource_re 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. +## D3D12 inline descriptors + +The guest device ABI checks byte +0x18 of the device before it writes descriptors itself. The stand-in sets it +(#3211), so the title calls device slot 17 for every constant buffer view and slot 24 for every +`CopyDescriptorsSimple`, and the stand-in records each of them. `X2W_D3D12_INLINE_DESCRIPTORS=1` leaves the byte at +0: + +- Slot 17 calls stop, and slot 24 calls for CBV/SRV/UAV heaps stop; sampler copies still arrive through slot 24. + Constant buffer views in title descriptor memory are then hardware buffer + descriptors, which the draw and compute buffer readers already decode (the branch of `indirect_table_buffer` for + words that are not a view token). Texture views are still created through slot 18, so their tokens still name + view records; a copy of one is a plain copy of the token. +- With `X2W_D3D12_RELEASE_RETIRED=1`, `retire_view_refs` no longer sees every descriptor that names a resource, + because copies made in title memory are not counted. A retired resource is then freed once its release fences + pass and no recorded list or submission holds it: as in D3D12, the application keeps a resource alive while its + descriptors are in use. Wrappers are never freed, so a token that names a freed resource still finds the dead + wrapper (no desktop object) and binds null; a wrapper address is never reused for another resource. +- A draw, mesh or compute call that reads a texture through a descriptor takes the list's retire hold before its + first use of it, under `retire_lock`. If the drain already freed it, the call binds null (draw) or refuses + (mesh, compute) and the case is logged as `x2w-d3d12 retire: N reads found their texture already freed; bound + null`. A repeated hold by the same recording skips the lock (a per-recording stamp on the resource). +- Fixtures: `startup_resource_retire_title_inline_{warp,hardware}_debug{0,1}` (case 11: a translated draw through a + stale descriptor holds a released texture, also from a second list and after its own list's reset, and binds null + once it is freed), `startup_inline_retire_{on,control}_{warp,hardware}` (a texture view, a 32-byte copy made with + `memcpy`, release, fences, `x2w_d3d12_token_texture` for what a draw would bind, 64 new textures for address reuse) + and `startup_indirect_{dispatch,constants,count}_inline_{warp,hardware}` (byte +0x18 stays 0; the indirect dispatch + cases pass). + +Unset, the byte is set and retirement waits for `retire_view_refs` as before. + ## D3D12 view allocation failure A new view record goes into three containers: the record vector, the vector of diff --git a/src/startup_stubs/d3d12_compute_dispatch.inl b/src/startup_stubs/d3d12_compute_dispatch.inl index f93ffcfc77..f6c6a55c1b 100644 --- a/src/startup_stubs/d3d12_compute_dispatch.inl +++ b/src/startup_stubs/d3d12_compute_dispatch.inl @@ -686,8 +686,11 @@ const char* record_translated_dispatch(Wrapper* self, const TranslatedDispatch& ReleaseSRWLockShared(¬e_lock); } Wrapper* const wrapper = known ? as_wrapper(reinterpret_cast(record.resource)) : nullptr; - ID3D12Resource* const texture = !wrapper || wrapper->own().kind != resource_kind ? nullptr + ID3D12Resource* texture = !wrapper || wrapper->own().kind != resource_kind ? nullptr : output ? static_cast(wrapper->own().real) : sampled_address_texture(wrapper); + // Hold before the first use: the drain can free a retired texture that descriptors still name. An output + // is the wrapper's own object; an input of a tiled address SRV is a separate texture outside the class. + if (texture && (output || !wrapper->own().tiled_address_srv) && !retire_hold(self, wrapper)) texture = nullptr; const D3D12_RESOURCE_DESC resource = texture ? texture->GetDesc() : D3D12_RESOURCE_DESC{}; if (!output) { D3D12_SHADER_RESOURCE_VIEW_DESC desc{}; diff --git a/src/startup_stubs/d3d12_draw.inl b/src/startup_stubs/d3d12_draw.inl index 1933d5f78e..75f7ec65db 100644 --- a/src/startup_stubs/d3d12_draw.inl +++ b/src/startup_stubs/d3d12_draw.inl @@ -3112,6 +3112,8 @@ bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UI desc.Texture2D.MipLevels = 1; // shared MostDetailedMip and MipLevels in all supported texture views if (srv.kind == 2) desc.Texture2DArray.ArraySize = 1; ID3D12Resource* texture = sampled_address_texture(resource); + // Hold before the first use: the drain can free a retired texture that descriptors still name. + if (texture && !resource->own().tiled_address_srv && !retire_hold(self, resource)) texture = nullptr; if (texture && record.desc_bytes >= 40) { std::memcpy(&desc, record.desc, 40); desc.Format = desktop_format(desc.Format); @@ -3149,10 +3151,7 @@ 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 (resource && !resource->own().tiled_address_srv) retire_hold(self, resource); - } + if (texture) require_state(self, texture, sampled_state(self, texture)); 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 56dbe26c48..38d33e425d 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -202,6 +202,10 @@ struct alignas(16) WrapperOwn { std::uint8_t retire_never; // RetireNever of this resource (set only with X2W_D3D12_RELEASE_RETIRED) std::uint8_t retire_left; // RetireLeft: the first use that took it out of the class volatile LONG retire_view_refs; // Live tracked slot-18 SRV descriptor slots referencing this resource. + // retire_hold fast path: a list's current hold set has a stamp (never reused, 0 = none), and a resource carries + // the stamp of the last set that held it, so a repeated hold by the same recording skips the lock and the search. + u64 retire_hold_stamp; // CommandList: stamp of its current retire_list_holds entry + volatile LONG64 retire_held_stamp; // Resource: stamp of the last hold set that took it 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. volatile LONG64 output_trace_recording; @@ -495,6 +499,22 @@ u64 unwrap(u64 value) volatile LONG wraps_to_fail; // fixture-only, set by x2w_d3d12_fail_wraps constexpr u64 out_of_memory = static_cast(E_OUTOFMEMORY); // for slots that return u64 +// X2W_D3D12_INLINE_DESCRIPTORS=1 (opt-in, docs/startup-runtime.md#d3d12-inline-descriptors): wrap() leaves device byte +// +0x18 at 0, so the title writes CBVs and copies CBV/SRV/UAV descriptors itself (no slot 17, no slot 24 for them). The +// retire drain cannot count those copies, so a retired resource is freed once its release fences pass: D3D12 leaves +// descriptor lifetime to the application. Wrappers are never freed, so a stale token still names the dead wrapper +// (real == null) and binds null. +bool inline_descriptors_on() +{ + static const bool on = [] { + const bool value = x2w_local::env_on("X2W_D3D12_INLINE_DESCRIPTORS"); + if (value) log("x2w-d3d12 X2W_D3D12_INLINE_DESCRIPTORS=1: device byte +0x18 left 0 (title writes CBVs and copies descriptors " + "inline; retired resources freed at their fences)"); + return value; + }(); + return on; +} + // Returns nullptr when the wrapper cannot be allocated or registered (#2653). The caller still owns // `real` then: it releases what it created and returns E_OUTOFMEMORY. Wrapper* wrap(IUnknown* real, Kind kind) @@ -517,7 +537,7 @@ Wrapper* wrap(IUnknown* real, Kind kind) // The guest checks device byte +0x18 before using its inline descriptor // writers. Request vtable calls so the shim records the descriptor. static_assert(offsetof(Wrapper, console_fields) + 2 * sizeof(u64) == 0x18); - if (kind == device_kind) w->console_fields[2] = 1; + if (kind == device_kind && !inline_descriptors_on()) w->console_fields[2] = 1; if (kind == fence_kind && real) w->own().completed = static_cast(static_cast(real)->GetCompletedValue()); AcquireSRWLockExclusive(®istry_lock); try { @@ -1050,7 +1070,7 @@ 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); +bool retire_hold(Wrapper* list, Wrapper* resource); void retire_drop_recording(Wrapper* list); void release_list_recording(Wrapper* list); void clear_draw_sampler_snapshot(Wrapper* self); @@ -6001,7 +6021,7 @@ std::vector retire_flights; std::unordered_map> retire_list_holds; // one desktop reference per entry volatile LONG retire_pending; // retired_resources and retire_flights, read without the lock volatile LONG retire_holds; // entries of retire_list_holds, read without the lock -volatile LONG64 retire_freed, retire_kept; +volatile LONG64 retire_freed, retire_kept, retire_hold_late; void register_retire_queue(Wrapper* queue) { @@ -6105,15 +6125,30 @@ void retire_note_title_release(Wrapper* w) // 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. -void retire_hold(Wrapper* list, Wrapper* resource) -{ - if (!resource || !resource->own().retire_when_idle) return; +// A draw, mesh or compute read reaches a texture through a descriptor, which with X2W_D3D12_INLINE_DESCRIPTORS no +// longer keeps it: the caller takes the hold before its first use of the texture and binds nothing on false, which +// means the drain has already claimed the desktop object (own().real cleared). +bool retire_hold(Wrapper* list, Wrapper* resource) +{ + if (!resource || !resource->own().retire_when_idle) return true; + // Already held by this recording: its holds are dropped only by retire_discard_holds of this list, on the thread + // that records it, and a stamp is never reused, so the desktop object the caller read is still referenced. + const u64 stamp = list->own().retire_hold_stamp; + if (stamp && static_cast(InterlockedCompareExchange64(&resource->own().retire_held_stamp, 0, 0)) == stamp) + return true; 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) { + if (!real) { + ReleaseSRWLockExclusive(&retire_lock); + const LONG64 late = InterlockedIncrement64(&retire_hold_late); + if (late <= 8 || late % 1000 == 0) + log("x2w-d3d12 retire: %lld reads found their texture already freed; bound null", late); + return false; + } + { 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()) { @@ -6125,6 +6160,9 @@ void retire_hold(Wrapper* list, Wrapper* resource) InterlockedIncrement(&retire_holds); held = true; } + static u64 next_stamp; // under retire_lock + if (!list->own().retire_hold_stamp) list->own().retire_hold_stamp = ++next_stamp; + InterlockedExchange64(&resource->own().retire_held_stamp, static_cast(list->own().retire_hold_stamp)); } catch (const std::bad_alloc&) { } } @@ -6136,10 +6174,12 @@ void retire_hold(Wrapper* list, Wrapper* resource) resource->own().retire_hold_missed = true; } ReleaseSRWLockExclusive(&retire_lock); + return true; } void retire_discard_holds(Wrapper* list) { + list->own().retire_hold_stamp = 0; // the next hold opens a new set; resources stamped with the old one miss if (!InterlockedCompareExchange(&retire_holds, 0, 0)) return; std::vector dropped; AcquireSRWLockExclusive(&retire_lock); @@ -6272,7 +6312,7 @@ void drain_retired_resources() InterlockedDecrement(&retire_pending); continue; } - if (InterlockedCompareExchange(&w->own().retire_view_refs, 0, 0) > 0) { + if (!inline_descriptors_on() && InterlockedCompareExchange(&w->own().retire_view_refs, 0, 0) > 0) { ++i; continue; } @@ -6460,7 +6500,8 @@ void retire_reasons_collect(RetireReasonReport& report) why = held_never[w->own().retire_never]; } else if (found == queued.end()) { why = Held::unqueued; - } else if (InterlockedCompareExchange(&w->own().retire_view_refs, 0, 0) > 0) { + } else if (!inline_descriptors_on() && InterlockedCompareExchange(&w->own().retire_view_refs, 0, 0) > 0) { + // the drain waits on view refs only without X2W_D3D12_INLINE_DESCRIPTORS why = Held::view_refs; if (const auto view = viewed.find(w); view != viewed.end() && view->second) { ++report.visible_count; @@ -6583,6 +6624,27 @@ extern "C" __declspec(dllexport) void x2w_d3d12_view_probe(unsigned long long ti } } +// Fixture export (startup_inline_retire): what a draw binds for a 32-byte texture token, step by step as the +// texture path does it (record id, as_wrapper, sampled_address_texture). wrapper: the resource wrapper the token +// names when it is still registered; texture: the desktop texture bound, or null (a null binding). +extern "C" __declspec(dllexport) BOOL x2w_d3d12_token_texture(const void* token, void** wrapper, void** texture) +{ + *wrapper = *texture = nullptr; + std::uint32_t words[8]; + std::memcpy(words, token, sizeof(words)); + ViewRecord record{}; + if (words[0] != view_token_magic) return FALSE; + AcquireSRWLockShared(¬e_lock); + const bool known = words[1] < view_records().size(); + if (known) record = view_records()[words[1]]; + ReleaseSRWLockShared(¬e_lock); + if (!known) return FALSE; + Wrapper* resource = as_wrapper(reinterpret_cast(record.resource)); + *wrapper = resource; + *texture = sampled_address_texture(resource); + return TRUE; +} + // Fixture-only: the next `count` wrapper allocations fail as an exhausted heap would (#2653). extern "C" __declspec(dllexport) void x2w_d3d12_fail_wraps(LONG count) { diff --git a/src/startup_stubs/native_mesh57.inl b/src/startup_stubs/native_mesh57.inl index b8455b82d3..a2632edd91 100644 --- a/src/startup_stubs/native_mesh57.inl +++ b/src/startup_stubs/native_mesh57.inl @@ -120,6 +120,8 @@ const char* bind_mesh57_buffers(Wrapper* self, Pass& pass, ID3D12GraphicsCommand if (record.resource) { sampled.owner=as_wrapper(reinterpret_cast(record.resource)); auto* tex=sampled_address_texture(sampled.owner); + // Hold before the first use: the drain can free a retired texture that descriptors still name. + if (tex && !sampled.owner->own().tiled_address_srv && !retire_hold(self,sampled.owner)) tex=nullptr; if (!tex || tex==arguments || std::find(pass.bound_targets,pass.bound_targets+pass.target_count,tex)!=pass.bound_targets+pass.target_count || (tex==pass.bound_depth && pass.depth_view_writable)) return "PS heap texture missing or aliased to a writable attachment"; const auto d=tex->GetDesc(); @@ -184,10 +186,7 @@ const char* bind_mesh57_buffers(Wrapper* self, Pass& pass, ID3D12GraphicsCommand auto dst=heap->GetCPUDescriptorHandleForHeapStart(); dst.ptr+=SIZE_T{texture.slot}*increment; device->CreateShaderResourceView(texture.resource.Get(),&texture.view,dst); - if (texture.resource) { - require_state(self, texture.resource.Get(), sampled_state(self, texture.resource.Get())); - if (!texture.owner->own().tiled_address_srv) retire_hold(self, texture.owner); - } + if (texture.resource) require_state(self, texture.resource.Get(), sampled_state(self, texture.resource.Get())); } auto handle = heap->GetCPUDescriptorHandleForHeapStart(); handle.ptr += SIZE_T{start} * increment; diff --git a/tests/cmake/startup_inline_retire.cmake b/tests/cmake/startup_inline_retire.cmake new file mode 100644 index 0000000000..0435b8a966 --- /dev/null +++ b/tests/cmake/startup_inline_retire.cmake @@ -0,0 +1,46 @@ +# X2W_D3D12_INLINE_DESCRIPTORS=1 (docs/startup-runtime.md#d3d12-inline-descriptors): retired textures are freed +# at their release fences although descriptors (including the title's own 32-byte copies) still name them; those +# then bind null, and a freed wrapper's address is never reused. control: the switch unset, the live slot keeps the +# texture until it is overwritten. +add_executable(startup_inline_retire tests/startup_inline_retire.cpp) +target_include_directories(startup_inline_retire PRIVATE src) +target_compile_features(startup_inline_retire PRIVATE cxx_std_17) +target_link_libraries(startup_inline_retire PRIVATE d3d12_xs_shim d3d12 dxgi) +foreach(backend IN ITEMS warp hardware) + foreach(mode IN ITEMS on control) + set(inline_test startup_inline_retire_${mode}_${backend}) + add_test(NAME ${inline_test} COMMAND startup_inline_retire ${backend} ${mode}) + set(inline_env "X2W_D3D12_BUDGET=1;X2W_D3D12_RELEASE_RETIRED=1;X2W_D3D12_PERMISSIVE=1;X2W_D3D12_LIST_NOOP=1") + list(APPEND inline_env "X2W_D3D12_RENDER=1" "X2W_D3D12_DEBUG=0") + if(mode STREQUAL "on") + list(APPEND inline_env "X2W_D3D12_INLINE_DESCRIPTORS=1") + endif() + set_tests_properties(${inline_test} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 ENVIRONMENT "${inline_env}") + endforeach() +endforeach() +# startup_indirect_dispatch with the switch: byte +0x18 stays 0 and the indirect dispatch cases still pass. +foreach(backend IN ITEMS warp hardware) + foreach(mode IN ITEMS dispatch constants count) + set(inline_dispatch startup_indirect_${mode}_inline_${backend}) + if(mode STREQUAL "dispatch") + add_test(NAME ${inline_dispatch} COMMAND startup_indirect_dispatch ${backend}) + else() + add_test(NAME ${inline_dispatch} COMMAND startup_indirect_dispatch ${backend} ${mode}) + endif() + set_tests_properties(${inline_dispatch} PROPERTIES TIMEOUT 30 ENVIRONMENT "X2W_D3D12_INLINE_DESCRIPTORS=1") + if(backend STREQUAL "hardware") + set_tests_properties(${inline_dispatch} PROPERTIES SKIP_RETURN_CODE 77) + endif() + endforeach() +endforeach() +# startup_resource_retire_title inline (case 11, #3429 review): a translated draw through a stale descriptor of a +# released texture records a retire hold, so the texture outlives its fences until the recording is dropped; once +# freed, the same descriptor binds null. debug1 runs it under the D3D12 debug layer (no stored messages allowed). +foreach(backend IN ITEMS warp hardware) + foreach(debug IN ITEMS 0 1) + set(inline_draw startup_resource_retire_title_inline_${backend}_debug${debug}) + add_test(NAME ${inline_draw} COMMAND startup_resource_retire_title ${backend} inline) + set_tests_properties(${inline_draw} 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=${debug};X2W_D3D12_RELEASE_RETIRED=1;X2W_D3D12_INLINE_DESCRIPTORS=1") + endforeach() +endforeach() diff --git a/tests/startup_indirect_dispatch.cpp b/tests/startup_indirect_dispatch.cpp index 5d8d53e01e..561014690b 100644 --- a/tests/startup_indirect_dispatch.cpp +++ b/tests/startup_indirect_dispatch.cpp @@ -378,8 +378,14 @@ int main(int argc, char** argv) try const std::array parameters{}; ComPtr guest; check(D3D12XboxCreateDevice(adapter.Get(), parameters.data(), IID_PPV_ARGS(&guest)), "create guest device"); - if (!reinterpret_cast(guest.Get())[0x18]) { - std::fputs("guest device permits inline descriptor creation\n", stderr); + // Byte +0x18 makes the guest call the shim for CBVs and copies (#3211); X2W_D3D12_INLINE_DESCRIPTORS=1 leaves it 0. + char inline_value[2]{}; + const bool inline_descriptors = + GetEnvironmentVariableA("X2W_D3D12_INLINE_DESCRIPTORS", inline_value, sizeof(inline_value)) == 1 && + inline_value[0] == '1'; + if (!reinterpret_cast(guest.Get())[0x18] != inline_descriptors) { + std::fputs(inline_descriptors ? "guest device does not permit inline descriptor creation\n" + : "guest device permits inline descriptor creation\n", stderr); return 1; } DXGI_ADAPTER_DESC1 adapter_desc{}; diff --git a/tests/startup_inline_retire.cpp b/tests/startup_inline_retire.cpp new file mode 100644 index 0000000000..d6d95d9bf7 --- /dev/null +++ b/tests/startup_inline_retire.cpp @@ -0,0 +1,363 @@ +// X2W_D3D12_INLINE_DESCRIPTORS=1 (docs/startup-runtime.md#d3d12-inline-descriptors): retirement once the title copies +// descriptors itself. +// startup_inline_retire +// on: X2W_D3D12_INLINE_DESCRIPTORS=1; control: unset. Both with X2W_D3D12_RELEASE_RETIRED=1 and X2W_D3D12_BUDGET=1. +// The title's own descriptor copy is a plain 32-byte memcpy in title descriptor memory (no slot 24 call), so no slot +// count sees it. With the switch a released texture is freed once its release fences pass, even while descriptors still +// name it; such a stale descriptor must then resolve to a null binding, never to another texture. In the control the +// live descriptor slot keeps the texture until it is overwritten, and a hand copy is not counted. +#include "startup_stubs/resource_budget.h" + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +using Microsoft::WRL::ComPtr; + +extern "C" __declspec(dllimport) HRESULT WINAPI D3D12XboxCreateDevice(IUnknown*, const void*, REFIID, void**); +extern "C" __declspec(dllimport) BOOL x2w_d3d12_budget_snapshot(x2w_budget::Snapshot*, SIZE_T); +extern "C" __declspec(dllimport) BOOL x2w_d3d12_token_texture(const void* token, void** wrapper, void** texture); + +namespace { +using namespace x2w_budget; + +constexpr UINT side = 64; +constexpr DWORD wait_ms = 10000; +constexpr int settle_limit = 200; +constexpr std::size_t token_bytes = 32; +constexpr std::uint32_t view_token_magic = 0x56573258; // "X2WV", d3d12_capture.inl + +template +Result invoke(IUnknown* object, unsigned slot, Args... args) +{ + using Call = Result (WINAPI*)(IUnknown*, Args...); + return reinterpret_cast((*reinterpret_cast(object))[slot])(object, args...); +} + +template +ComPtr desktop_object(IUnknown* guest, ID3D12Device* device, IUnknown* object) +{ + constexpr GUID key{0x0e34d52f, 0xd5a5, 0x4790, {0x91, 0xd4, 0x11, 0xa6, 0x7c, 0xbc, 0x2b, 0xc1}}; + ComPtr output; + if (FAILED(invoke(guest, 5, &key, object))) return output; + ComPtr reference; + UINT bytes = sizeof(IUnknown*); + const HRESULT hr = device->GetPrivateData(key, &bytes, reference.GetAddressOf()); + invoke(guest, 5, &key, static_cast(nullptr)); + if (SUCCEEDED(hr)) reference.As(&output); + return output; +} + +bool require(HRESULT hr, const char* stage) +{ + if (FAILED(hr)) std::printf("FAIL: %s hr=0x%08lx\n", stage, static_cast(hr)); + return SUCCEEDED(hr); +} + +ComPtr pick_adapter(IDXGIFactory4* factory, bool warp) +{ + ComPtr adapter; + if (warp) { + factory->EnumWarpAdapter(IID_PPV_ARGS(&adapter)); + return adapter; + } + wchar_t name[128]{}; + GetEnvironmentVariableW(L"XBOX2WINDOWS_ADAPTER", name, static_cast(std::size(name))); + for (UINT i = 0; factory->EnumAdapters1(i, &adapter) == S_OK; ++i, adapter.Reset()) { + DXGI_ADAPTER_DESC1 desc{}; + if (SUCCEEDED(adapter->GetDesc1(&desc)) && !(desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE) && + (!name[0] || std::wcsstr(desc.Description, name)) && + SUCCEEDED(D3D12CreateDevice(adapter.Get(), D3D_FEATURE_LEVEL_12_0, __uuidof(ID3D12Device), nullptr))) + return adapter; + } + return nullptr; +} + +struct Res { + ComPtr guest; + UINT64 bytes = 0; + bool released = false; + bool freed = false; +}; + +struct GuestQueue { + ComPtr queue, done; + ComPtr done_real; + UINT64 value = 0; +}; + +struct Context { + IUnknown* guest; + ID3D12Device* device; + HANDLE event = nullptr; + Snapshot base{}; + std::deque pool; + GuestQueue direct, gated; + ComPtr drain_allocator, drain_list; + ComPtr heap; + UINT64 heap_cpu = 0; + UINT increment = 0; + D3D12_RESOURCE_DESC desc{}; + UINT64 texture_bytes = 0; + + bool make_queue(GuestQueue& q) + { + const D3D12_COMMAND_QUEUE_DESC qd{D3D12_COMMAND_LIST_TYPE_DIRECT, 0, D3D12_COMMAND_QUEUE_FLAG_NONE, 0}; + if (!require(invoke(guest, 8, &qd, &__uuidof(ID3D12CommandQueue), q.queue.GetAddressOf()), "queue") || + !require(invoke(guest, 36, UINT64{0}, D3D12_FENCE_FLAG_NONE, &__uuidof(ID3D12Fence), q.done.GetAddressOf()), "fence")) + return false; + q.done_real = desktop_object(guest, device, q.done.Get()); + return q.done_real != nullptr; + } + bool sync(GuestQueue& q) + { + if (!require(invoke(q.queue.Get(), 14, q.done.Get(), ++q.value), "queue signal")) return false; + if (q.done_real->GetCompletedValue() >= q.value) return true; + if (SUCCEEDED(q.done_real->SetEventOnCompletion(q.value, event)) && WaitForSingleObject(event, wait_ms) == WAIT_OBJECT_0) + return true; + std::puts("FAIL: guest queue timed out"); + return false; + } + bool make_drain_list() + { + 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), + drain_allocator.GetAddressOf()), "allocator") && + require(invoke(guest, 73, list_desc, drain_allocator.Get(), nullptr, &__uuidof(ID3D12GraphicsCommandList), + drain_list.GetAddressOf()), "command list") && + require(invoke(drain_list.Get(), 139, drain_allocator.Get(), nullptr), "list reset") && + require(invoke(drain_list.Get(), 9), "list close"); + } + // A submission runs the retire drain. + void drain_once() + { + IUnknown* lists[] = {drain_list.Get()}; + invoke(direct.queue.Get(), 10, 1u, lists); + } + Res& make_texture(const char* name) + { + const D3D12_HEAP_PROPERTIES props{D3D12_HEAP_TYPE_DEFAULT}; + D3D12_RESOURCE_DESC d = desc; + Res& r = pool.emplace_back(); + r.bytes = texture_bytes; + if (!require(invoke(guest, 127, &props, D3D12_HEAP_FLAG_NONE, &d, D3D12_RESOURCE_STATE_COMMON, nullptr, nullptr, 0u, + nullptr, &__uuidof(ID3D12Resource), r.guest.GetAddressOf()), name)) + throw 4; + return r; + } + UINT64 slot(UINT index) const { return heap_cpu + std::uint64_t{index} * increment; } + void view(IUnknown* resource, UINT index) + { + 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(guest, 18, resource, &srv, slot(index)); + } + // The title's own copy: the token bytes only, no device call. + void hand_copy(UINT from, UINT to) const + { + std::memcpy(reinterpret_cast(slot(to)), reinterpret_cast(slot(from)), token_bytes); + } + // What a draw binds for the descriptor at `index`: the wrapper the token names and the desktop texture (or null). + bool binds(UINT index, const void* want_wrapper, bool want_texture, const char* what) const + { + std::uint32_t word = 0; + std::memcpy(&word, reinterpret_cast(slot(index)), sizeof(word)); + void* wrapper = nullptr; + void* texture = nullptr; + if (word != view_token_magic || !x2w_d3d12_token_texture(reinterpret_cast(slot(index)), &wrapper, &texture)) { + std::printf("FAIL: %s: slot %u holds no known view token\n", what, index); + return false; + } + if (wrapper == want_wrapper && (texture != nullptr) == want_texture) return true; + std::printf("FAIL: %s: token names wrapper %p (expected %p), binds %s (expected %s)\n", what, wrapper, want_wrapper, + texture ? "a texture" : "null", want_texture ? "a texture" : "null"); + return false; + } + bool expect(const char* stage, const char* fail) const + { + Snapshot now{}; + if (!x2w_d3d12_budget_snapshot(&now, sizeof(now))) return false; + UINT64 live_n = base.live[texture].objects, ret_n = base.retained[texture].objects; + for (const Res& r : pool) { + if (!r.released) ++live_n; + else if (!r.freed) ++ret_n; + } + const auto& got_live = now.live[texture]; + const auto& got_ret = now.retained[texture]; + if (got_live.objects == live_n && got_ret.objects == ret_n) return true; + std::printf("FAIL: %s\n stage '%s' live=%llu expected=%llu retained=%llu expected=%llu\n", fail, stage, + got_live.objects, live_n, got_ret.objects, 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) ret_n += r.released && !r.freed; + if (now.retained[texture].objects == ret_n) break; + } + return expect(stage, fail); + } +}; + +// 1: a texture with a live descriptor and a hand copy of it, then released. +bool case1_stale_copy(Context& c, bool on, const void*& old_wrapper) +{ + Res& t = c.make_texture("T1"); + old_wrapper = t.guest.Get(); + c.view(t.guest.Get(), 0); + c.hand_copy(0, 1); + if (!c.binds(0, old_wrapper, true, "case 1: original before Release") || + !c.binds(1, old_wrapper, true, "case 1: hand copy before Release")) + return false; + t.guest.Reset(); + t.released = true; + if (on) { + t.freed = true; + if (!c.settle("T1 released, descriptors still name it", "T1 not freed at its fences with inline descriptors")) + return false; + return c.binds(0, old_wrapper, false, "case 1: original after the free") && + c.binds(1, old_wrapper, false, "case 1: hand copy after the free"); + } + for (int i = 0; i < 8; ++i) + if (!c.stays("T1 with a live slot", "T1 freed while its slot was live (control)")) return false; + if (!c.binds(1, old_wrapper, true, "case 1: hand copy while the slot holds T1 (control)")) return false; + c.view(nullptr, 0); // overwrite the counted slot; the hand copy is not counted + t.freed = true; + return c.settle("T1 after its slot was overwritten", "T1 not freed after overwrite (control)") && + c.binds(1, old_wrapper, false, "case 1: hand copy after the free (control)"); +} + +// 2: new textures never take the freed texture's wrapper address, and the stale copy keeps naming the dead one. +bool case2_no_reuse(Context& c, const void* old_wrapper) +{ + for (int i = 0; i < 64; ++i) { + Res& t = c.make_texture("T2"); + if (t.guest.Get() == old_wrapper) { + std::puts("FAIL: case 2: a new texture reused the freed texture's wrapper address"); + return false; + } + } + return c.binds(1, old_wrapper, false, "case 2: hand copy after 64 new textures"); +} + +// 3: release behind a closed gate: nothing is freed before the release fences pass. +bool case3_fences(Context& c, bool on) +{ + Res& t = c.make_texture("T3"); + const void* wrapper = t.guest.Get(); + c.view(t.guest.Get(), 2); + c.hand_copy(2, 3); + ComPtr gate; + if (!require(invoke(c.guest, 36, UINT64{0}, D3D12_FENCE_FLAG_NONE, &__uuidof(ID3D12Fence), gate.GetAddressOf()), "gate") || + !require(invoke(c.gated.queue.Get(), 17, gate.Get(), UINT64{1}), "gate wait")) + return false; + t.guest.Reset(); + t.released = true; + for (int i = 0; i < 8; ++i) + if (!c.stays("T3 behind a closed gate", "T3 freed before its release fences passed")) return false; + if (!c.binds(3, wrapper, true, "case 3: hand copy before the gate opens")) return false; + if (!require(invoke(gate.Get(), 10, UINT64{1}), "signal gate") || !c.sync(c.gated)) return false; + if (!on) { + for (int i = 0; i < 8; ++i) + if (!c.stays("T3 after its fences, slot live", "T3 freed while its slot was live (control)")) return false; + c.view(nullptr, 2); + } + t.freed = true; + return c.settle("T3 after its release fences", "T3 not freed after its fences") && + c.binds(3, wrapper, false, "case 3: hand copy after the free"); +} + +// 4: a live texture with a hand copy is never freed. +bool case4_live(Context& c) +{ + Res& t = c.make_texture("T4"); + c.view(t.guest.Get(), 4); + c.hand_copy(4, 5); + for (int i = 0; i < 8; ++i) + if (!c.stays("T4 live", "a live texture left the budget")) return false; + return c.binds(5, t.guest.Get(), true, "case 4: hand copy of a live texture"); +} + +} // namespace + +int main(int argc, char** argv) +{ + if (argc != 3 || (std::strcmp(argv[1], "warp") && std::strcmp(argv[1], "hardware")) || + (std::strcmp(argv[2], "on") && std::strcmp(argv[2], "control"))) + return 2; + const bool on = std::strcmp(argv[2], "on") == 0; + char value[2]{}; + const bool switch_on = GetEnvironmentVariableA("X2W_D3D12_INLINE_DESCRIPTORS", value, sizeof(value)) == 1 && value[0] == '1'; + if (switch_on != on) return 2; + ComPtr factory; + if (FAILED(CreateDXGIFactory1(IID_PPV_ARGS(&factory)))) return 3; + const auto adapter = pick_adapter(factory.Get(), std::strcmp(argv[1], "warp") == 0); + if (!adapter) return 77; + ComPtr guest; + ComPtr device; + std::array parameters{}; + if (!require(D3D12XboxCreateDevice(adapter.Get(), parameters.data(), __uuidof(ID3D12Device), + reinterpret_cast(guest.GetAddressOf())), "Xbox device") || + !require(D3D12CreateDevice(adapter.Get(), D3D_FEATURE_LEVEL_12_0, IID_PPV_ARGS(&device)), "desktop device")) + return 3; + DXGI_ADAPTER_DESC1 adapter_desc{}; + adapter->GetDesc1(&adapter_desc); + std::printf("adapter=%ls inline_descriptors=%s\n", adapter_desc.Description, on ? "on" : "off"); + + Context c{guest.Get(), device.Get()}; + try { + c.desc = {D3D12_RESOURCE_DIMENSION_TEXTURE2D, 0, side, side, 1, 1, DXGI_FORMAT_R8G8B8A8_UNORM, {1, 0}, + D3D12_TEXTURE_LAYOUT_UNKNOWN, D3D12_RESOURCE_FLAG_NONE}; + c.texture_bytes = device->GetResourceAllocationInfo(0, 1, &c.desc).SizeInBytes; + c.increment = device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); + c.event = CreateEventW(nullptr, FALSE, FALSE, nullptr); + if (!c.event || c.increment < token_bytes || !c.make_queue(c.direct) || !c.make_queue(c.gated) || !c.make_drain_list()) + return 4; + const struct { + D3D12_DESCRIPTOR_HEAP_DESC desc; + UINT64 backing, bytes; + } request{{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 8, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE}, 0, 0}; + if (!require(invoke(guest.Get(), 14, &request, &__uuidof(ID3D12DescriptorHeap), c.heap.GetAddressOf()), "heap")) + return 4; + c.heap_cpu = invoke(c.heap.Get(), 9); + if (!x2w_d3d12_budget_snapshot(&c.base, sizeof(c.base))) { + std::puts("FAIL: no budget snapshot (X2W_D3D12_BUDGET=1 and X2W_D3D12_RELEASE_RETIRED=1 required)"); + return 4; + } + const void* old_wrapper = nullptr; + if (!case1_stale_copy(c, on, old_wrapper)) return 5; + std::puts(on ? "1 released texture freed at its fences; original and hand copy bind null" + : "1 control: live slot holds the texture, freed after overwrite; hand copy then binds null"); + if (!case2_no_reuse(c, old_wrapper)) return 5; + std::puts("2 64 new textures: no reuse of the freed wrapper address; hand copy still binds null"); + if (!case3_fences(c, on)) return 5; + std::puts("3 nothing freed before the release fences pass"); + if (!case4_live(c)) return 5; + std::puts("4 live texture with a hand copy stays"); + } catch (int code) { + return code; + } + if (FAILED(device->GetDeviceRemovedReason())) return 4; + std::puts(on ? "inline retirement checks passed" : "control: slot-count retirement checks passed"); + return 0; +} diff --git a/tests/startup_resource_retire_title.cpp b/tests/startup_resource_retire_title.cpp index 9645bda5f5..23c4f51952 100644 --- a/tests/startup_resource_retire_title.cpp +++ b/tests/startup_resource_retire_title.cpp @@ -3,7 +3,7 @@ // 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] +// startup_resource_retire_title [off|inline] // // Cases: // 1 slot 133 title_memory texture upload/copy (CopyTextureRegion + CopyResource): held behind closed list and @@ -31,6 +31,8 @@ // with only `this` in rcx. A live wrapper left in the second register must not select the (return buffer, // object) form, which wrote the handle over the heap object; the hidden-pointer form still fills its buffer. // Release builds of case 9 left a resource wrapper there and crashed at the heap's next Release. +// 11 inline mode (X2W_D3D12_INLINE_DESCRIPTORS=1 too; runs only cases 10 and 11): a translated draw through a +// stale descriptor of a released texture records a hold; once freed, the same descriptor binds null. // 9 slot 19-21 fallback (Slice 3a): the same view call in a tracked slot leaves a class texture in the retire class // (a refused view adds no ref, so the released texture retires), while a descriptor in a heap the shim does not // track keeps the retire_leave_class fallback and the texture is not freed. Runs in both modes; without the switch @@ -1013,6 +1015,159 @@ bool case7_draw_samples_slot133_texture(Context& c, void* title_mem) return check_target("readback after the texture left the budget", target_bytes.data(), row_pitch); } +// The case 7 draw (translated pipeline, 4x4 target, one-entry descriptor table) for a texture named by view_cpu. +struct DrawRig { + ComPtr root, pipeline, rtv_heap, views; + ComPtr target; + D3D12_RESOURCE_DESC target_desc{}; + UINT64 rtv = 0, view_cpu = 0, view_gpu = 0; + + bool make(Context& c) + { + if (!prepare_draw_translation(c, root, pipeline)) return false; + 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}; + if (!require(c.device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &target_desc, + D3D12_RESOURCE_STATE_COMMON, nullptr, IID_PPV_ARGS(&target)), + "rig target")) + return false; + const struct { + D3D12_DESCRIPTOR_HEAP_DESC desc; + UINT64 backing, bytes; + } rtv_desc{{D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 1}, 0, 0}, + view_desc{{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 1, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE}, 0, 0}; + if (!require(invoke(c.guest, 14, &rtv_desc, &__uuidof(ID3D12DescriptorHeap), rtv_heap.GetAddressOf()), "rig rtv heap") || + !require(invoke(c.guest, 14, &view_desc, &__uuidof(ID3D12DescriptorHeap), views.GetAddressOf()), "rig view heap")) + return false; + rtv = invoke(rtv_heap.Get(), 9); + invoke(c.guest, 20, target.Get(), static_cast(nullptr), rtv); + view_cpu = invoke(views.Get(), 9); + view_gpu = invoke(views.Get(), 10); + return true; + } + void view(Context& c, IUnknown* resource) const + { + 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, resource, &srv, view_cpu); + } + // Clear, then one draw sampling the table's texture into the covered 3x3 corner; executed and waited for. + // fresh = false records into l as it is (open after reset_list). + bool draw(Context& c, GuestList& l, bool fresh = true) const + { + if (fresh && !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}; + 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); + return c.sync(c.direct); + } +}; + +// 11 (X2W_D3D12_INLINE_DESCRIPTORS, #3429 review): with the switch a descriptor no longer keeps its texture, so a +// translated draw can reach a released texture through a stale descriptor. +// a: released, its release fences held back by a closed gate: the draw samples it and records a retire hold, so the +// drain keeps it after the gate opens until the recording is dropped (removing the hold fails here); the same +// second list drawing it meanwhile takes its own hold, and La reset and recorded again takes a new one; +// b: freed: the same stale descriptor binds null (the covered texels read 0), takes no hold, and nothing faults. +// Not covered: a free between the draw's read of the texture and its hold, which needs a drain on another thread. +bool case11_inline_stale_descriptor_draw(Context& c, void* title_mem) +{ + DrawRig rig; + if (!rig.make(c)) return false; + fill_title_memory(title_mem, draw_seed); + Res& T = c.make_slot133("T_inline", title_mem); + IUnknown* const t_guest = T.guest.Get(); + rig.view(c, t_guest); + + ComPtr gate; + if (!require(invoke(c.guest, 36, UINT64{0}, D3D12_FENCE_FLAG_NONE, &__uuidof(ID3D12Fence), gate.GetAddressOf()), "gate") || + !require(invoke(c.gated.queue.Get(), 17, gate.Get(), UINT64{1}), "gate wait")) + return false; + c.release(T); // the descriptor still names T; with the switch it does not keep it + if (!c.stays("T released behind a closed gate", "T freed before its release fences passed")) return false; + + GuestList La; + if (!rig.draw(c, La)) return false; + RetireProbe held{}; + if (!x2w_d3d12_retire_probe(t_guest, La.list.Get(), &held) || held.list_holds == 0) { + std::printf("FAIL: case 11a: a draw through a stale descriptor recorded no retire hold (list_holds=%u)\n", + held.list_holds); + return false; + } + std::array bytes{}; + UINT row_pitch = 0; + if (!read_target(c, rig.target.Get(), rig.target_desc, bytes.data(), row_pitch) || + !check_target("case 11a: released texture sampled through a stale descriptor", bytes.data(), row_pitch)) + return false; + // A second list drawing T while La holds it takes its own hold: the fast path is per recording, not per texture. + GuestList Lc; + if (!rig.draw(c, Lc)) return false; + RetireProbe other{}; + if (!x2w_d3d12_retire_probe(t_guest, Lc.list.Get(), &other) || other.list_holds == 0) { + std::printf("FAIL: case 11a: a second list drawing a texture another list holds recorded no hold (list_holds=%u)\n", + other.list_holds); + return false; + } + if (!SUCCEEDED(c.reset_list(Lc))) return false; // only La's hold is left + // A reset drops the hold; the same list recording the draw again must take a new one (retire_hold's per-recording + // fast path must not treat the texture as still held by the dropped recording). The gate still holds T. + if (!SUCCEEDED(c.reset_list(La)) || !rig.draw(c, La, false)) return false; + RetireProbe again{}; + if (!x2w_d3d12_retire_probe(t_guest, La.list.Get(), &again) || again.list_holds == 0) { + std::printf("FAIL: case 11a: the same list, drawing again after its reset, recorded no hold (list_holds=%u)\n", + again.list_holds); + return false; + } + if (!require(invoke(gate.Get(), 10, UINT64{1}), "signal gate") || !c.sync(c.gated)) return false; + for (int i = 0; i < 8; ++i) + if (!c.stays("T after its fences, held by the closed draw list", + "T freed while a closed draw recording still named it")) + return false; + if (!SUCCEEDED(c.reset_list(La))) return false; + T.freed = true; + if (!c.settle("T after its draw recording was dropped", "T kept after its draw recording was dropped")) return false; + + GuestList Lb; + if (!rig.draw(c, Lb)) return false; + RetireProbe none{}; + if (!x2w_d3d12_retire_probe(t_guest, Lb.list.Get(), &none) || none.list_holds != 0) { + std::printf("FAIL: case 11b: a draw through the descriptor of a freed texture recorded a hold (list_holds=%u)\n", + none.list_holds); + return false; + } + if (!read_target(c, rig.target.Get(), rig.target_desc, bytes.data(), row_pitch)) return false; + 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.data() + y * row_pitch + x * 4, sizeof(got)); + const std::uint32_t want = x >= draw_covered || y >= draw_covered ? draw_clear_pixel : 0u; + if (got == want) continue; + std::printf("FAIL: case 11b: freed texture: pixel (%u,%u) got %08lx want %08lx (null binding)\n", x, y, + static_cast(got), static_cast(want)); + return false; + } + return SUCCEEDED(c.reset_list(Lb)) && SUCCEEDED(c.device->GetDeviceRemovedReason()); +} + // 8 (Slice 3a, Refs #2379): UAV/RTV/DSV descriptor slots 19-21 hold a retire reference on their resource(s) the way // slot-18 SRVs do. The refs are read through the retire probe: the retire class still excludes render-target, // depth-stencil and unordered-access textures (retire_classify), so no budget column can show the reference yet. A @@ -1222,7 +1377,7 @@ bool case10_heap_start_abi(Context& c) 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"))) + (argc == 3 && std::strcmp(argv[2], "off") && std::strcmp(argv[2], "inline"))) return 2; ComPtr factory; if (FAILED(CreateDXGIFactory1(IID_PPV_ARGS(&factory)))) return 3; @@ -1258,10 +1413,17 @@ int main(int argc, char** argv) 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; + const bool off_mode = argc == 3 && std::strcmp(argv[2], "off") == 0; 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"); + // inline: X2W_D3D12_INLINE_DESCRIPTORS=1 as well; only cases 10 and 11 (cases 1-9 rely on descriptor slots + // keeping their textures, which the switch turns off). + char inline_value[2]{}; + const bool inline_mode = argc == 3 && !off_mode; + if (inline_mode != (GetEnvironmentVariableA("X2W_D3D12_INLINE_DESCRIPTORS", inline_value, sizeof(inline_value)) == 1 && + inline_value[0] == '1')) + return 2; + std::printf("adapter=%ls debug_layer=%s mode=%s\n", adapter_desc.Description, debug ? "enabled" : "off", off_mode ? "off" : inline_mode ? "inline" : "on"); constexpr SIZE_T page = D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT; auto* mem1 = VirtualAlloc(nullptr, page, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); @@ -1295,6 +1457,15 @@ int main(int argc, char** argv) 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 (inline_mode) { + if (!case11_inline_stale_descriptor_draw(c, mem1)) return 5; + std::puts("11 inline descriptors: a draw through a stale descriptor holds a released texture; a freed one binds null"); + const UINT64 inline_errors = debug ? debug->GetNumStoredMessages() : 0; + std::printf("debug_errors_or_warnings=%llu\n", inline_errors); + if (inline_errors || FAILED(device->GetDeviceRemovedReason())) return 4; + std::puts("inline-descriptor draw checks passed"); + return 0; + } 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");