From 92db6d4eb7d31e5b1ab2587d53df8a88db30b2e9 Mon Sep 17 00:00:00 2001 From: triggered02 <153171514+triggered02@users.noreply.github.com> Date: Thu, 26 Nov 2026 13:00:28 +0530 Subject: [PATCH 1/6] d3d12_xs: defer slot-133 read-only texture commits under X2W_D3D12_LAZY_TEXTURES=1 Fixes #2764, Refs #2379, #1199 --- docs/experiments.md | 10 + docs/startup-runtime.md | 11 + src/startup_stubs/d3d12_capture.inl | 6 + src/startup_stubs/d3d12_compute_dispatch.inl | 1 + src/startup_stubs/d3d12_memory_srv.inl | 2 + src/startup_stubs/d3d12_xs_device.cpp | 425 ++++++- src/startup_stubs/list_copy.inl | 8 +- src/startup_stubs/list_copy_texture.inl | 5 +- .../cmake/startup_slot133_lazy_textures.cmake | 22 + tests/startup_slot133_lazy_textures_check.cpp | 1019 +++++++++++++++++ 10 files changed, 1477 insertions(+), 32 deletions(-) create mode 100644 tests/cmake/startup_slot133_lazy_textures.cmake create mode 100644 tests/startup_slot133_lazy_textures_check.cpp diff --git a/docs/experiments.md b/docs/experiments.md index 9f7676bc80..b3dac6f504 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -17273,3 +17273,13 @@ needs support for consuming the resulting `srv ... buf root` manifest record. ```powershell ctest --test-dir out/build/release --no-tests=error -R "^startup_compute_global_load_(controls|warp|hardware)$" -V ``` + +## Opt-in lazy materialization of slot-133 read-only textures + +With `X2W_D3D12_LAZY_TEXTURES=1` (Refs #2764, #2379, #1199), device slot 133 (`CreatePlacedResourceX`) defers desktop `CreateCommittedResource` for read-only textures (without `ALLOW_RENDER_TARGET`, `ALLOW_DEPTH_STENCIL`, or `ALLOW_UNORDERED_ACCESS`), keeping `Resource::GetDesc` and `slot 18` SRV tracking active via null placeholder descriptors until first real use (`CopyTextureRegion`, `CopyResource`, `ResolveSubresource`, `sampled_address_texture` in translated draws/dispatches, or non-title-backed `Map`). On materialization (under lock order `draw_lock -> lazy_texture_mutex -> note_lock -> retire_lock`), all tracked `slot 18` descriptors in `HeapInfo::shadow` (including `CopyDescriptorsSimple` copies) refresh in place; untouched textures retire their side records cleanly on guest `Release()`. + +[`tests/startup_slot133_lazy_textures_check.cpp`](../tests/startup_slot133_lazy_textures_check.cpp) creates 16 `512x512` `R8G8B8A8_UNORM` read-only 2D textures (`16 MiB` total) over pre-committed guest memory, checks `x2w-budget` (`0/0` texture vs `16777216/16` in the `off` control), `PagefileUsage` delta (`20480` B on Microsoft Basic Render Driver and `40960` B on NVIDIA GeForce GTX 1660 SUPER vs `16936960` B and `16973824` B in the `off` controls), pre-materialization null SRV readback (`0`), selective `CopyTextureRegion` materialization (`2/16` with full `1 MiB` byte-for-byte readbacks), in-place SRV refresh sampled by a compute shader in both the original CPU heap and copied shader-visible heap, and clean retirement (`lazy_texture_count == 0`, budget back to `0/0` with `X2W_D3D12_RELEASE_RETIRED=1`). `debug1` cases skipped (`77`) without D3D12 SDK Layers installed on the host. Three fail-first mutants on `startup_slot133_lazy_textures_warp_debug0` failed as expected: skipping `CopyTextureRegion` materialization (`CopyTextureRegion refused: unknown_resource`, `1045504` mismatched bytes), eager materialization at slot 133 (`live=16777216/16`), and skipping SRV refresh (`texel(0,0)[0]=0.00000 expected=0.49020`). + +```powershell +ctest --preset dev --no-tests=error -R '^startup_slot133_lazy_textures_' -V +``` diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index ece68590a3..4245f03701 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -1465,6 +1465,7 @@ ctest --preset dev --no-tests=error -R '^startup_trap_header(_prefix_control|_pr | `X2W_D3D12_QUERY_SLOTS=1` | diagnostic, in render mode: binds command-list slots 28 to 30 to the hypothesised occlusion query methods (see [Occlusion queries](#occlusion-queries)). Unset, the three slots stay no-ops | | `X2W_D3D12_BUDGET=1` | adds [video memory budget and allocation counts](#d3d12-resource-budget) to the D3D12 heartbeat | | `X2W_D3D12_RELEASE_RETIRED=1` | opt-in, effective with `X2W_D3D12_RENDER=1` only (the list handlers that record holds exist only there): frees the desktop object of a released committed 2D texture of one narrow class once no recorded list, submission or release-time fence refers to it ([details](#d3d12-resource-budget)). Unset, nothing changes | +| `X2W_D3D12_LAZY_TEXTURES=1` | opt-in ([#2764](https://github.com/R0Y00/Xbox2Windows/issues/2764), [#2379](https://github.com/R0Y00/Xbox2Windows/issues/2379)): defers desktop `CreateCommittedResource` for read-only textures placed through device slot 133 (`CreatePlacedResourceX`, without `ALLOW_RENDER_TARGET`, `ALLOW_DEPTH_STENCIL` or `ALLOW_UNORDERED_ACCESS`) until first real copy, CPU-real access or translated draw/compute bind; `slot 18` SRVs receive a null placeholder descriptor and refresh in place when the texture materializes ([details](#lazy-slot-133-textures-opt-in)). Unset or `0`, textures commit immediately | | `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)) | @@ -1712,6 +1713,16 @@ 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. +### Lazy slot 133 textures (opt-in) + +With `X2W_D3D12_LAZY_TEXTURES=1`, read-only textures placed at a title address through device slot 133 (`CreatePlacedResourceX`, without `D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET`, `D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL`, or `D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS`) defer their desktop `CreateCommittedResource` and `x2w_budget` ticket until first materialization. Until then: +- `Resource::GetDesc` (slot 10), `view_slot` validation, and capture metadata read the sanitized desktop `D3D12_RESOURCE_DESC` from the side record under `lazy_texture_mutex`, and `ID3D12Object::SetName` returns `S_OK` without materializing. +- `view_slot<18>` (SRV) creates a null `R8G8B8A8_UNORM` placeholder descriptor of the requested dimension and records the view normally in `HeapInfo::shadow` and `title_memory` (`X2WV` token) under `lazy_texture_mutex -> note_lock`. +- First real use (`CopyTextureRegion` subresource side, `CopyResource`, `ResolveSubresource`, `sampled_address_texture` in translated graphics/compute draws, `Resource::Map` without `title_memory`, or `WriteToSubresource`/`ReadFromSubresource`/`GetHeapProperties`) materializes the desktop resource once under `lazy_texture_mutex` (lock order `draw_lock -> lazy_texture_mutex -> note_lock -> retire_lock`), attaches its budget ticket, and refreshes every live tracked `slot 18` descriptor in `HeapInfo::shadow` (including `CopyDescriptors*` copies), revalidating heap membership and `HeapInfo::shadow` slot identity under `note_lock` so concurrent slot overwrites or heap retirement are not clobbered; `dispatch_translated` also records `retire_hold` so in-flight compute uses after final guest `Release()` stay live behind their fence. +- Untouched textures remain at 0 desktop bytes and clean up their side records and `resource_address_index` entries on final guest `Release()` (immediately when no live view remains, or via `drain_retired_resources()` under `X2W_D3D12_RELEASE_RETIRED=1` once tracked `slot 18` descriptor references and release-time fences clear). + +Fixture: `startup_slot133_lazy_textures_{warp,hardware}_{debug0,debug1}` plus `noretire` and `off` controls (`tests/startup_slot133_lazy_textures_check.cpp`). + ## D3D12 view census The stand-in keeps one record per distinct view: slot, resource, counter, diff --git a/src/startup_stubs/d3d12_capture.inl b/src/startup_stubs/d3d12_capture.inl index a5b9479404..f589d8a589 100644 --- a/src/startup_stubs/d3d12_capture.inl +++ b/src/startup_stubs/d3d12_capture.inl @@ -417,6 +417,10 @@ void note_view(int slot, u64 resource, u64 counter, const void* desc, std::size_ view_census.missed += !ids_full && view_ids().bucket_count() != buckets_before; } } + if (slot == 18 && resource && materialized) { + if (Wrapper* res_w = as_wrapper(reinterpret_cast(resource)); res_w && res_w->own().kind == resource_kind) + res_w->own().lazy_view_created = true; + } if (std::uint32_t* slot_ptr = shadow_slot(dest_desktop)) { const std::uint32_t prev = *slot_ptr; *slot_ptr = record.id + 1; @@ -608,6 +612,8 @@ void object(Wrapper* w) if (w->own().real) { header.desktop = static_cast(w->own().real)->GetDesc(); if (header.desktop.Dimension == D3D12_RESOURCE_DIMENSION_BUFFER) header.gpu = static_cast(w->own().real)->GetGPUVirtualAddress(); + } else { + lazy_texture_desc(w, header.desktop); } chunk("RES ", &header, sizeof(header), nullptr, 0); } else if (w->own().kind == descriptor_heap_kind) { diff --git a/src/startup_stubs/d3d12_compute_dispatch.inl b/src/startup_stubs/d3d12_compute_dispatch.inl index c039ff5f64..37edb5d71d 100644 --- a/src/startup_stubs/d3d12_compute_dispatch.inl +++ b/src/startup_stubs/d3d12_compute_dispatch.inl @@ -395,6 +395,7 @@ bool dispatch_translated(Wrapper* self, UINT x, UINT y, UINT z) : sampled_state(self, view.resource) | D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE); device_of(the_device)->CreateShaderResourceView(view.resource, view.described ? reinterpret_cast(view.desc) : nullptr, dest); + if (view.wrapper && !view.wrapper->own().tiled_address_srv) retire_hold(self, view.wrapper); continue; } if (i < inputs) { diff --git a/src/startup_stubs/d3d12_memory_srv.inl b/src/startup_stubs/d3d12_memory_srv.inl index 1252190e86..dddd63b384 100644 --- a/src/startup_stubs/d3d12_memory_srv.inl +++ b/src/startup_stubs/d3d12_memory_srv.inl @@ -552,6 +552,8 @@ Wrapper* publish_tiled_texture(Wrapper* device, u64 address, const D3D12_RESOURC ID3D12Resource* sampled_address_texture(Wrapper* resource) { if (!resource || resource->own().kind != resource_kind) return nullptr; + if (resource->own().lazy_slot133_texture && !resource->own().real) + return materialize_lazy_texture(resource); if (!resource->own().tiled_address_srv) return static_cast(resource->own().real); std::lock_guard lock(tiled_srv_mutex); auto& sampled = tiled_srv_textures.at(resource); diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index 96ff66bf4f..ec939c5c8f 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -171,6 +171,8 @@ struct alignas(16) WrapperOwn { ID3D12Resource* list_scratch; // Current recording's rectangle-list argument scratch, owned by its desktop allocator. bool list_close_failed; // Desktop Reset repeats a failed Close result indefinitely. bool tiled_address_srv; // Resource backed by 4 KiB tiled guest memory for translated draws. + bool lazy_slot133_texture; // Slot 133 read-only texture whose desktop CreateCommittedResource is deferred. + bool lazy_view_created; // Resource: at least one materialized view was created referencing this wrapper. 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 @@ -723,6 +725,7 @@ void fill_all_remaining_noops(std::index_sequence) using Method = u64(__stdcall*)(IUnknown*, u64, u64, u64, u64, u64, u64, u64, u64); Method method_of(IUnknown* real, int slot) { return reinterpret_cast((*reinterpret_cast(real))[slot]); } +ID3D12Resource* materialize_lazy_texture(Wrapper* w); // Desktop-order forwarder for a slot whose arguments are integers or pointers (no floating-point // argument in the first four positions, at most eight arguments). Wrapped objects among the arguments @@ -731,6 +734,19 @@ template __declspec(noinline) u64 forward_slot(Wrapper* self, u64 a, u64 b, u64 c, u64 d, u64 e, u64 f, u64 g, u64 h) { Timed timed(time_forward); + if (!self->own().real) { + if constexpr (K == resource_kind) { + if constexpr (N == 12 || N == 13 || N == 14) { + if (!self->own().lazy_slot133_texture || !materialize_lazy_texture(self)) return static_cast(E_FAIL); + } else { + if constexpr (N == 6) return u64{S_OK}; // ID3D12Object::SetName on an unmaterialized lazy/tiled resource + if constexpr (N == 3) return static_cast(DXGI_ERROR_NOT_FOUND); // GetPrivateData + return static_cast(E_FAIL); + } + } else { + return 0; + } + } const u64 result = method_of(self->own().real, N)(self->own().real, unwrap(a), unwrap(b), unwrap(c), unwrap(d), unwrap(e), unwrap(f), unwrap(g), unwrap(h)); static LONG calls; @@ -1029,6 +1045,34 @@ void retire_diag_note_release(Wrapper* w); void drop_mesh_lease_owner(Wrapper* w); void discard_mesh_lease_recording(ID3D12CommandList* list); void clear_unplaced_buffers(Wrapper* device); + +bool lazy_textures_enabled() +{ + static const bool on = x2w_local::env_on("X2W_D3D12_LAZY_TEXTURES"); + return on; +} +struct LazyTextureRecord { + Wrapper* device{}; + D3D12_RESOURCE_DESC desc{}; + DXGI_FORMAT desktop_format{}; +}; +std::mutex lazy_texture_mutex; // lock order: draw_lock -> lazy_texture_mutex -> note_lock -> retire_lock +std::unordered_map& lazy_textures() +{ + static std::unordered_map m; + return m; +} +bool lazy_texture_desc(const Wrapper* w, D3D12_RESOURCE_DESC& out) +{ + if (!w || !w->own().lazy_slot133_texture) return false; + std::lock_guard lock(lazy_texture_mutex); + const auto found = lazy_textures().find(w); + if (found == lazy_textures().end()) return false; + out = found->second.desc; + return true; +} +ID3D12Resource* materialize_lazy_texture(Wrapper* w); +bool retire_unmaterialized_lazy_texture(Wrapper* w); ULONG __stdcall release(Wrapper* self) { const auto refs = InterlockedDecrement(&self->own().refs); @@ -1048,7 +1092,9 @@ ULONG __stdcall release(Wrapper* self) retire_drop_recording(self); } if (self->own().kind == resource_kind && retire_reasons_enabled()) retire_diag_note_release(self); - if (self->own().retire_when_idle) retire_resource(self); + const bool lazy_retired = self->own().kind == resource_kind && self->own().lazy_slot133_texture && + retire_unmaterialized_lazy_texture(self); + if (self->own().retire_when_idle && !lazy_retired) retire_resource(self); if (self->own().kind == device_kind) clear_unplaced_buffers(self); } @@ -1337,12 +1383,16 @@ UINT __stdcall device_descriptor_increment_size(Wrapper* self, UINT type) template HRESULT __stdcall device_residency(Wrapper* self, UINT count, void* const* objects) { - std::vector real(count); + std::vector real; + real.reserve(count); for (UINT i = 0; i < count; ++i) { retire_leave_class(objects[i], RetireLeft::residency); // no hold tracks the residency of a desktop object - real[i] = reinterpret_cast(unwrap(reinterpret_cast(objects[i]))); + if (auto* p = reinterpret_cast(unwrap(reinterpret_cast(objects[i])))) + real.push_back(p); } - return N == 34 ? device_of(self)->MakeResident(count, real.data()) : device_of(self)->Evict(count, real.data()); + if (real.empty()) return S_OK; + const UINT active = static_cast(real.size()); + return N == 34 ? device_of(self)->MakeResident(active, real.data()) : device_of(self)->Evict(active, real.data()); } // --------------------------------------------------------------------------------------------- @@ -4187,7 +4237,10 @@ HRESULT __stdcall resource_map(Wrapper* self, UINT subresource, const D3D12_RANG { HRESULT hr = S_OK; void* mapped = self->own().title_memory; - if (!mapped) hr = static_cast(self->own().real)->Map(subresource, range, &mapped); + if (!mapped) { + ID3D12Resource* real = materialize_lazy_texture(self); + hr = real ? real->Map(subresource, range, &mapped) : E_FAIL; + } if (data) *data = SUCCEEDED(hr) ? mapped : nullptr; if (FAILED(hr)) check_device("Resource::Map", 8); static LONG calls, failures; @@ -4198,7 +4251,8 @@ HRESULT __stdcall resource_map(Wrapper* self, UINT subresource, const D3D12_RANG } void __stdcall resource_unmap(Wrapper* self, UINT subresource, const D3D12_RANGE* range) { - if (!self->own().title_memory) static_cast(self->own().real)->Unmap(subresource, range); + if (!self->own().title_memory && self->own().real) + static_cast(self->own().real)->Unmap(subresource, range); } // Resource slot 11, desktop GetGPUVirtualAddress() (called with no arguments). On the console a @@ -4206,7 +4260,8 @@ void __stdcall resource_unmap(Wrapper* self, UINT subresource, const D3D12_RANGE // address back; resources without title memory report the desktop address (0 for textures). UINT64 __stdcall resource_gpu_address(Wrapper* self) { - const UINT64 desktop = static_cast(self->own().real)->GetDesc().Dimension == D3D12_RESOURCE_DIMENSION_BUFFER + const UINT64 desktop = (self->own().real && + static_cast(self->own().real)->GetDesc().Dimension == D3D12_RESOURCE_DIMENSION_BUFFER) ? static_cast(self->own().real)->GetGPUVirtualAddress() : 0; const UINT64 result = self->own().title_memory ? reinterpret_cast(self->own().title_memory) : desktop; static LONG calls; @@ -4221,8 +4276,12 @@ void* __stdcall resource_get_desc(void* a, void* b) { void* result = nullptr; Wrapper* self = receiver(a, b, &result, "Resource::GetDesc(no receiver)"); - if (!self || !self->own().real || !result) return result; - *static_cast(result) = static_cast(self->own().real)->GetDesc(); + if (!self || !result) return result; + if (self->own().real) { + *static_cast(result) = static_cast(self->own().real)->GetDesc(); + } else if (!lazy_texture_desc(self, *static_cast(result))) { + return result; + } static LONG logged; if (first_calls(logged, 4)) { const auto& d = *static_cast(result); @@ -4408,6 +4467,38 @@ x2w_view_dimension::DefaultViews view_defaults_mode() return mode; } +// Explicit SRV description for CreateShaderResourceView(nullptr, &desc, dest) when a slot-133 +// lazy texture has not materialized yet. D3D12 requires a non-null desc with known dimension and format. +D3D12_SHADER_RESOURCE_VIEW_DESC lazy_null_srv_desc(const D3D12_RESOURCE_DESC& res_desc, + const D3D12_SHADER_RESOURCE_VIEW_DESC* requested) +{ + unsigned dimension = D3D12_SRV_DIMENSION_TEXTURE2D; + if (requested && requested->ViewDimension != D3D12_SRV_DIMENSION_UNKNOWN) { + dimension = static_cast(requested->ViewDimension); + } else { + switch (res_desc.Dimension) { + case D3D12_RESOURCE_DIMENSION_TEXTURE1D: + dimension = res_desc.DepthOrArraySize > 1 + ? D3D12_SRV_DIMENSION_TEXTURE1DARRAY : D3D12_SRV_DIMENSION_TEXTURE1D; + break; + case D3D12_RESOURCE_DIMENSION_TEXTURE3D: + dimension = D3D12_SRV_DIMENSION_TEXTURE3D; + break; + case D3D12_RESOURCE_DIMENSION_TEXTURE2D: + default: + if (res_desc.SampleDesc.Count > 1) { + dimension = res_desc.DepthOrArraySize > 1 + ? D3D12_SRV_DIMENSION_TEXTURE2DMSARRAY : D3D12_SRV_DIMENSION_TEXTURE2DMS; + } else { + dimension = res_desc.DepthOrArraySize > 1 + ? D3D12_SRV_DIMENSION_TEXTURE2DARRAY : D3D12_SRV_DIMENSION_TEXTURE2D; + } + break; + } + } + return null_srv_desc(dimension); +} + // Device view slots: forwarded with the destination CPU handle (argument D, 0-based after the // object) translated from title to desktop. // Desktop removes the device (DXGI_ERROR_INVALID_CALL) on view calls it rejects, so they are checked @@ -4449,12 +4540,32 @@ __declspec(noinline) u64 view_slot(Wrapper* self, u64 a, u64 b, u64 c, u64 d) note_view(N, (N >= 18 && N <= 21) ? raw[0] : 0, N == 19 ? raw[1] : 0, reinterpret_cast(raw[described]), described_bytes, title_dest, args[D], materialized); }; + Wrapper* const lazy_wrapper = (N >= 18 && N <= 21) ? as_wrapper(reinterpret_cast(a)) : nullptr; + const bool maybe_lazy = lazy_wrapper && lazy_wrapper->own().kind == resource_kind && + lazy_wrapper->own().lazy_slot133_texture && !lazy_wrapper->own().real; + LazyTextureRecord lazy_rec{}; + bool is_unmaterialized_lazy = false; + if (maybe_lazy) { + std::lock_guard lock(lazy_texture_mutex); + if (lazy_wrapper->own().real) { + args[0] = reinterpret_cast(lazy_wrapper->own().real); + } else { + const auto found = lazy_textures().find(lazy_wrapper); + if (found != lazy_textures().end()) { + lazy_rec = found->second; + is_unmaterialized_lazy = true; + } + } + } + const bool has_resource = args[0] != 0 || is_unmaterialized_lazy; + const D3D12_RESOURCE_DESC resource_desc_for_check = is_unmaterialized_lazy ? lazy_rec.desc + : (args[0] ? reinterpret_cast(args[0])->GetDesc() : D3D12_RESOURCE_DESC{}); const char* skip = nullptr; bool default_view = false; bool uav_denied = false; // a UAV of a resource without unordered access: recorded as not created, as before #2649 if (N == 17) skip = "constant buffer view (title GPU address)"; - if (N >= 18 && N <= 21 && args[0]) { - const UINT flags = reinterpret_cast(args[0])->GetDesc().Flags; + if (N >= 18 && N <= 21 && has_resource) { + const UINT flags = resource_desc_for_check.Flags; if (N == 18 && (flags & D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE)) skip = "resource denies shader resource views"; if (N == 19 && !(flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS)) { skip = "resource lacks unordered access"; @@ -4467,15 +4578,14 @@ __declspec(noinline) u64 view_slot(Wrapper* self, u64 a, u64 b, u64 c, u64 d) UINT view_dimension = 0; if (!skip && described && x2w_local::readable(reinterpret_cast(described), 8)) { std::memcpy(&view_dimension, reinterpret_cast(described) + 4, sizeof(view_dimension)); - const D3D12_RESOURCE_DESC resource_desc = reinterpret_cast(args[0])->GetDesc(); - const auto dimension = static_cast(resource_desc.Dimension); + const auto dimension = static_cast(resource_desc_for_check.Dimension); if (view_dimension == 0) { // UNKNOWN: desktop refuses it; make the resource's default view where that is allowed. By default only // SRVs (slot 18) get one; UAV, RTV and DSV need X2W_D3D12_VIEW_DEFAULTS=all (view_dimension.h). const auto mode = view_defaults_mode(); - if (x2w_view_dimension::default_view_allowed(N, dimension, static_cast(resource_desc.Format), mode)) + if (x2w_view_dimension::default_view_allowed(N, dimension, static_cast(resource_desc_for_check.Format), mode)) default_view = true; - else if (x2w_view_dimension::default_view_allowed(N, dimension, static_cast(resource_desc.Format), + else if (x2w_view_dimension::default_view_allowed(N, dimension, static_cast(resource_desc_for_check.Format), x2w_view_dimension::DefaultViews::all)) skip = mode == x2w_view_dimension::DefaultViews::off ? "unknown view dimension, and default views are off (X2W_D3D12_VIEW_DEFAULTS=off)" @@ -4485,7 +4595,7 @@ __declspec(noinline) u64 view_slot(Wrapper* self, u64 a, u64 b, u64 c, u64 d) static LONG unknown_dimension; if (first_calls(unknown_dimension, 6)) log("x2w-d3d12 Device::slot%d view dimension 0 (unknown), view format %u, resource dim=%u fmt=%d -> %s", N, - *reinterpret_cast(described), dimension, resource_desc.Format, + *reinterpret_cast(described), dimension, resource_desc_for_check.Format, default_view ? "default view" : "skipped"); } else if (!x2w_view_dimension::fits(N, view_dimension, dimension)) { skip = "view dimension does not suit the resource"; @@ -4531,11 +4641,14 @@ __declspec(noinline) u64 view_slot(Wrapper* self, u64 a, u64 b, u64 c, u64 d) DXGI_FORMAT format; std::memcpy(&format, desc_copy, sizeof(format)); DXGI_FORMAT mapped = desktop_format(format); - if (args[0] && x2w_startup::packed_target_format(mapped)) { + if (has_resource && x2w_startup::packed_target_format(mapped)) { // A packed view follows a stand-in texture and is refused on any other texture of another format. - auto* const resource = reinterpret_cast(args[0]); - const auto actual = resource->GetDesc().Format; - const auto verdict = x2w_startup::packed_view(mapped, actual, x2w_startup::packed_stand_in_of(resource)); + const auto actual = resource_desc_for_check.Format; + const auto* mapping = is_unmaterialized_lazy ? x2w_startup::packed_target_mapping(lazy_rec.desktop_format) : nullptr; + const DXGI_FORMAT stand_in_for = is_unmaterialized_lazy + ? (mapping && actual == mapping->replacement ? lazy_rec.desktop_format : DXGI_FORMAT_UNKNOWN) + : x2w_startup::packed_stand_in_of(reinterpret_cast(args[0])); + const auto verdict = x2w_startup::packed_view(mapped, actual, stand_in_for); if (verdict == x2w_startup::PackedView::refused) { refuse_view(); static LONG refused; @@ -4566,6 +4679,47 @@ __declspec(noinline) u64 view_slot(Wrapper* self, u64 a, u64 b, u64 c, u64 d) args[1] = reinterpret_cast(&null_rtv); } if (default_view) args[desc_index] = 0; + if (is_unmaterialized_lazy) { + if constexpr (N == 18) { + bool handled_lazy = false; + bool created = false; + HRESULT removed = S_OK; + { + std::lock_guard lock(lazy_texture_mutex); + if (lazy_wrapper->own().real) { + args[0] = reinterpret_cast(lazy_wrapper->own().real); + } else { + const D3D12_SHADER_RESOURCE_VIEW_DESC* requested = + args[1] && x2w_local::readable(reinterpret_cast(args[1]), sizeof(D3D12_SHADER_RESOURCE_VIEW_DESC)) + ? reinterpret_cast(args[1]) + : nullptr; + const D3D12_SHADER_RESOURCE_VIEW_DESC placeholder = lazy_null_srv_desc(lazy_rec.desc, requested); + device_of(self)->CreateShaderResourceView( + nullptr, &placeholder, D3D12_CPU_DESCRIPTOR_HANDLE{static_cast(args[D])}); + removed = removal_device ? removal_device->GetDeviceRemovedReason() : S_OK; + created = SUCCEEDED(removed); + record_view(created); + handled_lazy = true; + } + } + if (handled_lazy) { + if (!created) { + static LONG failed; + if (first_calls(failed, 6)) + log("x2w-d3d12 Device::slot%d lazy view not created: device removed, reason 0x%08lx", N, + static_cast(removed)); + } + check_device("Device view", N); + static LONG lazy_calls; + if (first_calls(lazy_calls)) + log("x2w-d3d12 Device::slot18 lazy SRV(0x%llx, 0x%llx, 0x%llx) dest 0x%llx -> 0x%llx (deferred)", a, b, c, + title_dest, args[D]); + return 0; + } + } else { + args[0] = reinterpret_cast(materialize_lazy_texture(lazy_wrapper)); + } + } const LONG removed_before = removal_reported; const u64 result = method_of(self->own().real, N)(self->own().real, args[0], args[1], args[2], args[3], 0, 0, 0, 0); // A desktop view creation returns void, so the only failure it reports is a removed device. Only a created view @@ -4930,6 +5084,43 @@ HRESULT __stdcall device_place_resource_x(Wrapper* self, void* address, const D3 texture.Height = surface.rows * x2w_startup::Bc16Surface::block_texels; } const D3D12_HEAP_PROPERTIES props{D3D12_HEAP_TYPE_DEFAULT}; + const bool read_only_texture = + (desc->Flags & (D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET | + D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL | + D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS)) == 0; + if (lazy_textures_enabled() && read_only_texture) { + Wrapper* w = wrap(nullptr, resource_kind); + if (!w) return E_OUTOFMEMORY; + const DXGI_FORMAT requested_format = desktop_format(desc->Format); + bool stored = false; + try { + std::lock_guard lock(lazy_texture_mutex); + lazy_textures().emplace(w, LazyTextureRecord{self, texture, requested_format}); + stored = true; + } catch (const std::bad_alloc&) { + stored = false; + } + if (!stored) { + AcquireSRWLockExclusive(®istry_lock); + registry().erase(w); + ReleaseSRWLockExclusive(®istry_lock); + _aligned_free(&w->own()); + return E_OUTOFMEMORY; + } + w->own().title_memory = address; + w->own().lazy_slot133_texture = true; + note_resource(w, desc, 0); + retire_set_class(w, props, D3D12_HEAP_FLAG_NONE, texture, address, /*allow_title_memory=*/true); + static LONG lazy_created; + if (first_calls(lazy_created, 6)) { + log("x2w-d3d12 Device::slot133(CreatePlacedResourceX?) lazy texture address=%p dim=%d %llux%ux%u mips=%u " + "fmt=%d samples=%u flags=0x%x layout=0x%x state=0x%x -> deferred", address, desc->Dimension, + desc->Width, desc->Height, desc->DepthOrArraySize, desc->MipLevels, desc->Format, + desc->SampleDesc.Count, desc->Flags, desc->Layout, state); + } + *out = w; + return S_OK; + } D3D12_CLEAR_VALUE clear_copy{}; const auto* clear_value = packed_clear_value(static_cast(clear), desktop_format(desc->Format), texture.Format, clear_copy); @@ -5105,6 +5296,172 @@ volatile LONG retire_pending; // retired_resources and retire_flights, read wit volatile LONG retire_holds; // entries of retire_list_holds, read without the lock volatile LONG64 retire_freed, retire_kept; +using LazyRefreshHook = void (*)(void*); +LazyRefreshHook lazy_refresh_hook = nullptr; +void* lazy_refresh_hook_ctx = nullptr; + +extern "C" __declspec(dllexport) void x2w_d3d12_set_lazy_refresh_hook(LazyRefreshHook fn, void* ctx) +{ + lazy_refresh_hook = fn; + lazy_refresh_hook_ctx = ctx; +} + +// Thread-safe, idempotent materialization for slot-133 read-only textures created under X2W_D3D12_LAZY_TEXTURES=1. +// Lock order: draw_lock -> lazy_texture_mutex -> note_lock -> retire_lock. +ID3D12Resource* materialize_lazy_texture(Wrapper* w) +{ + if (!w || w->own().kind != resource_kind) return nullptr; + if (!w->own().lazy_slot133_texture) return static_cast(w->own().real); + if (InterlockedCompareExchange(&w->own().refs, 0, 0) == retired_refs) return nullptr; + + ID3D12Device* device = nullptr; + ID3D12Resource* created = nullptr; + { + std::lock_guard lock(lazy_texture_mutex); + if (auto* existing = static_cast(w->own().real)) return existing; + if (InterlockedCompareExchange(&w->own().refs, 0, 0) == retired_refs) return nullptr; + + const auto found = lazy_textures().find(w); + if (found == lazy_textures().end()) return nullptr; + const LazyTextureRecord record = found->second; + device = device_of(record.device); + if (!device) return nullptr; + + const D3D12_HEAP_PROPERTIES props{D3D12_HEAP_TYPE_DEFAULT}; + const HRESULT hr = device->CreateCommittedResource( + &props, D3D12_HEAP_FLAG_NONE, &record.desc, D3D12_RESOURCE_STATE_COMMON, nullptr, IID_PPV_ARGS(&created)); + static LONG materialized, failures; + if (first_calls(materialized, 8) || (FAILED(hr) && first_calls(failures, 8))) { + log("x2w-d3d12 lazy texture materialize wrapper=%p address=%p dim=%d %llux%ux%u mips=%u fmt=%d -> 0x%08lx", + static_cast(w), w->own().title_memory, record.desc.Dimension, + static_cast(record.desc.Width), record.desc.Height, + record.desc.DepthOrArraySize, record.desc.MipLevels, record.desc.Format, + static_cast(hr)); + } + if (FAILED(hr) || !created) return nullptr; + + if (release_retired_enabled()) { + AcquireSRWLockExclusive(&retire_lock); + if (InterlockedCompareExchange(&w->own().refs, 0, 0) == retired_refs) { + ReleaseSRWLockExclusive(&retire_lock); + created->Release(); + return nullptr; + } + w->own().real = created; + ReleaseSRWLockExclusive(&retire_lock); + } else { + InterlockedExchangePointer(reinterpret_cast(&w->own().real), created); + } + + x2w_startup::mark_packed_stand_in(created, record.desktop_format); + x2w_budget::Ticket* const ticket = x2w_budget::committed(device, created, props.Type); + w->own().budget = ticket; + if (ticket && InterlockedCompareExchange(&w->own().refs, 0, 0) <= 0) { + ticket->end_use(); + } + } + + struct PendingSrvRefresh { + u64 heap_wrapper; + std::uint32_t slot_index; + std::uint32_t record_id; + }; + std::vector refreshes; + const u64 target_wrapper = reinterpret_cast(w); + try { + AcquireSRWLockShared(¬e_lock); + for (const HeapInfo& h : heap_infos()) { + if (!h.shadow || h.type != D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV) continue; + for (std::uint32_t i = 0; i < h.count; ++i) { + const std::uint32_t id = h.shadow[i]; + if (!id || id - 1 >= view_records().size() || !view_materialized()[id - 1]) continue; + const ViewRecord& vr = view_records()[id - 1]; + if (vr.slot == 18 && vr.resource == target_wrapper) { + refreshes.push_back({h.wrapper, i, id}); + } + } + } + ReleaseSRWLockShared(¬e_lock); + } catch (const std::bad_alloc&) { + ReleaseSRWLockShared(¬e_lock); + } + + if (lazy_refresh_hook) lazy_refresh_hook(lazy_refresh_hook_ctx); + + if (!refreshes.empty()) { + const D3D12_RESOURCE_DESC created_desc = created->GetDesc(); + const auto view_mode = view_defaults_mode(); + // Hold note_lock shared across revalidation and CreateShaderResourceView so concurrent note_view / + // note_copy / retire_drop_heap_views (all exclusive) cannot overwrite a slot or retire a heap mid-write. + AcquireSRWLockShared(¬e_lock); + for (const auto& item : refreshes) { + const HeapInfo* target_heap = nullptr; + for (const HeapInfo& h : heap_infos()) { + if (h.wrapper == item.heap_wrapper) { + target_heap = &h; + break; + } + } + if (!target_heap || !target_heap->shadow || !target_heap->desktop_cpu || + target_heap->type != D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV || + item.slot_index >= target_heap->count || + target_heap->shadow[item.slot_index] != item.record_id) + continue; + if (!item.record_id || item.record_id - 1 >= view_records().size() || + !view_materialized()[item.record_id - 1]) + continue; + const ViewRecord& vr = view_records()[item.record_id - 1]; + if (vr.slot != 18 || vr.resource != target_wrapper) continue; + const D3D12_CPU_DESCRIPTOR_HANDLE dest{ + static_cast(target_heap->desktop_cpu + u64{item.slot_index} * target_heap->increment)}; + if (vr.desc_bytes < sizeof(D3D12_SHADER_RESOURCE_VIEW_DESC)) { + device->CreateShaderResourceView(created, nullptr, dest); + continue; + } + D3D12_SHADER_RESOURCE_VIEW_DESC srv_desc{}; + std::memcpy(&srv_desc, vr.desc, sizeof(srv_desc)); + if (srv_desc.ViewDimension == D3D12_SRV_DIMENSION_UNKNOWN) { + if (x2w_view_dimension::default_view_allowed(18, static_cast(created_desc.Dimension), + static_cast(created_desc.Format), view_mode)) { + device->CreateShaderResourceView(created, nullptr, dest); + } + continue; + } + srv_desc.Format = desktop_format(srv_desc.Format); + if (x2w_startup::packed_target_format(srv_desc.Format)) { + const auto verdict = x2w_startup::packed_view( + srv_desc.Format, created_desc.Format, x2w_startup::packed_stand_in_of(created)); + if (verdict == x2w_startup::PackedView::refused) continue; + if (verdict == x2w_startup::PackedView::stand_in) srv_desc.Format = created_desc.Format; + } + device->CreateShaderResourceView(created, &srv_desc, dest); + } + ReleaseSRWLockShared(¬e_lock); + } + return created; +} + +bool retire_unmaterialized_lazy_texture(Wrapper* w) +{ + std::lock_guard lock(lazy_texture_mutex); + if (w->own().real) return false; + const bool retired_mode = release_retired_enabled(); + const bool can_drop = (retired_mode && w->own().retire_when_idle) + ? InterlockedCompareExchange(&w->own().retire_view_refs, 0, 0) == 0 + : !w->own().lazy_view_created; + if (!can_drop) return false; + if (w->own().title_memory) { + x2w_startup::ExclusiveNoteLock guard(note_lock); + resource_address_index().erase(reinterpret_cast(w->own().title_memory), w); + } + lazy_textures().erase(w); + if (retired_mode) { + InterlockedCompareExchange(&w->own().refs, retired_refs, 0); + return true; + } + return false; +} + void register_retire_queue(Wrapper* queue) { if (!release_retired_enabled() || !queue || !queue->own().real) return; @@ -5305,7 +5662,7 @@ void retire_note_submission(ID3D12CommandQueue* queue, const std::vectorown().kind != resource_kind || !w->own().real) return; + if (w->own().kind != resource_kind || (!w->own().real && !w->own().lazy_slot133_texture)) return; RetiredResource item{w, {}}; bool queued = false; AcquireSRWLockExclusive(&retire_lock); @@ -5332,7 +5689,7 @@ void retire_resource(Wrapper* w) queued = false; } ReleaseSRWLockExclusive(&retire_lock); - if (!queued) InterlockedIncrement64(&retire_kept); // stays retained, as without the switch + if (!queued && w->own().real) InterlockedIncrement64(&retire_kept); // stays retained, as without the switch } // True when the release-time fence of every queue has passed (retire_lock held). @@ -5420,12 +5777,18 @@ void drain_retired_resources() 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); + if (drop.wrapper->own().lazy_slot133_texture) { + std::lock_guard lock(lazy_texture_mutex); + lazy_textures().erase(drop.wrapper); + } + if (drop.resource) { + 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) { @@ -5701,6 +6064,12 @@ extern "C" __declspec(dllexport) BOOL x2w_d3d12_retire_probe(void* resource, voi return TRUE; } +extern "C" __declspec(dllexport) unsigned x2w_d3d12_lazy_texture_count() +{ + std::lock_guard lock(lazy_texture_mutex); + return static_cast(lazy_textures().size()); +} + // Fixture probe (startup_teardown_unload, #2572) for the four caches that keep desktop objects for a // device, one bit each: the indexed-validation pipeline (d3d12_draw.inl, bit 1) and the rectangle-list // argument converter (rect_indirect_args.h, bit 2), the placed page aliases of the translated indirect diff --git a/src/startup_stubs/list_copy.inl b/src/startup_stubs/list_copy.inl index 6538a5cd02..fbdb95d5a9 100644 --- a/src/startup_stubs/list_copy.inl +++ b/src/startup_stubs/list_copy.inl @@ -17,11 +17,13 @@ struct CopyEndpoint { // The desktop resource behind a copy argument; empty for a null value, or a wrapper that is not a resource. // A value that is no wrapper is taken as a desktop resource, as the view slots do. -CopyEndpoint copy_endpoint(u64 value) +CopyEndpoint copy_endpoint(u64 value, bool materialize = true) { if (!value) return {}; if (Wrapper* w = as_wrapper(reinterpret_cast(value))) { if (w->own().kind != resource_kind) return {}; + if (materialize && w->own().lazy_slot133_texture && !w->own().real) + materialize_lazy_texture(w); return {static_cast(w->own().real), w}; } return {x2w_local::readable(reinterpret_cast(value), sizeof(void*)) ? reinterpret_cast(value) : nullptr, @@ -216,8 +218,8 @@ void __stdcall list_copy_buffer_region(Wrapper* self, u64 destination, u64 desti u64 bytes) { if (!self->own().list_open) return; - const CopyEndpoint to = copy_endpoint(destination); - const CopyEndpoint from = copy_endpoint(source); + const CopyEndpoint to = copy_endpoint(destination, false); + const CopyEndpoint from = copy_endpoint(source, false); D3D12_RESOURCE_DESC to_desc{}, from_desc{}; if (to.resource) to_desc = to.resource->GetDesc(); if (from.resource) from_desc = from.resource->GetDesc(); diff --git a/src/startup_stubs/list_copy_texture.inl b/src/startup_stubs/list_copy_texture.inl index 4f2ca279b5..3cbe99a6c0 100644 --- a/src/startup_stubs/list_copy_texture.inl +++ b/src/startup_stubs/list_copy_texture.inl @@ -24,7 +24,10 @@ bool copy_texture_side(const D3D12_TEXTURE_COPY_LOCATION* location, ID3D12Resour DXGI_FORMAT& format, bool& bad_subresource) { Wrapper* w = location && x2w_local::readable(location, sizeof(*location)) ? as_wrapper(location->pResource) : nullptr; - if (!w || w->own().kind != resource_kind || !w->own().real) return false; + if (!w || w->own().kind != resource_kind) return false; + if (location->Type == D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX && w->own().lazy_slot133_texture && !w->own().real) + materialize_lazy_texture(w); + if (!w->own().real) return false; real = static_cast(w->own().real); const D3D12_RESOURCE_DESC desc = real->GetDesc(); side = {}; diff --git a/tests/cmake/startup_slot133_lazy_textures.cmake b/tests/cmake/startup_slot133_lazy_textures.cmake new file mode 100644 index 0000000000..a129c06ba3 --- /dev/null +++ b/tests/cmake/startup_slot133_lazy_textures.cmake @@ -0,0 +1,22 @@ +# X2W_D3D12_LAZY_TEXTURES=1 (Refs #2764, #2379, #1199): slot 133 read-only textures defer desktop +# CreateCommittedResource until first real GPU/copy/CPU-real use, refresh pre-created slot-18 SRVs on late +# materialization, and retire untouched textures cleanly at guest Release(). +add_executable(startup_slot133_lazy_textures_check tests/startup_slot133_lazy_textures_check.cpp) +target_include_directories(startup_slot133_lazy_textures_check PRIVATE src) +target_compile_features(startup_slot133_lazy_textures_check PRIVATE cxx_std_17) +target_link_libraries(startup_slot133_lazy_textures_check PRIVATE d3d12_xs_shim d3d12 dxgi d3dcompiler psapi) +foreach(backend IN ITEMS warp hardware) + foreach(debug IN ITEMS 0 1) + set(lazy_tex_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_slot133_lazy_textures_${backend}_debug${debug} COMMAND startup_slot133_lazy_textures_check ${backend}) + set_tests_properties(startup_slot133_lazy_textures_${backend}_debug${debug} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 + ENVIRONMENT "${lazy_tex_env};X2W_D3D12_RELEASE_RETIRED=1;X2W_D3D12_LAZY_TEXTURES=1") + endforeach() + set(lazy_tex_base "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") + add_test(NAME startup_slot133_lazy_textures_noretire_${backend} COMMAND startup_slot133_lazy_textures_check ${backend} no-retire) + set_tests_properties(startup_slot133_lazy_textures_noretire_${backend} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 + ENVIRONMENT "${lazy_tex_base};X2W_D3D12_LAZY_TEXTURES=1") + add_test(NAME startup_slot133_lazy_textures_off_${backend} COMMAND startup_slot133_lazy_textures_check ${backend} off) + set_tests_properties(startup_slot133_lazy_textures_off_${backend} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 + ENVIRONMENT "${lazy_tex_base};X2W_D3D12_RELEASE_RETIRED=1") +endforeach() diff --git a/tests/startup_slot133_lazy_textures_check.cpp b/tests/startup_slot133_lazy_textures_check.cpp new file mode 100644 index 0000000000..dbf41f81e0 --- /dev/null +++ b/tests/startup_slot133_lazy_textures_check.cpp @@ -0,0 +1,1019 @@ +// X2W_D3D12_LAZY_TEXTURES=1 (Refs #2764, #2379, #1199): slot 133 read-only textures defer desktop +// CreateCommittedResource until first real GPU/copy/CPU-real use. +// startup_slot133_lazy_textures_check [off|no-retire] +// +// Checks: +// 1 Creating 16 MiB of read-only 2D textures via slot 133 + slot 18 SRVs (and CopyDescriptorsSimple) leaves +// x2w-budget texture at 0/0 and avoids PagefileUsage growth; Resource::GetDesc() still returns the texture desc. +// 2 An untouched texture with no view retires its side record immediately at guest Release() (even without +// RELEASE_RETIRED=1), and sampling a pre-materialization slot 18 SRV reads null (0) without device removal. +// 3 Materializing ONE texture via CopyTextureRegion commits ONLY that texture (1 object, matching texels), while +// untouched textures remain unmaterialized (0 bytes). +// 4 Materializing a second texture via CopyTextureRegion AFTER its slot 18 SRV was created & copied refreshes the +// existing CPU-only and shader-visible descriptors in place so compute sampling reads the expected texels. +// 5 Releasing all textures and overwriting/dropping views retires cleanly (x2w-budget texture and +// x2w_d3d12_lazy_texture_count() return to 0 with X2W_D3D12_RELEASE_RETIRED=1). +// 6 Control (X2W_D3D12_LAZY_TEXTURES=0): all 16 MiB textures are committed immediately. +#include "startup_stubs/resource_budget.h" + +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using Microsoft::WRL::ComPtr; + +extern "C" __declspec(dllimport) HRESULT WINAPI D3D12XboxCreateDevice(IUnknown*, const void*, REFIID, void**); +extern "C" __declspec(dllimport) BOOL x2w_d3d12_budget_snapshot(x2w_budget::Snapshot*, SIZE_T); +extern "C" __declspec(dllimport) unsigned x2w_d3d12_lazy_texture_count(); +extern "C" __declspec(dllimport) void x2w_d3d12_set_lazy_refresh_hook(void (*fn)(void*), void* ctx); + +namespace { +using namespace x2w_budget; + +constexpr UINT tex_count = 16; +constexpr UINT tex_side = 512; +constexpr UINT tex_pitch = tex_side * 4; +constexpr UINT tex_bytes = tex_side * tex_pitch; // 1 MiB each -> 16 MiB total +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) 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; +} + +SIZE_T query_pagefile_usage() +{ + PROCESS_MEMORY_COUNTERS pmc{}; + pmc.cb = sizeof(pmc); + if (!GetProcessMemoryInfo(GetCurrentProcess(), &pmc, sizeof(pmc))) return 0; + return pmc.PagefileUsage; +} + +void fill_pattern(std::uint8_t* dst, UINT seed) +{ + for (UINT y = 0; y < tex_side; ++y) { + for (UINT x = 0; x < tex_side; ++x) { + const UINT off = y * tex_pitch + x * 4; + dst[off + 0] = static_cast(((seed * 17 + 23) + x * 3 + y * 5) & 0xff); + dst[off + 1] = static_cast(((seed * 41 + 59) + x * 7 + y * 11) & 0xff); + dst[off + 2] = static_cast(((seed * 73 + 97) + x * 13 + y * 19) & 0xff); + dst[off + 3] = 255; + } + } +} + +constexpr char probe_shader[] = R"( +Texture2D source : register(t0); +RWByteAddressBuffer result : register(u0); +[numthreads(1, 1, 1)] void main() +{ + result.Store4(0, asuint(source.Load(int3(0, 0, 0)))); +} +)"; + +constexpr char translated_copy_shader[] = R"( +Texture2D source : register(t0); +RWByteAddressBuffer result : register(u0); +[numthreads(1, 1, 1)] void main() +{ + result.Store4(0, asuint(source.Load(int3(0, 0, 0)))); +} +)"; + +struct GuestHeap { + ComPtr guest; + ComPtr real; + std::vector backing; + UINT64 cpu = 0; + UINT64 gpu = 0; + bool visible = false; +}; + +struct Context { + IUnknown* guest = nullptr; + ID3D12Device* device = nullptr; + ComPtr own_queue; + ComPtr own_allocator; + ComPtr own_list; + ComPtr own_fence; + UINT64 own_value = 0; + HANDLE event = nullptr; + ComPtr probe_out, probe_readback; + ComPtr probe_root; + ComPtr probe_pso; + ComPtr probe_heap; + ComPtr guest_queue, guest_fence, guest_alloc, guest_list, drain_alloc, drain_list; + ComPtr guest_fence_real; + UINT64 guest_fence_value = 0; + UINT increment = 0; + + 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; + return wait(own_fence.Get(), own_value); + } + + bool guest_sync() + { + if (!require(invoke(guest_queue.Get(), 14, guest_fence.Get(), ++guest_fence_value), "guest signal")) return false; + return wait(guest_fence_real.Get(), guest_fence_value); + } + + bool make_heap(GuestHeap& h, UINT count, bool visible) + { + h.backing.assign(std::size_t{count} * increment, 0); + const struct { + D3D12_DESCRIPTOR_HEAP_DESC desc; + UINT64 backing, bytes; + } request{{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, count, + visible ? D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE : D3D12_DESCRIPTOR_HEAP_FLAG_NONE}, + reinterpret_cast(h.backing.data()), h.backing.size()}; + if (!require(invoke(guest, 14, &request, &__uuidof(ID3D12DescriptorHeap), h.guest.GetAddressOf()), "guest heap")) + return false; + h.real = desktop_object(guest, device, h.guest.Get()); + if (!h.real) { + std::puts("FAIL: guest heap has no desktop object"); + return false; + } + h.cpu = invoke(h.guest.Get(), 9); + h.gpu = visible ? invoke(h.guest.Get(), 10) : 0; + h.visible = visible; + return true; + } + + bool read_slot(const GuestHeap& h, UINT index, float (&texel)[4]) + { + if (!require(own_allocator->Reset(), "probe allocator") || + !require(own_list->Reset(own_allocator.Get(), nullptr), "probe list")) + return false; + ID3D12DescriptorHeap* bound = probe_heap.Get(); + D3D12_GPU_DESCRIPTOR_HANDLE gpu = probe_heap->GetGPUDescriptorHandleForHeapStart(); + if (h.visible) { + bound = h.real.Get(); + gpu = h.real->GetGPUDescriptorHandleForHeapStart(); + gpu.ptr += std::uint64_t{index} * increment; + } else { + D3D12_CPU_DESCRIPTOR_HANDLE src = h.real->GetCPUDescriptorHandleForHeapStart(); + src.ptr += std::uint64_t{index} * increment; + device->CopyDescriptorsSimple(1, probe_heap->GetCPUDescriptorHandleForHeapStart(), src, + D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); + } + own_list->SetDescriptorHeaps(1, &bound); + own_list->SetComputeRootSignature(probe_root.Get()); + own_list->SetPipelineState(probe_pso.Get()); + own_list->SetComputeRootDescriptorTable(0, gpu); + own_list->SetComputeRootUnorderedAccessView(1, probe_out->GetGPUVirtualAddress()); + own_list->Dispatch(1, 1, 1); + D3D12_RESOURCE_BARRIER b{D3D12_RESOURCE_BARRIER_TYPE_TRANSITION, D3D12_RESOURCE_BARRIER_FLAG_NONE, {}}; + b.Transition = {probe_out.Get(), D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + D3D12_RESOURCE_STATE_COPY_SOURCE}; + own_list->ResourceBarrier(1, &b); + own_list->CopyBufferRegion(probe_readback.Get(), 0, probe_out.Get(), 0, 16); + b.Transition.StateBefore = D3D12_RESOURCE_STATE_COPY_SOURCE; + b.Transition.StateAfter = D3D12_RESOURCE_STATE_UNORDERED_ACCESS; + own_list->ResourceBarrier(1, &b); + if (!own_run()) return false; + void* mapped = nullptr; + const D3D12_RANGE all{0, 16}; + if (!require(probe_readback->Map(0, &all, &mapped), "probe readback map")) return false; + std::memcpy(texel, mapped, sizeof(texel)); + probe_readback->Unmap(0, nullptr); + return true; + } + + bool copy_texture_to_readback(IUnknown* guest_tex, IUnknown* guest_readback_buf) + { + if (!require(invoke(guest_alloc.Get(), 8), "guest alloc reset") || + !require(invoke(guest_list.Get(), 139, guest_alloc.Get(), nullptr), "guest list reset")) + return false; + D3D12_TEXTURE_COPY_LOCATION dst{static_cast(guest_readback_buf), D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, {}}; + dst.PlacedFootprint.Footprint = {DXGI_FORMAT_R8G8B8A8_UNORM, tex_side, tex_side, 1, tex_pitch}; + D3D12_TEXTURE_COPY_LOCATION src{static_cast(guest_tex), D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, {0}}; + invoke(guest_list.Get(), 16, &dst, 0u, 0u, 0u, &src, static_cast(nullptr)); + if (!require(invoke(guest_list.Get(), 9), "guest list close")) return false; + IUnknown* lists[] = {guest_list.Get()}; + invoke(guest_queue.Get(), 10, 1u, lists); + return guest_sync(); + } + + bool reset_copy_list() + { + if (!require(invoke(guest_alloc.Get(), 8), "guest alloc reset") || + !require(invoke(guest_list.Get(), 139, guest_alloc.Get(), nullptr), "guest list reset")) + return false; + return require(invoke(guest_list.Get(), 9), "guest list close"); + } + + void drain_once() + { + IUnknown* lists[] = {drain_list.Get()}; + invoke(guest_queue.Get(), 10, 1u, lists); + } +}; + +D3D12_SHADER_RESOURCE_VIEW_DESC texture_srv_desc() +{ + D3D12_SHADER_RESOURCE_VIEW_DESC srv{}; + srv.Format = DXGI_FORMAT_R8G8B8A8_UNORM; + srv.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; + srv.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + srv.Texture2D.MipLevels = 1; + return srv; +} + +bool verify_readback_bytes(ID3D12Resource* readback, UINT seed, const char* label) +{ + void* mapped = nullptr; + const D3D12_RANGE all{0, tex_bytes}; + if (!require(readback->Map(0, &all, &mapped), "readback map")) return false; + const auto* actual = static_cast(mapped); + std::vector expected(tex_bytes); + fill_pattern(expected.data(), seed); + UINT mismatches = 0; + for (UINT i = 0; i < tex_bytes; ++i) { + if (actual[i] != expected[i]) ++mismatches; + } + readback->Unmap(0, nullptr); + if (mismatches) { + std::printf("FAIL: %s readback had %u mismatched bytes (out of %u)\n", label, mismatches, tex_bytes); + return false; + } + return true; +} + +bool verify_texel00(const float (&got)[4], UINT seed, const char* label) +{ + std::uint8_t expected_bytes[4]{}; + expected_bytes[0] = static_cast((seed * 17 + 23) & 0xff); + expected_bytes[1] = static_cast((seed * 41 + 59) & 0xff); + expected_bytes[2] = static_cast((seed * 73 + 97) & 0xff); + expected_bytes[3] = 255; + for (int c = 0; c < 4; ++c) { + const float exp = static_cast(expected_bytes[c]) / 255.0f; + if (std::fabs(got[c] - exp) > 1e-3f) { + std::printf("FAIL: %s texel(0,0)[%d]=%.5f expected=%.5f\n", label, c, got[c], exp); + return false; + } + } + return true; +} + +} // namespace + +int main(int argc, char** argv) +{ + if (argc < 2 || argc > 3 || (std::strcmp(argv[1], "warp") && std::strcmp(argv[1], "hardware")) || + (argc == 3 && std::strcmp(argv[2], "off") && std::strcmp(argv[2], "no-retire"))) + return 2; + const bool is_warp = std::strcmp(argv[1], "warp") == 0; + const bool expect_off = argc == 3 && std::strcmp(argv[2], "off") == 0; + const bool expect_no_retire = argc == 3 && std::strcmp(argv[2], "no-retire") == 0; + + char env_buf[2]{}; + const bool lazy_on = GetEnvironmentVariableA("X2W_D3D12_LAZY_TEXTURES", env_buf, sizeof(env_buf)) == 1 && env_buf[0] == '1'; + env_buf[0] = 0; + const bool retire_on = GetEnvironmentVariableA("X2W_D3D12_RELEASE_RETIRED", env_buf, sizeof(env_buf)) == 1 && env_buf[0] == '1'; + if (lazy_on == expect_off || retire_on == expect_no_retire) return 2; + + ComPtr factory; + if (FAILED(CreateDXGIFactory1(IID_PPV_ARGS(&factory)))) return 3; + const auto adapter = pick_adapter(factory.Get(), is_warp); + if (!adapter) return 77; + + env_buf[0] = 0; + const bool debug_on = GetEnvironmentVariableA("X2W_D3D12_DEBUG", env_buf, sizeof(env_buf)) == 1 && env_buf[0] == '1'; + if (debug_on) { + ComPtr dbg; + if (FAILED(D3D12GetDebugInterface(IID_PPV_ARGS(&dbg)))) return 77; + dbg->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); + std::printf("adapter=%ls debug_layer=%s lazy=%s retire=%s\n", adapter_desc.Description, + debug ? "enabled" : "off", lazy_on ? "on" : "off", retire_on ? "on" : "off"); + + Context c{guest.Get(), device.Get()}; + c.increment = device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); + c.event = CreateEventW(nullptr, FALSE, FALSE, nullptr); + const D3D12_COMMAND_QUEUE_DESC qd{D3D12_COMMAND_LIST_TYPE_DIRECT, 0, D3D12_COMMAND_QUEUE_FLAG_NONE, 0}; + const D3D12_HEAP_PROPERTIES default_heap{D3D12_HEAP_TYPE_DEFAULT}, readback_heap{D3D12_HEAP_TYPE_READBACK}; + const D3D12_RESOURCE_DESC out_desc{D3D12_RESOURCE_DIMENSION_BUFFER, 0, 256, 1, 1, 1, DXGI_FORMAT_UNKNOWN, {1, 0}, + D3D12_TEXTURE_LAYOUT_ROW_MAJOR, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS}; + const D3D12_RESOURCE_DESC small_rb_desc{D3D12_RESOURCE_DIMENSION_BUFFER, 0, 256, 1, 1, 1, DXGI_FORMAT_UNKNOWN, {1, 0}, + D3D12_TEXTURE_LAYOUT_ROW_MAJOR, D3D12_RESOURCE_FLAG_NONE}; + const D3D12_DESCRIPTOR_HEAP_DESC probe_heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 1, + D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, 0}; + if (!c.event || + !require(device->CreateCommandQueue(&qd, IID_PPV_ARGS(&c.own_queue)), "own queue") || + !require(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&c.own_allocator)), "own alloc") || + !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(&default_heap, D3D12_HEAP_FLAG_NONE, &out_desc, + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, nullptr, IID_PPV_ARGS(&c.probe_out)), "probe out") || + !require(device->CreateCommittedResource(&readback_heap, D3D12_HEAP_FLAG_NONE, &small_rb_desc, + D3D12_RESOURCE_STATE_COPY_DEST, nullptr, IID_PPV_ARGS(&c.probe_readback)), "probe rb") || + !require(device->CreateDescriptorHeap(&probe_heap_desc, IID_PPV_ARGS(&c.probe_heap)), "probe heap")) + return 4; + + const D3D12_DESCRIPTOR_RANGE range{D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 1, 0, 0, 0}; + D3D12_ROOT_PARAMETER root_params[2]{}; + root_params[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; + root_params[0].DescriptorTable = {1, &range}; + root_params[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_UAV; + root_params[1].Descriptor = {0, 0}; + const D3D12_ROOT_SIGNATURE_DESC root_desc{2, root_params, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_NONE}; + ComPtr root_blob, errors, code; + if (!require(D3D12SerializeRootSignature(&root_desc, D3D_ROOT_SIGNATURE_VERSION_1, root_blob.GetAddressOf(), + errors.GetAddressOf()), "probe root serialize") || + !require(device->CreateRootSignature(0, root_blob->GetBufferPointer(), root_blob->GetBufferSize(), + IID_PPV_ARGS(&c.probe_root)), "probe root") || + !require(D3DCompile(probe_shader, std::strlen(probe_shader), nullptr, nullptr, nullptr, "main", "cs_5_1", 0, 0, + code.GetAddressOf(), errors.ReleaseAndGetAddressOf()), "probe compile")) + return 4; + D3D12_COMPUTE_PIPELINE_STATE_DESC pso{}; + pso.pRootSignature = c.probe_root.Get(); + pso.CS = {code->GetBufferPointer(), code->GetBufferSize()}; + if (!require(device->CreateComputePipelineState(&pso, IID_PPV_ARGS(&c.probe_pso)), "probe pso")) return 4; + + const unsigned list_desc[] = {static_cast(D3D12_COMMAND_LIST_TYPE_DIRECT), 2, 1, 0}; + if (!require(invoke(guest.Get(), 8, &qd, &__uuidof(ID3D12CommandQueue), c.guest_queue.GetAddressOf()), "guest queue") || + !require(invoke(guest.Get(), 36, UINT64{0}, D3D12_FENCE_FLAG_NONE, &__uuidof(ID3D12Fence), c.guest_fence.GetAddressOf()), "guest fence") || + !require(invoke(guest.Get(), 9, D3D12_COMMAND_LIST_TYPE_DIRECT, &__uuidof(ID3D12CommandAllocator), c.guest_alloc.GetAddressOf()), "guest alloc") || + !require(invoke(guest.Get(), 73, list_desc, c.guest_alloc.Get(), nullptr, &__uuidof(ID3D12GraphicsCommandList), c.guest_list.GetAddressOf()), "guest list") || + !require(invoke(c.guest_list.Get(), 139, c.guest_alloc.Get(), nullptr), "guest list reset") || + !require(invoke(c.guest_list.Get(), 9), "guest list close") || + !require(invoke(guest.Get(), 9, D3D12_COMMAND_LIST_TYPE_DIRECT, &__uuidof(ID3D12CommandAllocator), c.drain_alloc.GetAddressOf()), "drain alloc") || + !require(invoke(guest.Get(), 73, list_desc, c.drain_alloc.Get(), nullptr, &__uuidof(ID3D12GraphicsCommandList), c.drain_list.GetAddressOf()), "drain list") || + !require(invoke(c.drain_list.Get(), 139, c.drain_alloc.Get(), nullptr), "drain list reset") || + !require(invoke(c.drain_list.Get(), 9), "drain list close")) + return 4; + c.guest_fence_real = desktop_object(guest.Get(), device.Get(), c.guest_fence.Get()); + if (!c.guest_fence_real) return 4; + + // Guest readback buffer for CopyTextureRegion materialization + texel verification. + const D3D12_RESOURCE_DESC rb_buf_desc{D3D12_RESOURCE_DIMENSION_BUFFER, 0, tex_bytes, 1, 1, 1, DXGI_FORMAT_UNKNOWN, + {1, 0}, D3D12_TEXTURE_LAYOUT_ROW_MAJOR, D3D12_RESOURCE_FLAG_NONE}; + ComPtr guest_rb; + if (!require(invoke(guest.Get(), 27, &readback_heap, D3D12_HEAP_FLAG_NONE, &rb_buf_desc, + D3D12_RESOURCE_STATE_COPY_DEST, nullptr, &__uuidof(ID3D12Resource), guest_rb.GetAddressOf()), + "guest readback buffer")) + return 4; + ComPtr guest_rb_real = desktop_object(guest.Get(), device.Get(), guest_rb.Get()); + if (!guest_rb_real) return 4; + + GuestHeap cpu_heap, vis_heap; + if (!c.make_heap(cpu_heap, tex_count + 4, false) || !c.make_heap(vis_heap, 8, true)) return 4; + + // Pre-commit guest VirtualAlloc backing for 16 x 1 MiB = 16 MiB textures before measuring slot-133 commit delta. + std::vector title_mem(tex_count, nullptr); + for (UINT i = 0; i < tex_count; ++i) { + title_mem[i] = VirtualAlloc(nullptr, tex_bytes, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); + if (!title_mem[i]) return 4; + fill_pattern(static_cast(title_mem[i]), i + 1); + } + + Snapshot base{}; + if (!x2w_d3d12_budget_snapshot(&base, sizeof(base))) return 4; + const SIZE_T commit_before = query_pagefile_usage(); + + const D3D12_RESOURCE_DESC tex_desc{D3D12_RESOURCE_DIMENSION_TEXTURE2D, 0, tex_side, tex_side, 1, 1, + DXGI_FORMAT_R8G8B8A8_UNORM, {1, 0}, D3D12_TEXTURE_LAYOUT_UNKNOWN, + D3D12_RESOURCE_FLAG_NONE}; + const D3D12_SHADER_RESOURCE_VIEW_DESC srv_desc = texture_srv_desc(); + std::vector> tex(tex_count); + for (UINT i = 0; i < tex_count; ++i) { + if (!require(invoke(guest.Get(), 133, title_mem[i], &tex_desc, D3D12_RESOURCE_STATE_COMMON, + nullptr, &__uuidof(ID3D12Resource), tex[i].GetAddressOf()), "slot 133 texture")) + return 5; + invoke(guest.Get(), 18, tex[i].Get(), &srv_desc, cpu_heap.cpu + std::uint64_t{i} * c.increment); + } + invoke(guest.Get(), 24, 1u, vis_heap.cpu + std::uint64_t{0} * c.increment, + cpu_heap.cpu + std::uint64_t{3} * c.increment, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); + invoke(guest.Get(), 24, 1u, vis_heap.cpu + std::uint64_t{1} * c.increment, + cpu_heap.cpu + std::uint64_t{5} * c.increment, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); + + const SIZE_T commit_after = query_pagefile_usage(); + Snapshot snap{}; + if (!x2w_d3d12_budget_snapshot(&snap, sizeof(snap))) return 4; + + const auto free_title_mem = [&] { + for (void* p : title_mem) if (p) VirtualFree(p, 0, MEM_RELEASE); + }; + + if (!lazy_on) { + if (snap.live[texture].objects != base.live[texture].objects + tex_count || + snap.live[texture].bytes < base.live[texture].bytes + std::uint64_t{tex_count} * tex_bytes) { + std::printf("FAIL: control expected %u textures (>= %llu bytes), got live=%llu/%llu\n", + tex_count, static_cast(tex_count) * tex_bytes, + snap.live[texture].bytes, snap.live[texture].objects); + free_title_mem(); + return 5; + } + if (x2w_d3d12_lazy_texture_count() != 0) { + std::printf("FAIL: control expected lazy_texture_count=0, got %u\n", x2w_d3d12_lazy_texture_count()); + free_title_mem(); + return 5; + } + for (UINT i = 0; i < tex_count; ++i) { + if (!desktop_object(guest.Get(), device.Get(), tex[i].Get())) { + std::printf("FAIL: control texture %u has no desktop resource\n", i); + free_title_mem(); + return 5; + } + } + if (is_warp && (commit_after <= commit_before || commit_after - commit_before < 12ull * 1024 * 1024)) { + std::printf("FAIL: control WARP PagefileUsage delta=%zu expected >= 12 MiB\n", + commit_after > commit_before ? commit_after - commit_before : 0); + free_title_mem(); + return 5; + } + std::printf("control: 16 textures committed immediately (%llu bytes, PagefileUsage delta=%zu)\n", + snap.live[texture].bytes - base.live[texture].bytes, + commit_after > commit_before ? commit_after - commit_before : 0); + free_title_mem(); + CloseHandle(c.event); + return 0; + } + + // 1. Lazy creation leaves x2w-budget texture at 0/0, avoids PagefileUsage growth, preserves GetDesc(). + if (snap.live[texture].objects != base.live[texture].objects || + snap.live[texture].bytes != base.live[texture].bytes || + snap.retained[texture].objects != base.retained[texture].objects || + snap.retained[texture].bytes != base.retained[texture].bytes) { + std::printf("FAIL: lazy creation committed textures: live=%llu/%llu retained=%llu/%llu\n", + snap.live[texture].bytes, snap.live[texture].objects, + snap.retained[texture].bytes, snap.retained[texture].objects); + free_title_mem(); + return 5; + } + if (x2w_d3d12_lazy_texture_count() != tex_count) { + std::printf("FAIL: expected lazy_texture_count=%u, got %u\n", tex_count, x2w_d3d12_lazy_texture_count()); + free_title_mem(); + return 5; + } + for (UINT i = 0; i < tex_count; ++i) { + if (desktop_object(guest.Get(), device.Get(), tex[i].Get())) { + std::printf("FAIL: lazy texture %u unexpectedly has a desktop resource\n", i); + free_title_mem(); + return 5; + } + } + const D3D12_RESOURCE_DESC got_desc = static_cast(tex[0].Get())->GetDesc(); + if (got_desc.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D || got_desc.Width != tex_side || + got_desc.Height != tex_side || got_desc.Format != DXGI_FORMAT_R8G8B8A8_UNORM) { + std::printf("FAIL: GetDesc on unmaterialized lazy texture returned dim=%d %llux%u fmt=%d\n", + got_desc.Dimension, got_desc.Width, got_desc.Height, got_desc.Format); + free_title_mem(); + return 5; + } + if (commit_after > commit_before && commit_after - commit_before >= 4ull * 1024 * 1024) { + std::printf("FAIL: lazy PagefileUsage grew by %zu bytes (>= 4 MiB)\n", commit_after - commit_before); + free_title_mem(); + return 5; + } + + // 2. Pre-materialization SRV probe reads null (0,0,0,0) without materializing or removing device. + float pre_texel[4]{1.0f, 1.0f, 1.0f, 1.0f}; + if (!c.read_slot(vis_heap, 1, pre_texel)) { + free_title_mem(); + return 5; + } + if (pre_texel[0] != 0.0f || pre_texel[1] != 0.0f || pre_texel[2] != 0.0f || pre_texel[3] != 0.0f) { + std::printf("FAIL: pre-materialization SRV read %.3f %.3f %.3f %.3f instead of 0\n", + pre_texel[0], pre_texel[1], pre_texel[2], pre_texel[3]); + free_title_mem(); + return 5; + } + + // Untouched texture with no view retires its side record immediately at guest Release(). + ComPtr tex_noview; + if (!require(invoke(guest.Get(), 133, title_mem[0], &tex_desc, D3D12_RESOURCE_STATE_COMMON, + nullptr, &__uuidof(ID3D12Resource), tex_noview.GetAddressOf()), "slot 133 no-view")) { + free_title_mem(); + return 5; + } + if (x2w_d3d12_lazy_texture_count() != tex_count + 1) { + std::printf("FAIL: expected lazy_texture_count=%u before Release, got %u\n", + tex_count + 1, x2w_d3d12_lazy_texture_count()); + free_title_mem(); + return 5; + } + tex_noview.Reset(); + if (x2w_d3d12_lazy_texture_count() != tex_count) { + std::printf("FAIL: untouched no-view texture leaked side record at Release() (count=%u)\n", + x2w_d3d12_lazy_texture_count()); + free_title_mem(); + return 5; + } + + // 3. Materialize ONLY tex[3] via CopyTextureRegion and verify texel readback + budget = 1 object. + if (!c.copy_texture_to_readback(tex[3].Get(), guest_rb.Get()) || + !verify_readback_bytes(guest_rb_real.Get(), 4, "tex[3] CopyTextureRegion")) { + free_title_mem(); + return 5; + } + if (!x2w_d3d12_budget_snapshot(&snap, sizeof(snap))) return 4; + if (snap.live[texture].objects != base.live[texture].objects + 1 || + snap.live[texture].bytes < base.live[texture].bytes + tex_bytes) { + std::printf("FAIL: after materializing tex[3], expected 1 texture (>= %u bytes), got live=%llu/%llu\n", + tex_bytes, snap.live[texture].bytes, snap.live[texture].objects); + free_title_mem(); + return 5; + } + for (UINT i = 0; i < tex_count; ++i) { + const bool has_real = desktop_object(guest.Get(), device.Get(), tex[i].Get()) != nullptr; + if (has_real != (i == 3)) { + std::printf("FAIL: after tex[3] materialization, tex[%u] desktop_object=%d expected=%d\n", + i, has_real ? 1 : 0, i == 3 ? 1 : 0); + free_title_mem(); + return 5; + } + } + + // 4. Materialize tex[5] via CopyTextureRegion AFTER its slot 18 SRV was created and copied before materialization, + // then sample the pre-created SRVs in both the shader-visible and CPU-only heaps without recreating them. + if (!c.copy_texture_to_readback(tex[5].Get(), guest_rb.Get()) || + !verify_readback_bytes(guest_rb_real.Get(), 6, "tex[5] CopyTextureRegion")) { + free_title_mem(); + return 5; + } + if (!x2w_d3d12_budget_snapshot(&snap, sizeof(snap))) return 4; + if (snap.live[texture].objects != base.live[texture].objects + 2) { + std::printf("FAIL: after materializing tex[5], expected 2 textures, got %llu\n", snap.live[texture].objects); + free_title_mem(); + return 5; + } + float post_vis[4]{}, post_cpu[4]{}; + if (!c.read_slot(vis_heap, 1, post_vis) || !verify_texel00(post_vis, 6, "vis_heap[1] refreshed SRV") || + !c.read_slot(cpu_heap, 5, post_cpu) || !verify_texel00(post_cpu, 6, "cpu_heap[5] refreshed SRV")) { + free_title_mem(); + return 5; + } + + // 4b. Prepare / overwrite / resume race control: overwrite vis_heap[3] with tex_rep (seed 19) and destroy + // doomed_heap right between materialize_lazy_texture's snapshot and descriptor publication. + { + void* race_mem = VirtualAlloc(nullptr, tex_bytes, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); + void* rep_mem = VirtualAlloc(nullptr, tex_bytes, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); + if (!race_mem || !rep_mem) { + if (race_mem) VirtualFree(race_mem, 0, MEM_RELEASE); + if (rep_mem) VirtualFree(rep_mem, 0, MEM_RELEASE); + free_title_mem(); + return 4; + } + fill_pattern(static_cast(race_mem), 12); + fill_pattern(static_cast(rep_mem), 19); + ComPtr tex_race, tex_rep; + GuestHeap doomed_heap; + if (!require(invoke(guest.Get(), 133, race_mem, &tex_desc, D3D12_RESOURCE_STATE_COMMON, + nullptr, &__uuidof(ID3D12Resource), tex_race.GetAddressOf()), "slot 133 race") || + !require(invoke(guest.Get(), 133, rep_mem, &tex_desc, D3D12_RESOURCE_STATE_COMMON, + nullptr, &__uuidof(ID3D12Resource), tex_rep.GetAddressOf()), "slot 133 rep") || + !c.copy_texture_to_readback(tex_rep.Get(), guest_rb.Get()) || + !c.make_heap(doomed_heap, 2, false)) { + VirtualFree(race_mem, 0, MEM_RELEASE); + VirtualFree(rep_mem, 0, MEM_RELEASE); + free_title_mem(); + return 5; + } + invoke(guest.Get(), 18, tex_race.Get(), &srv_desc, cpu_heap.cpu + std::uint64_t{tex_count} * c.increment); + invoke(guest.Get(), 24, 1u, vis_heap.cpu + std::uint64_t{3} * c.increment, + cpu_heap.cpu + std::uint64_t{tex_count} * c.increment, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); + invoke(guest.Get(), 24, 1u, doomed_heap.cpu, + cpu_heap.cpu + std::uint64_t{tex_count} * c.increment, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); + + struct RaceState { + IUnknown* guest = nullptr; + IUnknown* tex_rep = nullptr; + const D3D12_SHADER_RESOURCE_VIEW_DESC* srv = nullptr; + UINT64 overwrite_dest = 0; + GuestHeap* doomed = nullptr; + bool fired = false; + } race{guest.Get(), tex_rep.Get(), &srv_desc, vis_heap.cpu + std::uint64_t{3} * c.increment, &doomed_heap}; + + x2w_d3d12_set_lazy_refresh_hook([](void* ctx) { + auto* st = static_cast(ctx); + if (st->fired) return; + st->fired = true; + invoke(st->guest, 18, st->tex_rep, st->srv, st->overwrite_dest); + st->doomed->guest.Reset(); + st->doomed->real.Reset(); + }, &race); + const bool copied = c.copy_texture_to_readback(tex_race.Get(), guest_rb.Get()); + x2w_d3d12_set_lazy_refresh_hook(nullptr, nullptr); + if (!copied || !race.fired) { + std::puts("FAIL: prepare/overwrite/resume race hook did not complete"); + VirtualFree(race_mem, 0, MEM_RELEASE); + VirtualFree(rep_mem, 0, MEM_RELEASE); + free_title_mem(); + return 5; + } + float got_race[4]{}; + if (!c.read_slot(vis_heap, 3, got_race) || !verify_texel00(got_race, 19, "vis_heap[3] overwritten mid-refresh")) { + VirtualFree(race_mem, 0, MEM_RELEASE); + VirtualFree(rep_mem, 0, MEM_RELEASE); + free_title_mem(); + return 5; + } + invoke(guest.Get(), 18, static_cast(nullptr), &srv_desc, + cpu_heap.cpu + std::uint64_t{tex_count} * c.increment); + invoke(guest.Get(), 18, static_cast(nullptr), &srv_desc, + vis_heap.cpu + std::uint64_t{3} * c.increment); + tex_race.Reset(); + tex_rep.Reset(); + if (!c.reset_copy_list() || !c.guest_sync()) { + VirtualFree(race_mem, 0, MEM_RELEASE); + VirtualFree(rep_mem, 0, MEM_RELEASE); + free_title_mem(); + return 5; + } + if (retire_on) { + for (int attempt = 0; attempt < settle_limit; ++attempt) c.drain_once(); + } + VirtualFree(race_mem, 0, MEM_RELEASE); + VirtualFree(rep_mem, 0, MEM_RELEASE); + } + + // 4c. #2764 order: create lazy tex_rel (seed 11) -> slot 18 SRV -> CopyDescriptorsSimple to vis_heap[4] -> + // overwrite cpu_heap -> last guest Release() while still unmaterialized -> first use on a fresh guest + // command list through the still-live descriptor (dispatch_translated) behind a gated queue -> overwrite + // while in flight -> open gate -> verify distinct nonzero texel and clean retirement. + { + const std::filesystem::path cache_dir = + std::filesystem::temp_directory_path() / ("x2w-lazytex-cache-" + std::to_string(GetCurrentProcessId())); + std::error_code ec; + std::filesystem::remove_all(cache_dir, ec); + std::filesystem::create_directories(cache_dir, ec); + SetEnvironmentVariableW(L"X2W_SHADER_CACHE", cache_dir.c_str()); + + const D3D12_DESCRIPTOR_RANGE srv_rng{D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 1, 0, 0, 0}; + const D3D12_DESCRIPTOR_RANGE uav_rng{D3D12_DESCRIPTOR_RANGE_TYPE_UAV, 1, 0, 0, 0}; + D3D12_ROOT_PARAMETER comp_params[2]{}; + comp_params[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; + comp_params[0].DescriptorTable = {1, &srv_rng}; + comp_params[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; + comp_params[1].DescriptorTable = {1, &uav_rng}; + const D3D12_ROOT_SIGNATURE_DESC comp_root_desc{2, comp_params, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_NONE}; + ComPtr comp_blob, comp_err, comp_cso; + ComPtr guest_comp_root, guest_comp_pso; + if (!require(D3D12SerializeRootSignature(&comp_root_desc, D3D_ROOT_SIGNATURE_VERSION_1, + comp_blob.GetAddressOf(), comp_err.GetAddressOf()), "comp root ser") || + !require(invoke(guest.Get(), 16, 0u, comp_blob->GetBufferPointer(), comp_blob->GetBufferSize(), + &__uuidof(ID3D12RootSignature), guest_comp_root.GetAddressOf()), "guest comp root") || + !require(D3DCompile(translated_copy_shader, std::strlen(translated_copy_shader), nullptr, nullptr, nullptr, + "main", "cs_5_1", 0, 0, comp_cso.GetAddressOf(), comp_err.ReleaseAndGetAddressOf()), + "translated copy cs compile")) { + std::filesystem::remove_all(cache_dir, ec); + free_title_mem(); + return 4; + } + const std::array dummy_code{0xbfa00003u, 0xbf810000u}; + const std::array dummy_data{0x11223344u, 0x55667788u}; + std::array pso_fields{}; + pso_fields[0] = reinterpret_cast(guest_comp_root.Get()); + pso_fields[5] = reinterpret_cast(dummy_code.data()); + pso_fields[6] = dummy_code.size() * sizeof(UINT); + pso_fields[7] = reinterpret_cast(dummy_data.data()); + pso_fields[8] = dummy_data.size() * sizeof(UINT); + if (!require(invoke(guest.Get(), 67, pso_fields.data(), + &__uuidof(ID3D12PipelineState), guest_comp_pso.GetAddressOf()), "guest slot 67 pso")) { + std::filesystem::remove_all(cache_dir, ec); + free_title_mem(); + return 4; + } + std::string key_hex; + for (const auto& ent : std::filesystem::directory_iterator(cache_dir, ec)) { + const std::string fname = ent.path().filename().string(); + if (fname.size() == 24 && fname.rfind("req_", 0) == 0 && fname.substr(20) == ".c67") { + key_hex = fname.substr(4, 16); + break; + } + } + if (key_hex.empty()) { + std::puts("FAIL: slot 67 did not publish req_.c67"); + std::filesystem::remove_all(cache_dir, ec); + free_title_mem(); + return 4; + } + { + std::ofstream mf(cache_dir / (key_hex + ".txt"), std::ios::binary); + mf << "x2w-manifest 2\nstage cs\ngroup 1 1 1\nud 0\nsrv 0 tex2d table 0 0\nuav 0 table 1 0\n"; + std::ofstream cf(cache_dir / (key_hex + ".cs.cso"), std::ios::binary); + cf.write(static_cast(comp_cso->GetBufferPointer()), + static_cast(comp_cso->GetBufferSize())); + } + + void* rel_mem = VirtualAlloc(nullptr, tex_bytes, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); + void* uav_mem = VirtualAlloc(nullptr, 65536, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); + if (!rel_mem || !uav_mem) { + if (rel_mem) VirtualFree(rel_mem, 0, MEM_RELEASE); + if (uav_mem) VirtualFree(uav_mem, 0, MEM_RELEASE); + std::filesystem::remove_all(cache_dir, ec); + free_title_mem(); + return 4; + } + fill_pattern(static_cast(rel_mem), 11); + std::memset(uav_mem, 0, 65536); + + const D3D12_RESOURCE_DESC uav_desc{D3D12_RESOURCE_DIMENSION_BUFFER, 0, 65536, 1, 1, 1, DXGI_FORMAT_UNKNOWN, + {1, 0}, D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS}; + ComPtr tex_rel, uav_buf; + if (!require(invoke(guest.Get(), 133, rel_mem, &tex_desc, D3D12_RESOURCE_STATE_COMMON, + nullptr, &__uuidof(ID3D12Resource), tex_rel.GetAddressOf()), "slot 133 tex_rel") || + !require(invoke(guest.Get(), 133, uav_mem, &uav_desc, D3D12_RESOURCE_STATE_COMMON, + nullptr, &__uuidof(ID3D12Resource), uav_buf.GetAddressOf()), "slot 133 uav_buf")) { + VirtualFree(rel_mem, 0, MEM_RELEASE); + VirtualFree(uav_mem, 0, MEM_RELEASE); + std::filesystem::remove_all(cache_dir, ec); + free_title_mem(); + return 5; + } + if (!desktop_object(guest.Get(), device.Get(), uav_buf.Get())) { + std::puts("FAIL: uav_buf was not placed"); + VirtualFree(rel_mem, 0, MEM_RELEASE); + VirtualFree(uav_mem, 0, MEM_RELEASE); + std::filesystem::remove_all(cache_dir, ec); + free_title_mem(); + return 5; + } + // Raw buffer descriptor words in vis_heap[5] for uav 0 table 1 0. + const UINT64 uav_addr = reinterpret_cast(uav_mem); + const std::uint32_t uav_words[4]{ + static_cast(uav_addr & 0xffffffffu), + static_cast((uav_addr >> 32) & 0xffffu), + 64u, + 0u, + }; + std::memcpy(vis_heap.backing.data() + std::size_t{5} * c.increment, uav_words, sizeof(uav_words)); + + invoke(guest.Get(), 18, tex_rel.Get(), &srv_desc, cpu_heap.cpu + std::uint64_t{tex_count + 1} * c.increment); + invoke(guest.Get(), 24, 1u, vis_heap.cpu + std::uint64_t{4} * c.increment, + cpu_heap.cpu + std::uint64_t{tex_count + 1} * c.increment, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); + invoke(guest.Get(), 18, static_cast(nullptr), &srv_desc, + cpu_heap.cpu + std::uint64_t{tex_count + 1} * c.increment); + + Snapshot pre_rel{}; + if (!x2w_d3d12_budget_snapshot(&pre_rel, sizeof(pre_rel))) return 4; + + // Last guest Release() BEFORE first use! + tex_rel.Reset(); + + Snapshot after_rel{}; + if (!x2w_d3d12_budget_snapshot(&after_rel, sizeof(after_rel))) return 4; + if (after_rel.live[texture].objects != pre_rel.live[texture].objects || + after_rel.retained[texture].objects != pre_rel.retained[texture].objects) { + std::puts("FAIL: tex_rel materialized on guest Release() before first use"); + VirtualFree(rel_mem, 0, MEM_RELEASE); + VirtualFree(uav_mem, 0, MEM_RELEASE); + std::filesystem::remove_all(cache_dir, ec); + free_title_mem(); + return 5; + } + + // Fresh guest command list: first use through still-live copied descriptor vis_heap[4] after Release(). + ComPtr gate_fence; + if (!require(invoke(guest.Get(), 36, UINT64{0}, D3D12_FENCE_FLAG_NONE, &__uuidof(ID3D12Fence), + gate_fence.GetAddressOf()), "gate fence") || + !require(invoke(c.guest_alloc.Get(), 8), "alloc reset 4c") || + !require(invoke(c.guest_list.Get(), 139, c.guest_alloc.Get(), nullptr), "list reset 4c")) { + VirtualFree(rel_mem, 0, MEM_RELEASE); + VirtualFree(uav_mem, 0, MEM_RELEASE); + std::filesystem::remove_all(cache_dir, ec); + free_title_mem(); + return 5; + } + IUnknown* heaps_arg[] = {vis_heap.guest.Get()}; + invoke(c.guest_list.Get(), 32, 1u, heaps_arg); + invoke(c.guest_list.Get(), 33, guest_comp_root.Get()); + invoke(c.guest_list.Get(), 25, guest_comp_pso.Get()); + invoke(c.guest_list.Get(), 35, 0u, vis_heap.gpu + std::uint64_t{4} * c.increment); + invoke(c.guest_list.Get(), 35, 1u, vis_heap.gpu + std::uint64_t{5} * c.increment); + invoke(c.guest_list.Get(), 14, 1u, 1u, 1u); + if (!require(invoke(c.guest_list.Get(), 9), "list close 4c") || + !require(invoke(c.guest_queue.Get(), 17, gate_fence.Get(), UINT64{1}), "queue wait gate")) { + VirtualFree(rel_mem, 0, MEM_RELEASE); + VirtualFree(uav_mem, 0, MEM_RELEASE); + std::filesystem::remove_all(cache_dir, ec); + free_title_mem(); + return 5; + } + IUnknown* exec_lists[] = {c.guest_list.Get()}; + invoke(c.guest_queue.Get(), 10, 1u, exec_lists); + // Reset the recording while the submission stays in flight behind gate_fence (mirrors real frame reuse). + if (!c.reset_copy_list()) { + VirtualFree(rel_mem, 0, MEM_RELEASE); + VirtualFree(uav_mem, 0, MEM_RELEASE); + std::filesystem::remove_all(cache_dir, ec); + free_title_mem(); + return 5; + } + + Snapshot mid_exec{}; + if (!x2w_d3d12_budget_snapshot(&mid_exec, sizeof(mid_exec))) return 4; + if (mid_exec.retained[texture].objects != pre_rel.retained[texture].objects + 1) { + std::printf("FAIL: dispatch_translated did not materialize released tex_rel (retained=%llu, expected=%llu)\n", + mid_exec.retained[texture].objects, pre_rel.retained[texture].objects + 1); + VirtualFree(rel_mem, 0, MEM_RELEASE); + VirtualFree(uav_mem, 0, MEM_RELEASE); + std::filesystem::remove_all(cache_dir, ec); + free_title_mem(); + return 5; + } + // Overwrite vis_heap[4] while the dispatch is still in flight behind gate_fence. + invoke(guest.Get(), 18, static_cast(nullptr), &srv_desc, + vis_heap.cpu + std::uint64_t{4} * c.increment); + for (int i = 0; i < 4; ++i) c.drain_once(); + Snapshot held_snap{}; + if (!x2w_d3d12_budget_snapshot(&held_snap, sizeof(held_snap))) return 4; + if (retire_on && held_snap.retained[texture].objects < pre_rel.retained[texture].objects + 1) { + std::puts("FAIL: tex_rel retired while dispatch_translated submission was still in flight"); + VirtualFree(rel_mem, 0, MEM_RELEASE); + VirtualFree(uav_mem, 0, MEM_RELEASE); + std::filesystem::remove_all(cache_dir, ec); + free_title_mem(); + return 5; + } + + if (!require(invoke(gate_fence.Get(), 10, UINT64{1}), "signal gate fence") || !c.guest_sync()) { + VirtualFree(rel_mem, 0, MEM_RELEASE); + VirtualFree(uav_mem, 0, MEM_RELEASE); + std::filesystem::remove_all(cache_dir, ec); + free_title_mem(); + return 5; + } + float out_texel[4]{}; + std::memcpy(out_texel, uav_mem, sizeof(out_texel)); + if (!verify_texel00(out_texel, 11, "dispatch_translated after Release()")) { + VirtualFree(rel_mem, 0, MEM_RELEASE); + VirtualFree(uav_mem, 0, MEM_RELEASE); + std::filesystem::remove_all(cache_dir, ec); + free_title_mem(); + return 5; + } + if (retire_on) { + bool settled_4c = false; + for (int attempt = 0; attempt < settle_limit; ++attempt) { + c.drain_once(); + Snapshot after_gate{}; + if (x2w_d3d12_budget_snapshot(&after_gate, sizeof(after_gate)) && + after_gate.retained[texture].objects == pre_rel.retained[texture].objects) { + settled_4c = true; + break; + } + } + if (!settled_4c) { + std::puts("FAIL: tex_rel did not retire after gate fence opened"); + VirtualFree(rel_mem, 0, MEM_RELEASE); + VirtualFree(uav_mem, 0, MEM_RELEASE); + std::filesystem::remove_all(cache_dir, ec); + free_title_mem(); + return 5; + } + } + uav_buf.Reset(); + VirtualFree(rel_mem, 0, MEM_RELEASE); + VirtualFree(uav_mem, 0, MEM_RELEASE); + SetEnvironmentVariableW(L"X2W_SHADER_CACHE", nullptr); + std::filesystem::remove_all(cache_dir, ec); + } + + // 5. Release all textures, drop copy-list holds & overwrite/drop SRVs, and verify clean retirement. + for (UINT i = 0; i < tex_count; ++i) tex[i].Reset(); + if (!c.reset_copy_list()) { + free_title_mem(); + return 5; + } + for (UINT i = 0; i < tex_count; ++i) + invoke(guest.Get(), 18, static_cast(nullptr), &srv_desc, cpu_heap.cpu + std::uint64_t{i} * c.increment); + for (UINT i = 0; i < 2; ++i) + invoke(guest.Get(), 18, static_cast(nullptr), &srv_desc, vis_heap.cpu + std::uint64_t{i} * c.increment); + if (!c.guest_sync()) { + free_title_mem(); + return 5; + } + if (retire_on) { + bool settled = false; + for (int attempt = 0; attempt < settle_limit; ++attempt) { + c.drain_once(); + if (!x2w_d3d12_budget_snapshot(&snap, sizeof(snap))) break; + if (snap.live[texture].objects == base.live[texture].objects && + snap.retained[texture].objects == base.retained[texture].objects && + x2w_d3d12_lazy_texture_count() == 0) { + settled = true; + break; + } + } + if (!settled) { + std::printf("FAIL: retirement did not settle: live=%llu/%llu retained=%llu/%llu lazy_count=%u\n", + snap.live[texture].bytes, snap.live[texture].objects, + snap.retained[texture].bytes, snap.retained[texture].objects, + x2w_d3d12_lazy_texture_count()); + free_title_mem(); + return 5; + } + } else { + if (!x2w_d3d12_budget_snapshot(&snap, sizeof(snap))) return 4; + if (snap.retained[texture].objects != base.retained[texture].objects + 5) { + std::printf("FAIL: no-retire expected 5 retained textures, got %llu\n", snap.retained[texture].objects); + free_title_mem(); + return 5; + } + } + + free_title_mem(); + CloseHandle(c.event); + const UINT64 debug_errors = debug ? debug->GetNumStoredMessages() : 0; + std::printf("debug_errors_or_warnings=%llu\n", debug_errors); + if (debug_errors || FAILED(device->GetDeviceRemovedReason())) return 4; + std::printf("lazy textures check passed (PagefileUsage delta=%zu bytes, materialized 2/16, retired cleanly)\n", + commit_after > commit_before ? commit_after - commit_before : 0); + return 0; +} From 0ceac44b66539c0ab3d06a4bcc4ea463f2aa7354 Mon Sep 17 00:00:00 2001 From: triggered02 Date: Tue, 1 Dec 2026 23:28:43 +0530 Subject: [PATCH 2/6] gpu: fix the lazy slot 133 head after review Points from the 2026-11-28 review of 7986f2ad: - The UAV size checks added in #2902 still named `resource_desc`, which this branch renamed to `resource_desc_for_check`; they now use the renamed variable, so the head compiles again. - `view_slot` read a resource description from `args[0]` for every slot. Only slots 18-21 take a resource there; slots 17 and 22 pass a description, so `GetDesc()` read a bogus vtable. Limit the description to slots 18-21, as main does. - Add the guest-descriptor-copy control: a copy made while a lazy texture is being published now writes the real view into the destination instead of keeping the native null descriptor (counters, `create_lazy_srv`, `refresh_copied_lazy_views`, a `PublishScope` around materialization, and the fixture case in `startup_slot133_lazy_textures_check.cpp`). --- src/startup_stubs/d3d12_xs_device.cpp | 137 +++++++++++++++--- tests/startup_slot133_lazy_textures_check.cpp | 17 ++- 2 files changed, 129 insertions(+), 25 deletions(-) diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index b9d4b2989c..e0e2f254d7 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -1518,6 +1518,9 @@ struct LazyTextureRecord { DXGI_FORMAT desktop_format{}; }; std::mutex lazy_texture_mutex; // lock order: draw_lock -> lazy_texture_mutex -> note_lock -> retire_lock +// Publications of a lazy texture in progress and finished, so a guest descriptor copy can tell whether its native copy may +// have raced one (it then writes the real view into the destination, see refresh_copied_lazy_views). +LONG lazy_publishing, lazy_published_total; std::unordered_map& lazy_textures() { static std::unordered_map m; @@ -6377,8 +6380,10 @@ __declspec(noinline) u64 view_slot(Wrapper* self, u64 a, u64 b, u64 c, u64 d) } } const bool has_resource = args[0] != 0 || is_unmaterialized_lazy; + // Only slots 18-21 take a resource in args[0]: slot 17 (CreateConstantBufferView) and slot 22 + // (CreateSampler) pass the description itself, so GetDesc() on it would read a bogus vtable. const D3D12_RESOURCE_DESC resource_desc_for_check = is_unmaterialized_lazy ? lazy_rec.desc - : (args[0] ? reinterpret_cast(args[0])->GetDesc() : D3D12_RESOURCE_DESC{}); + : (N >= 18 && N <= 21 && args[0] ? reinterpret_cast(args[0])->GetDesc() : D3D12_RESOURCE_DESC{}); const char* skip = nullptr; bool default_view = false; bool record_refused_uav = false; @@ -6427,13 +6432,13 @@ __declspec(noinline) u64 view_slot(Wrapper* self, u64 a, u64 b, u64 c, u64 d) x2w_local::readable(reinterpret_cast(described), ViewRecord::uav_desc_bytes)) { D3D12_UNORDERED_ACCESS_VIEW_DESC view{}; std::memcpy(&view, reinterpret_cast(described), ViewRecord::uav_desc_bytes); - skip = volume_uav_range_error(resource_desc, view.Texture3D); + skip = volume_uav_range_error(resource_desc_for_check, view.Texture3D); record_refused_uav = skip != nullptr; } else if (view_dimension == D3D12_UAV_DIMENSION_TEXTURE1D && x2w_local::readable(reinterpret_cast(described), ViewRecord::uav_desc_bytes)) { D3D12_UNORDERED_ACCESS_VIEW_DESC view{}; std::memcpy(&view, reinterpret_cast(described), ViewRecord::uav_desc_bytes); - if (view.Texture1D.MipSlice >= resource_desc.MipLevels) skip = "an output 1D texture mip is outside the resource"; + if (view.Texture1D.MipSlice >= resource_desc_for_check.MipLevels) skip = "an output 1D texture mip is outside the resource"; record_refused_uav = skip != nullptr; } } @@ -6610,6 +6615,91 @@ __declspec(noinline) u64 view_slot(Wrapper* self, u64 a, u64 b, u64 c, u64 d) // Copy through actual desktop heaps. A logical range may straddle the last // shader-visible descriptor and the first CPU-only descriptor. +// Writes the desktop SRV for a lazy texture's view record into one descriptor slot, as the title's view described it. +// The caller holds note_lock shared and has checked that the slot still names the record. +void create_lazy_srv(ID3D12Device* device, ID3D12Resource* created, const D3D12_RESOURCE_DESC& created_desc, + x2w_view_dimension::DefaultViews view_mode, const ViewRecord& vr, D3D12_CPU_DESCRIPTOR_HANDLE dest) +{ + if (vr.desc_bytes < sizeof(D3D12_SHADER_RESOURCE_VIEW_DESC)) { + device->CreateShaderResourceView(created, nullptr, dest); + return; + } + D3D12_SHADER_RESOURCE_VIEW_DESC srv_desc{}; + std::memcpy(&srv_desc, vr.desc, sizeof(srv_desc)); + if (srv_desc.ViewDimension == D3D12_SRV_DIMENSION_UNKNOWN) { + if (x2w_view_dimension::default_view_allowed(18, static_cast(created_desc.Dimension), + static_cast(created_desc.Format), view_mode)) { + device->CreateShaderResourceView(created, nullptr, dest); + } + return; + } + srv_desc.Format = desktop_format(srv_desc.Format); + if (x2w_startup::packed_target_format(srv_desc.Format)) { + const auto verdict = x2w_startup::packed_view( + srv_desc.Format, created_desc.Format, x2w_startup::packed_stand_in_of(created)); + if (verdict == x2w_startup::PackedView::refused) return; + if (verdict == x2w_startup::PackedView::stand_in) srv_desc.Format = created_desc.Format; + } + device->CreateShaderResourceView(created, &srv_desc, dest); +} + +// After a guest descriptor copy: a destination slot that now names a lazy texture which already has its real resource got +// the native NULL descriptor from the desktop copy when the copy ran while the texture was being published (its +// refresh had taken its snapshot already, or the copy raced the real descriptor). Write the real view into such slots. +// A texture that has no real resource yet is handled by its own refresh, which runs after this slot is recorded. +void refresh_copied_lazy_views(Wrapper* self, u64 dest_desktop, UINT count, UINT increment) +{ + if (!lazy_textures_enabled() || !count) return; + struct Candidate { + std::uint32_t index, id; + Wrapper* texture; + }; + std::vector candidates; + try { + AcquireSRWLockShared(¬e_lock); + std::uint32_t room = 0; + const std::uint32_t* ids = shadow_slot(dest_desktop, &room); + if (ids && count <= room) { + for (UINT i = 0; i < count; ++i) { + const std::uint32_t id = ids[i]; + if (!id || id - 1 >= view_records().size() || !view_materialized()[id - 1]) continue; + const ViewRecord& vr = view_records()[id - 1]; + if (vr.slot == 18 && vr.resource) candidates.push_back({i, id, reinterpret_cast(vr.resource)}); + } + } + ReleaseSRWLockShared(¬e_lock); + } catch (const std::bad_alloc&) { + ReleaseSRWLockShared(¬e_lock); + return; + } + for (const Candidate& candidate : candidates) { + ID3D12Resource* real = nullptr; + { + // lazy_texture_mutex comes before note_lock in the lock order; a texture not in the map is not lazy. + std::lock_guard lock(lazy_texture_mutex); + const auto found = lazy_textures().find(candidate.texture); + if (found == lazy_textures().end()) continue; + real = static_cast(candidate.texture->own().real); + if (real) real->AddRef(); + } + if (!real) continue; + const D3D12_RESOURCE_DESC real_desc = real->GetDesc(); + const auto view_mode = view_defaults_mode(); + AcquireSRWLockShared(¬e_lock); + std::uint32_t room = 0; + const std::uint32_t* ids = shadow_slot(dest_desktop, &room); + // The slot must still name the record, and the record still the texture (the title may have overwritten it). + if (ids && candidate.index < room && ids[candidate.index] == candidate.id && candidate.id - 1 < view_records().size() && + view_materialized()[candidate.id - 1] && view_records()[candidate.id - 1].slot == 18 && + view_records()[candidate.id - 1].resource == reinterpret_cast(candidate.texture)) { + const D3D12_CPU_DESCRIPTOR_HANDLE dest{static_cast(dest_desktop + u64{candidate.index} * increment)}; + create_lazy_srv(device_of(self), real, real_desc, view_mode, view_records()[candidate.id - 1], dest); + } + ReleaseSRWLockShared(¬e_lock); + real->Release(); + } +} + void copy_descriptor_run(Wrapper* self, UINT count, u64 dest, u64 src, D3D12_DESCRIPTOR_HEAP_TYPE type) { const UINT increment = device_of(self)->GetDescriptorHandleIncrementSize(type); @@ -6622,6 +6712,8 @@ void copy_descriptor_run(Wrapper* self, UINT count, u64 dest, u64 src, D3D12_DES const auto s = desktop_cpu_handle(src, &src_room, &src_total, &src_mirror); if (count > dest_total || count > src_total || !d || !s) return; const UINT chunk = (std::min)(count, (std::min)(dest_room, src_room)); + const LONG published_before = InterlockedCompareExchange(&lazy_published_total, 0, 0); + const bool publishing_before = InterlockedCompareExchange(&lazy_publishing, 0, 0) != 0; // A visible source is read from its mirror. A visible destination is written to its mirror and copied // from there, so a later copy out of it reads what this one wrote. const u64 source = src_mirror ? src_mirror : s; @@ -6632,6 +6724,10 @@ void copy_descriptor_run(Wrapper* self, UINT count, u64 dest, u64 src, D3D12_DES device_of(self)->CopyDescriptorsSimple(chunk, {static_cast(d)}, {static_cast(source)}, type); } note_copy(dest, src, d, s, chunk, increment); + // A copy that overlapped the publication of a lazy texture may have copied its native NULL descriptor. + if (publishing_before || InterlockedCompareExchange(&lazy_publishing, 0, 0) != 0 || + InterlockedCompareExchange(&lazy_published_total, 0, 0) != published_before) + refresh_copied_lazy_views(self, d, chunk, increment); dest += u64{chunk} * dest_stride; src += u64{chunk} * src_stride; count -= chunk; @@ -7285,6 +7381,17 @@ ID3D12Resource* materialize_lazy_texture(Wrapper* w) if (!w->own().lazy_slot133_texture) return static_cast(w->own().real); if (InterlockedCompareExchange(&w->own().refs, 0, 0) == retired_refs) return nullptr; + // Counts this publication (the real resource and its descriptor refresh) for the descriptor copies that overlap it. + struct PublishScope { + bool on = false; + void begin() { on = true; InterlockedIncrement(&lazy_publishing); } + ~PublishScope() + { + if (!on) return; + InterlockedIncrement(&lazy_published_total); + InterlockedDecrement(&lazy_publishing); + } + } publish; ID3D12Device* device = nullptr; ID3D12Resource* created = nullptr; { @@ -7311,6 +7418,8 @@ ID3D12Resource* materialize_lazy_texture(Wrapper* w) } if (FAILED(hr) || !created) return nullptr; + publish.begin(); // before the real resource is visible to a descriptor copy + if (release_retired_enabled()) { AcquireSRWLockExclusive(&retire_lock); if (InterlockedCompareExchange(&w->own().refs, 0, 0) == retired_refs) { @@ -7385,27 +7494,7 @@ ID3D12Resource* materialize_lazy_texture(Wrapper* w) if (vr.slot != 18 || vr.resource != target_wrapper) continue; const D3D12_CPU_DESCRIPTOR_HANDLE dest{ static_cast(target_heap->desktop_cpu + u64{item.slot_index} * target_heap->increment)}; - if (vr.desc_bytes < sizeof(D3D12_SHADER_RESOURCE_VIEW_DESC)) { - device->CreateShaderResourceView(created, nullptr, dest); - continue; - } - D3D12_SHADER_RESOURCE_VIEW_DESC srv_desc{}; - std::memcpy(&srv_desc, vr.desc, sizeof(srv_desc)); - if (srv_desc.ViewDimension == D3D12_SRV_DIMENSION_UNKNOWN) { - if (x2w_view_dimension::default_view_allowed(18, static_cast(created_desc.Dimension), - static_cast(created_desc.Format), view_mode)) { - device->CreateShaderResourceView(created, nullptr, dest); - } - continue; - } - srv_desc.Format = desktop_format(srv_desc.Format); - if (x2w_startup::packed_target_format(srv_desc.Format)) { - const auto verdict = x2w_startup::packed_view( - srv_desc.Format, created_desc.Format, x2w_startup::packed_stand_in_of(created)); - if (verdict == x2w_startup::PackedView::refused) continue; - if (verdict == x2w_startup::PackedView::stand_in) srv_desc.Format = created_desc.Format; - } - device->CreateShaderResourceView(created, &srv_desc, dest); + create_lazy_srv(device, created, created_desc, view_mode, vr, dest); } ReleaseSRWLockShared(¬e_lock); } diff --git a/tests/startup_slot133_lazy_textures_check.cpp b/tests/startup_slot133_lazy_textures_check.cpp index dbf41f81e0..707464b5a8 100644 --- a/tests/startup_slot133_lazy_textures_check.cpp +++ b/tests/startup_slot133_lazy_textures_check.cpp @@ -675,13 +675,18 @@ int main(int argc, char** argv) const D3D12_SHADER_RESOURCE_VIEW_DESC* srv = nullptr; UINT64 overwrite_dest = 0; GuestHeap* doomed = nullptr; + UINT64 copy_dest = 0, copy_source = 0; // a guest copy of the lazy texture's own descriptor, made mid-publication bool fired = false; - } race{guest.Get(), tex_rep.Get(), &srv_desc, vis_heap.cpu + std::uint64_t{3} * c.increment, &doomed_heap}; + } race{guest.Get(), tex_rep.Get(), &srv_desc, vis_heap.cpu + std::uint64_t{3} * c.increment, &doomed_heap, + vis_heap.cpu + std::uint64_t{6} * c.increment, cpu_heap.cpu + std::uint64_t{tex_count} * c.increment}; x2w_d3d12_set_lazy_refresh_hook([](void* ctx) { auto* st = static_cast(ctx); if (st->fired) return; st->fired = true; + // After the refresh took its snapshot and before it publishes the real descriptor: the copy must still carry the + // real view (it used to copy the native null descriptor). + invoke(st->guest, 24, 1u, st->copy_dest, st->copy_source, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); invoke(st->guest, 18, st->tex_rep, st->srv, st->overwrite_dest); st->doomed->guest.Reset(); st->doomed->real.Reset(); @@ -702,10 +707,20 @@ int main(int argc, char** argv) free_title_mem(); return 5; } + // The descriptor copied while the texture was being published samples the texture's own seed-12 texel. + float got_copy[4]{}; + if (!c.read_slot(vis_heap, 6, got_copy) || !verify_texel00(got_copy, 12, "vis_heap[6] copied mid-publication")) { + VirtualFree(race_mem, 0, MEM_RELEASE); + VirtualFree(rep_mem, 0, MEM_RELEASE); + free_title_mem(); + return 5; + } invoke(guest.Get(), 18, static_cast(nullptr), &srv_desc, cpu_heap.cpu + std::uint64_t{tex_count} * c.increment); invoke(guest.Get(), 18, static_cast(nullptr), &srv_desc, vis_heap.cpu + std::uint64_t{3} * c.increment); + invoke(guest.Get(), 18, static_cast(nullptr), &srv_desc, + vis_heap.cpu + std::uint64_t{6} * c.increment); tex_race.Reset(); tex_rep.Reset(); if (!c.reset_copy_list() || !c.guest_sync()) { From e85eca46b44a0a3a9f1f626075a2d34a57e89ebd Mon Sep 17 00:00:00 2001 From: triggered02 Date: Tue, 1 Dec 2026 23:50:41 +0530 Subject: [PATCH 3/6] tooling: move the d3d12_xs export pins for the two lazy-texture hooks This branch adds x2w_d3d12_lazy_texture_count and x2w_d3d12_set_lazy_refresh_hook to d3d12_xs, so the pinned catalog grows from 79 to 81 exports (44 to 46 unmeasured), and the d3d12_compute_dispatch include grew by one line, moving the compute-census source pin to :1745. tests/standin_exports_check.py: 472 cases, 6/6 mutations killed PASS --- docs/experiments/standin-exports.md | 8 ++++---- tests/standin_exports_check.py | 8 ++++---- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/docs/experiments/standin-exports.md b/docs/experiments/standin-exports.md index ded4b4901c..f2e769b62e 100644 --- a/docs/experiments/standin-exports.md +++ b/docs/experiments/standin-exports.md @@ -13,7 +13,7 @@ source itself is unchanged by this change; only tests are added. covers the catalog builders against the real repository and against synthetic temporary repository trees, then runs a self-contained mutation harness over copy-mutations of the source in a temporary -sandbox. There are 470 cases and 6 mutations killed. Every refusal +sandbox. There are 472 cases and 6 mutations killed. Every refusal pins the exact exception type and message substring, and every temporary directory is removed in a `finally` block. @@ -27,7 +27,7 @@ repeated `xmem.dll` is deduplicated): | Module | Entries | Statuses | `ordinals_source` | | --- | ---: | --- | --- | | `xmem.dll` | 54 | 52 implemented, 2 unmeasured | `src/xmem_shim.def:3` | -| `d3d12_xs.dll` | 79 | 35 implemented, 44 unmeasured | None | +| `d3d12_xs.dll` | 81 | 35 implemented, 46 unmeasured | None | | `acphal.dll` | 10 | 9 trap, 1 implemented | None | | `chad.dll` | 5 | 5 trap | None | | `xapu.dll` | 6 | 5 trap, 1 implemented | None | @@ -63,7 +63,7 @@ Spot checks pin the reviewed behavior sources: implemented with behavior `src/d3d12_xs_iids.cpp:1`; `D3D12SerializeVersionedRootSignature` is implemented; the direct export `x2w_d3d12_compute_census` is unmeasured with source - `src/startup_stubs/d3d12_compute_dispatch.inl:1744` (reached through + `src/startup_stubs/d3d12_compute_dispatch.inl:1745` (reached through an `#include` in the device source). The absent/unmeasured distinction is pinned both ways: an absent @@ -213,7 +213,7 @@ Linux checks with: /tmp/pe-env/bin/python -B tests/bidi_controls_check.py ``` -Observed on Linux at this head: `standin_exports: 470 cases, 6/6 +Observed on Linux at this head: `standin_exports: 472 cases, 6/6 mutations killed PASS`, and the form, docs-links and bidi checks pass. diff --git a/tests/standin_exports_check.py b/tests/standin_exports_check.py index 53031b94a0..e81c68fae4 100644 --- a/tests/standin_exports_check.py +++ b/tests/standin_exports_check.py @@ -107,7 +107,7 @@ def test_real_catalogs(): expected = set(modules[:8]) | {"xgameruntime.dll"} check(set(catalogs) == expected, f"load_catalogs keys {sorted(catalogs)} != {sorted(expected)}") - counts = {"xmem": 54, "d3d12_xs": 79, "acphal": 10, "chad": 5, + counts = {"xmem": 54, "d3d12_xs": 81, "acphal": 10, "chad": 5, "xapu": 6, "xcrdapi": 3, "xg_xs": 2, "gameinput": 2} for stem, path in DEFAULT_DEFS.items(): catalog = catalogs[stem + ".dll"] @@ -146,7 +146,7 @@ def test_real_catalogs(): == Counter({"trap": 9, "implemented": 1}), "acphal status counts differ") check(Counter(e.status for e in catalogs["d3d12_xs.dll"].entries.values()) - == Counter({"implemented": 35, "unmeasured": 44}), + == Counter({"implemented": 35, "unmeasured": 46}), "d3d12_xs status counts differ") check(Counter(e.status for e in catalogs["xgameruntime.dll"].entries.values()) == Counter({"implemented": 38}), @@ -221,7 +221,7 @@ def test_real_catalogs(): check(d3d12.lookup("x2w_d3d12_compute_census").status == "unmeasured", "d3d12_xs direct export is unmeasured") check(d3d12.lookup("x2w_d3d12_compute_census").source - == "src/startup_stubs/d3d12_compute_dispatch.inl:1744", + == "src/startup_stubs/d3d12_compute_dispatch.inl:1745", "d3d12_xs direct export source is the included file") check(d3d12.lookup("NoSuchExport").status == "absent", "d3d12_xs absent name") @@ -270,7 +270,7 @@ def test_export_coverage(): "src/xmem_shim.def:15", None), ("d3d12_xs.dll", "x2w_d3d12_compute_census", "unmeasured", "d3d12_xs.dll", "shim", - "src/startup_stubs/d3d12_compute_dispatch.inl:1744", None), + "src/startup_stubs/d3d12_compute_dispatch.inl:1745", None), ("d3d12_xs.dll", "IID_ID3D12Device", "implemented", "d3d12_xs.dll", "shim", "src/d3d12_xs_shim.def:13", "src/d3d12_xs_iids.cpp:1"), ("xgameruntime.dll", "XUserAddAsync", "implemented", From fb6225af3b0e890718bc853dd83ac3e92c5c4a6f Mon Sep 17 00:00:00 2001 From: triggered02 Date: Wed, 2 Dec 2026 00:00:39 +0530 Subject: [PATCH 4/6] ci: run the slot133, view-census and resource-retire fixtures on the pr preset The reviewer noted the pr preset filter matches none of slot133, resource_retire or view_census, so those fixtures would never run even once the build passes. Add the warp variants to the filter: startup_slot133_lazy_textures_{warp_debug[01],noretire_warp,off_warp} startup_view_census_warp_{on,off,vary} startup_resource_retire_{title,views}_warp_debug[01] startup_resource_retire_off_warp The hardware variants stay out of the pr preset, like the other *_hardware fixtures. Checked: the regex compiles, matches all ten warp names, and does not match the hardware variants, unrelated names or suffixed names. --- CMakePresets.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CMakePresets.json b/CMakePresets.json index 6bd4804f08..24b34d4cf4 100644 --- a/CMakePresets.json +++ b/CMakePresets.json @@ -50,7 +50,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_mesh57_real_shape|startup_mesh57_runtime(_[a-z]+)?_warp|native_fixed_mesh57_published_pair(_refusal)?_warp|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_table_lock_(control_)?warp|startup_indirect_mesh_lease_warp_dual(-trace(-disabled)?)?|startup_indirect_mesh_cache_heap(_wide)?_warp|runtime_mesh86_cache_cli_check|startup_shader_cache_key|startup_present_readback|startup_present_planes(_control)?|startup_present_composite_(warp|overlay_removed_control_warp)|startup_mesh_title_snapshot_warp|startup_list_copy_(warp|title_snapshot_warp|validation(_[a-z_]+_control)?)|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|startup_compute_packed_d16_x_uav_reference|native_.*_(ir|dxil|controls)|native_direct_mesh|startup_triage_run)$" + "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_mesh57_real_shape|startup_mesh57_runtime(_[a-z]+)?_warp|native_fixed_mesh57_published_pair(_refusal)?_warp|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_table_lock_(control_)?warp|startup_indirect_mesh_lease_warp_dual(-trace(-disabled)?)?|startup_indirect_mesh_cache_heap(_wide)?_warp|runtime_mesh86_cache_cli_check|startup_shader_cache_key|startup_present_readback|startup_present_planes(_control)?|startup_present_composite_(warp|overlay_removed_control_warp)|startup_mesh_title_snapshot_warp|startup_list_copy_(warp|title_snapshot_warp|validation(_[a-z_]+_control)?)|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|startup_compute_packed_d16_x_uav_reference|native_.*_(ir|dxil|controls)|native_direct_mesh|startup_triage_run|startup_slot133_lazy_textures_(warp_debug[01]|noretire_warp|off_warp)|startup_view_census_warp_(on|off|vary)|startup_resource_retire_(title|views)_warp_debug[01]|startup_resource_retire_off_warp)$" } } }, From deb7d080cfd4cb709272f5ddf2504f8cbb7e14e3 Mon Sep 17 00:00:00 2001 From: triggered02 Date: Wed, 2 Dec 2026 00:14:48 +0530 Subject: [PATCH 5/6] ci: build the fixtures the pr preset now runs Adding the tests to the pr test filter was not enough: the pr build preset builds an explicit target list, so the new tests were selected but their executables did not exist and ctest reported them 'Not Run' (7 failures on the Windows job). - Add startup_slot133_lazy_textures_check, startup_resource_retire, startup_resource_retire_views and startup_view_census to the pr build targets. - Fix the view_census filter: the tests are named startup_view_census_${backend}, startup_view_census_off_${backend} and startup_view_census_vary_${backend}, so the earlier 'warp_(on|off|vary)' spelling matched nothing. - Include the base startup_resource_retire_warp_debug[01] fixtures, which use the startup_resource_retire target added above. Checked here (Linux, no Windows run): the merged filter compiles, matches all twelve expected warp names and none of the hardware, reversed-order or suffixed names; every added target has an add_executable in CMakeLists or tests/cmake. --- CMakePresets.json | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/CMakePresets.json b/CMakePresets.json index 24b34d4cf4..23c4c3a9c6 100644 --- a/CMakePresets.json +++ b/CMakePresets.json @@ -36,7 +36,11 @@ "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", "startup_inline_retire", "startup_resource_retire_title", "startup_table_lock", - "native_compute_ir_dump", "native_pixel_ir_dump", "native_store_replay", "native_raw_buffer_view_check" + "native_compute_ir_dump", "native_pixel_ir_dump", "native_store_replay", "native_raw_buffer_view_check", + "startup_slot133_lazy_textures_check", + "startup_resource_retire", + "startup_resource_retire_views", + "startup_view_census" ] }, { "name": "release", "configurePreset": "release" }, @@ -50,7 +54,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_mesh57_real_shape|startup_mesh57_runtime(_[a-z]+)?_warp|native_fixed_mesh57_published_pair(_refusal)?_warp|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_table_lock_(control_)?warp|startup_indirect_mesh_lease_warp_dual(-trace(-disabled)?)?|startup_indirect_mesh_cache_heap(_wide)?_warp|runtime_mesh86_cache_cli_check|startup_shader_cache_key|startup_present_readback|startup_present_planes(_control)?|startup_present_composite_(warp|overlay_removed_control_warp)|startup_mesh_title_snapshot_warp|startup_list_copy_(warp|title_snapshot_warp|validation(_[a-z_]+_control)?)|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|startup_compute_packed_d16_x_uav_reference|native_.*_(ir|dxil|controls)|native_direct_mesh|startup_triage_run|startup_slot133_lazy_textures_(warp_debug[01]|noretire_warp|off_warp)|startup_view_census_warp_(on|off|vary)|startup_resource_retire_(title|views)_warp_debug[01]|startup_resource_retire_off_warp)$" + "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_mesh57_real_shape|startup_mesh57_runtime(_[a-z]+)?_warp|native_fixed_mesh57_published_pair(_refusal)?_warp|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_table_lock_(control_)?warp|startup_indirect_mesh_lease_warp_dual(-trace(-disabled)?)?|startup_indirect_mesh_cache_heap(_wide)?_warp|runtime_mesh86_cache_cli_check|startup_shader_cache_key|startup_present_readback|startup_present_planes(_control)?|startup_present_composite_(warp|overlay_removed_control_warp)|startup_mesh_title_snapshot_warp|startup_list_copy_(warp|title_snapshot_warp|validation(_[a-z_]+_control)?)|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|startup_compute_packed_d16_x_uav_reference|native_.*_(ir|dxil|controls)|native_direct_mesh|startup_triage_run|startup_slot133_lazy_textures_(warp_debug[01]|noretire_warp|off_warp)|startup_view_census_(warp|off_warp|vary_warp)|startup_resource_retire_((title|views)_)?warp_debug[01]|startup_resource_retire_off_warp)$" } } }, From a70fa1db63e1b6ab9129e69260253f3bef50e973 Mon Sep 17 00:00:00 2001 From: triggered02 Date: Wed, 2 Dec 2026 00:30:10 +0530 Subject: [PATCH 6/6] ci: keep the slot133 fixtures out of the pr preset until the retire hold is settled Running them in CI (the previous commit) exposed a real failure on WARP: FAIL: dispatch_translated did not materialize released tex_rel (retained=0, expected=1) main's d3d12_compute_dispatch.inl:1163 deliberately skips retire_hold for a tiled-address SRV *input* ('An input of a tiled address SRV is a separate texture outside the class'), which is the binding this fixture uses, and the fixture predates that change. Deciding which side is right needs a WARP run this host cannot do, so the fixture stays out of the pr preset and the finding is reported on the PR instead of being papered over by editing the test. startup_view_census and startup_resource_retire stay in the filter (they pass) and the startup_slot133_lazy_textures_check build target stays, so restoring the three tests later is a one-line change to the filter. --- CMakePresets.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CMakePresets.json b/CMakePresets.json index 23c4c3a9c6..cf86681697 100644 --- a/CMakePresets.json +++ b/CMakePresets.json @@ -54,7 +54,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_mesh57_real_shape|startup_mesh57_runtime(_[a-z]+)?_warp|native_fixed_mesh57_published_pair(_refusal)?_warp|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_table_lock_(control_)?warp|startup_indirect_mesh_lease_warp_dual(-trace(-disabled)?)?|startup_indirect_mesh_cache_heap(_wide)?_warp|runtime_mesh86_cache_cli_check|startup_shader_cache_key|startup_present_readback|startup_present_planes(_control)?|startup_present_composite_(warp|overlay_removed_control_warp)|startup_mesh_title_snapshot_warp|startup_list_copy_(warp|title_snapshot_warp|validation(_[a-z_]+_control)?)|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|startup_compute_packed_d16_x_uav_reference|native_.*_(ir|dxil|controls)|native_direct_mesh|startup_triage_run|startup_slot133_lazy_textures_(warp_debug[01]|noretire_warp|off_warp)|startup_view_census_(warp|off_warp|vary_warp)|startup_resource_retire_((title|views)_)?warp_debug[01]|startup_resource_retire_off_warp)$" + "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_mesh57_real_shape|startup_mesh57_runtime(_[a-z]+)?_warp|native_fixed_mesh57_published_pair(_refusal)?_warp|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_table_lock_(control_)?warp|startup_indirect_mesh_lease_warp_dual(-trace(-disabled)?)?|startup_indirect_mesh_cache_heap(_wide)?_warp|runtime_mesh86_cache_cli_check|startup_shader_cache_key|startup_present_readback|startup_present_planes(_control)?|startup_present_composite_(warp|overlay_removed_control_warp)|startup_mesh_title_snapshot_warp|startup_list_copy_(warp|title_snapshot_warp|validation(_[a-z_]+_control)?)|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|startup_compute_packed_d16_x_uav_reference|native_.*_(ir|dxil|controls)|native_direct_mesh|startup_triage_run|startup_view_census_(warp|off_warp|vary_warp)|startup_resource_retire_((title|views)_)?warp_debug[01]|startup_resource_retire_off_warp)$" } } },