Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions CMakePresets.json
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@
"xmem_run_break_readers_check", "xmem_run_break_readers_control", "xmem_cross_call_merge_check",
"xmem_placeholder_split_check", "xmem_map_split_first_check", "startup_dstorage_break_window_check",
"xmem_page_runs_device_check", "linear_buffer_backing_check",
"bcpack_formats_check", "startup_stub_consumer"
"bcpack_formats_check", "startup_stub_consumer", "startup_inline_retire", "startup_resource_retire_title"
]
},
{ "name": "release", "configurePreset": "release" },
Expand All @@ -48,7 +48,7 @@
"displayName": "Windows pull request smoke tests",
"filter": {
"include": {
"name": "^(bcpack_all_formats(_golden_control)?|startup_bcpack_storage|desktop_root_signature|era_heap_(allocation|failure)|xmem_shim_mapped_pages|cpu_aot_fuzz_smoke|cpu_archive_texture_gpu_warp|dual_uav_warp|spirv_.*_warp|static_exe_intake|descriptor_heap_paging(_swapped)?_warp|startup_launch|startup_tools_lint|startup_gfx2hlsl_cvt_off_f32_i4_controls|startup_gfx2hlsl_sad_hi_msad_controls|startup_indirect_(dispatch|count_split|draw(_indexed)?|mesh(_xmem_arguments(_skip_wait)?)?|counts_control)_warp|startup_indirect_mesh_lease_warp_dual(-trace(-disabled)?)?|startup_shader_cache_key|startup_present_readback|xmem_(run_break_readers|cross_call_merge|placeholder_split|map_split_first)(_[a-z_]+)?|startup_dstorage_break_window(_[a-z_]+)?|xmem_page_runs_device(_join)?_warp|linear_buffer_backing_share_warp|startup_stage_package)$"
"name": "^(bcpack_all_formats(_golden_control)?|startup_bcpack_storage|desktop_root_signature|era_heap_(allocation|failure)|xmem_shim_mapped_pages|cpu_aot_fuzz_smoke|cpu_archive_texture_gpu_warp|dual_uav_warp|spirv_.*_warp|static_exe_intake|descriptor_heap_paging(_swapped)?_warp|startup_launch|startup_tools_lint|startup_gfx2hlsl_cvt_off_f32_i4_controls|startup_gfx2hlsl_sad_hi_msad_controls|startup_indirect_(dispatch|count_split|draw(_indexed)?|mesh(_xmem_arguments(_skip_wait)?)?|counts_control)_warp|startup_indirect_(dispatch|constants|count)_inline_warp|startup_inline_retire_(on|control)_warp|startup_resource_retire_title_inline_warp_debug0|startup_indirect_mesh_lease_warp_dual(-trace(-disabled)?)?|startup_shader_cache_key|startup_present_readback|xmem_(run_break_readers|cross_call_merge|placeholder_split|map_split_first)(_[a-z_]+)?|startup_dstorage_break_window(_[a-z_]+)?|xmem_page_runs_device(_join)?_warp|linear_buffer_backing_share_warp|startup_stage_package)$"
}
}
},
Expand Down
31 changes: 31 additions & 0 deletions docs/startup-runtime.md
Original file line number Diff line number Diff line change
Expand Up @@ -1661,6 +1661,7 @@ ctest --preset dev --no-tests=error -R '^startup_hook_(window|overlap)$' -V
| `X2W_D3D12_QUERY_SLOTS=1` | diagnostic, in render mode: binds command-list slots 28 to 30 to the confirmed `BeginQuery`, `EndQuery` and `ResolveQueryData` methods (see [Occlusion queries](#occlusion-queries)). The bindings remain diagnostic because the forwarding behavior is not a console runtime oracle. Unset, the three slots stay no-ops |
| `X2W_D3D12_BUDGET=1` | adds [video memory budget and allocation counts](#d3d12-resource-budget) to the D3D12 heartbeat |
| `X2W_D3D12_RELEASE_RETIRED=1` | opt-in, effective with `X2W_D3D12_RENDER=1` only (the list handlers that record holds exist only there): frees the desktop object of a released committed 2D texture of one narrow class once no recorded list, submission or release-time fence refers to it ([details](#d3d12-resource-budget)). Unset, nothing changes |
| `X2W_D3D12_INLINE_DESCRIPTORS=1` | opt-in: leaves byte +0x18 of the guest device at 0, so the title writes constant buffer views and copies CBV/SRV/UAV descriptors itself instead of calling device slots 17 and 24 (sampler copies still arrive through slot 24); with `X2W_D3D12_RELEASE_RETIRED=1`, a retired resource is then freed once its release fences pass ([details](#d3d12-inline-descriptors)). Unset, nothing changes |
| `X2W_D3D12_RELEASE_RETIRED_VIEWS=1` | legacy diagnostic. Logs that clearing live slots is disabled and enables the existing retirement breakdown when base retirement and budgets are on ([details](#d3d12-resource-budget)) |
| `X2W_D3D12_RETIRE_REASONS=1` | diagnostic only, effective with `X2W_D3D12_RELEASE_RETIRED=1` and `X2W_D3D12_BUDGET=1`: adds one `x2w-retire held:` line to the heartbeat that counts final-released resources whose desktop object is still alive, by reason ([details](#d3d12-resource-budget)). Unset, nothing is recorded |
| `X2W_D3D12_VIEW_DEFAULTS=all` or `=off` | `all` is experimental: UAV, RTV and DSV descriptions with `ViewDimension` 0 also get the resource's default view, which drops their requested format and component mapping. `off` skips the measured SRV case too. Unset, only SRVs of typed non-depth textures get the default view ([details](#unknown-and-mismatched-view-dimensions)) |
Expand Down Expand Up @@ -1940,6 +1941,36 @@ FALSE without the switch, like `x2w_d3d12_budget_snapshot`. `startup_resource_re
runs the same steps without the switch. The hardware cases report 77 without a
physical adapter, and the debug-layer cases report 77 where the debug layer is not installed.

## D3D12 inline descriptors

The guest device ABI checks byte +0x18 of the device before it writes descriptors itself. The stand-in sets it
(#3211), so the title calls device slot 17 for every constant buffer view and slot 24 for every
`CopyDescriptorsSimple`, and the stand-in records each of them. `X2W_D3D12_INLINE_DESCRIPTORS=1` leaves the byte at
0:

- Slot 17 calls stop, and slot 24 calls for CBV/SRV/UAV heaps stop; sampler copies still arrive through slot 24.
Constant buffer views in title descriptor memory are then hardware buffer
descriptors, which the draw and compute buffer readers already decode (the branch of `indirect_table_buffer` for
words that are not a view token). Texture views are still created through slot 18, so their tokens still name
view records; a copy of one is a plain copy of the token.
- With `X2W_D3D12_RELEASE_RETIRED=1`, `retire_view_refs` no longer sees every descriptor that names a resource,
because copies made in title memory are not counted. A retired resource is then freed once its release fences
pass and no recorded list or submission holds it: as in D3D12, the application keeps a resource alive while its
descriptors are in use. Wrappers are never freed, so a token that names a freed resource still finds the dead
wrapper (no desktop object) and binds null; a wrapper address is never reused for another resource.
- A draw, mesh or compute call that reads a texture through a descriptor takes the list's retire hold before its
first use of it, under `retire_lock`. If the drain already freed it, the call binds null (draw) or refuses
(mesh, compute) and the case is logged as `x2w-d3d12 retire: N reads found their texture already freed; bound
null`. A repeated hold by the same recording skips the lock (a per-recording stamp on the resource).
- Fixtures: `startup_resource_retire_title_inline_{warp,hardware}_debug{0,1}` (case 11: a translated draw through a
stale descriptor holds a released texture, also from a second list and after its own list's reset, and binds null
once it is freed), `startup_inline_retire_{on,control}_{warp,hardware}` (a texture view, a 32-byte copy made with
`memcpy`, release, fences, `x2w_d3d12_token_texture` for what a draw would bind, 64 new textures for address reuse)
and `startup_indirect_{dispatch,constants,count}_inline_{warp,hardware}` (byte +0x18 stays 0; the indirect dispatch
cases pass).

Unset, the byte is set and retirement waits for `retire_view_refs` as before.

## D3D12 view allocation failure

A new view record goes into three containers: the record vector, the vector of
Expand Down
5 changes: 4 additions & 1 deletion src/startup_stubs/d3d12_compute_dispatch.inl
Original file line number Diff line number Diff line change
Expand Up @@ -686,8 +686,11 @@ const char* record_translated_dispatch(Wrapper* self, const TranslatedDispatch&
ReleaseSRWLockShared(&note_lock);
}
Wrapper* const wrapper = known ? as_wrapper(reinterpret_cast<const void*>(record.resource)) : nullptr;
ID3D12Resource* const texture = !wrapper || wrapper->own().kind != resource_kind ? nullptr
ID3D12Resource* texture = !wrapper || wrapper->own().kind != resource_kind ? nullptr
: output ? static_cast<ID3D12Resource*>(wrapper->own().real) : sampled_address_texture(wrapper);
// Hold before the first use: the drain can free a retired texture that descriptors still name. An output
// is the wrapper's own object; an input of a tiled address SRV is a separate texture outside the class.
if (texture && (output || !wrapper->own().tiled_address_srv) && !retire_hold(self, wrapper)) texture = nullptr;
const D3D12_RESOURCE_DESC resource = texture ? texture->GetDesc() : D3D12_RESOURCE_DESC{};
if (!output) {
D3D12_SHADER_RESOURCE_VIEW_DESC desc{};
Expand Down
7 changes: 3 additions & 4 deletions src/startup_stubs/d3d12_draw.inl
Original file line number Diff line number Diff line change
Expand Up @@ -3112,6 +3112,8 @@ bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UI
desc.Texture2D.MipLevels = 1; // shared MostDetailedMip and MipLevels in all supported texture views
if (srv.kind == 2) desc.Texture2DArray.ArraySize = 1;
ID3D12Resource* texture = sampled_address_texture(resource);
// Hold before the first use: the drain can free a retired texture that descriptors still name.
if (texture && !resource->own().tiled_address_srv && !retire_hold(self, resource)) texture = nullptr;
if (texture && record.desc_bytes >= 40) {
std::memcpy(&desc, record.desc, 40);
desc.Format = desktop_format(desc.Format);
Expand Down Expand Up @@ -3149,10 +3151,7 @@ bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UI
return false;
}
if (texture && !upload_texture(self, resource, texture)) texture = nullptr;
if (texture) {
require_state(self, texture, sampled_state(self, texture));
if (resource && !resource->own().tiled_address_srv) retire_hold(self, resource);
}
if (texture) require_state(self, texture, sampled_state(self, texture));
const bool had_texture = texture != nullptr;
bool mismatched = false;
static LONG shown;
Expand Down
80 changes: 71 additions & 9 deletions src/startup_stubs/d3d12_xs_device.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -202,6 +202,10 @@ struct alignas(16) WrapperOwn {
std::uint8_t retire_never; // RetireNever of this resource (set only with X2W_D3D12_RELEASE_RETIRED)
std::uint8_t retire_left; // RetireLeft: the first use that took it out of the class
volatile LONG retire_view_refs; // Live tracked slot-18 SRV descriptor slots referencing this resource.
// retire_hold fast path: a list's current hold set has a stamp (never reused, 0 = none), and a resource carries
// the stamp of the last set that held it, so a repeated hold by the same recording skips the lock and the search.
u64 retire_hold_stamp; // CommandList: stamp of its current retire_list_holds entry
volatile LONG64 retire_held_stamp; // Resource: stamp of the last hold set that took it
bool retire_has_written_gen; // Whether written_textures()[title_memory].generation was snapshotted at Release.
u64 retire_written_gen; // Snapshotted written_textures() generation for stale-entry cleanup.
volatile LONG64 output_trace_recording;
Expand Down Expand Up @@ -495,6 +499,22 @@ u64 unwrap(u64 value)
volatile LONG wraps_to_fail; // fixture-only, set by x2w_d3d12_fail_wraps
constexpr u64 out_of_memory = static_cast<std::uint32_t>(E_OUTOFMEMORY); // for slots that return u64

// X2W_D3D12_INLINE_DESCRIPTORS=1 (opt-in, docs/startup-runtime.md#d3d12-inline-descriptors): wrap() leaves device byte
// +0x18 at 0, so the title writes CBVs and copies CBV/SRV/UAV descriptors itself (no slot 17, no slot 24 for them). The
// retire drain cannot count those copies, so a retired resource is freed once its release fences pass: D3D12 leaves
// descriptor lifetime to the application. Wrappers are never freed, so a stale token still names the dead wrapper
// (real == null) and binds null.
bool inline_descriptors_on()
{
static const bool on = [] {
const bool value = x2w_local::env_on("X2W_D3D12_INLINE_DESCRIPTORS");
if (value) log("x2w-d3d12 X2W_D3D12_INLINE_DESCRIPTORS=1: device byte +0x18 left 0 (title writes CBVs and copies descriptors "
"inline; retired resources freed at their fences)");
return value;
}();
return on;
}

// Returns nullptr when the wrapper cannot be allocated or registered (#2653). The caller still owns
// `real` then: it releases what it created and returns E_OUTOFMEMORY.
Wrapper* wrap(IUnknown* real, Kind kind)
Expand All @@ -517,7 +537,7 @@ Wrapper* wrap(IUnknown* real, Kind kind)
// The guest checks device byte +0x18 before using its inline descriptor
// writers. Request vtable calls so the shim records the descriptor.
static_assert(offsetof(Wrapper, console_fields) + 2 * sizeof(u64) == 0x18);
if (kind == device_kind) w->console_fields[2] = 1;
if (kind == device_kind && !inline_descriptors_on()) w->console_fields[2] = 1;
if (kind == fence_kind && real) w->own().completed = static_cast<LONG64>(static_cast<ID3D12Fence*>(real)->GetCompletedValue());
AcquireSRWLockExclusive(&registry_lock);
try {
Expand Down Expand Up @@ -1050,7 +1070,7 @@ void retire_add_view_ref(const void* object);
void retire_release_view_ref(const void* object);
void retire_drop_heap_views(Wrapper* heap);
void retire_note_title_release(Wrapper* w);
void retire_hold(Wrapper* list, Wrapper* resource);
bool retire_hold(Wrapper* list, Wrapper* resource);
void retire_drop_recording(Wrapper* list);
void release_list_recording(Wrapper* list);
void clear_draw_sampler_snapshot(Wrapper* self);
Expand Down Expand Up @@ -6001,7 +6021,7 @@ std::vector<RetireFlight> retire_flights;
std::unordered_map<Wrapper*, std::vector<ID3D12Resource*>> retire_list_holds; // one desktop reference per entry
volatile LONG retire_pending; // retired_resources and retire_flights, read without the lock
volatile LONG retire_holds; // entries of retire_list_holds, read without the lock
volatile LONG64 retire_freed, retire_kept;
volatile LONG64 retire_freed, retire_kept, retire_hold_late;

void register_retire_queue(Wrapper* queue)
{
Expand Down Expand Up @@ -6105,15 +6125,30 @@ void retire_note_title_release(Wrapper* w)
// After a copy, texture copy or resolve was forwarded to the desktop list: the list keeps a desktop reference to the
// resource until its recording is dropped. Only wrappers are members of the class, so a raw desktop pointer is never
// held. Assumption, not proven: the guest has no raw pointer to the desktop object of a class member.
void retire_hold(Wrapper* list, Wrapper* resource)
{
if (!resource || !resource->own().retire_when_idle) return;
// A draw, mesh or compute read reaches a texture through a descriptor, which with X2W_D3D12_INLINE_DESCRIPTORS no
// longer keeps it: the caller takes the hold before its first use of the texture and binds nothing on false, which
// means the drain has already claimed the desktop object (own().real cleared).
bool retire_hold(Wrapper* list, Wrapper* resource)
{
if (!resource || !resource->own().retire_when_idle) return true;
// Already held by this recording: its holds are dropped only by retire_discard_holds of this list, on the thread
// that records it, and a stamp is never reused, so the desktop object the caller read is still referenced.
const u64 stamp = list->own().retire_hold_stamp;
if (stamp && static_cast<u64>(InterlockedCompareExchange64(&resource->own().retire_held_stamp, 0, 0)) == stamp)
return true;
bool held = false;
AcquireSRWLockExclusive(&retire_lock);
// own().real is cleared by drain_retired_resources under this lock, so the read and the AddRef happen under it
// (retire_lock is a leaf: nothing else is taken inside).
auto* real = static_cast<ID3D12Resource*>(resource->own().real);
if (real) {
if (!real) {
ReleaseSRWLockExclusive(&retire_lock);
const LONG64 late = InterlockedIncrement64(&retire_hold_late);
if (late <= 8 || late % 1000 == 0)
log("x2w-d3d12 retire: %lld reads found their texture already freed; bound null", late);
return false;
}
{
try {
auto& held_by_list = retire_list_holds[list];
if (std::find(held_by_list.begin(), held_by_list.end(), real) != held_by_list.end()) {
Expand All @@ -6125,6 +6160,9 @@ void retire_hold(Wrapper* list, Wrapper* resource)
InterlockedIncrement(&retire_holds);
held = true;
}
static u64 next_stamp; // under retire_lock
if (!list->own().retire_hold_stamp) list->own().retire_hold_stamp = ++next_stamp;
InterlockedExchange64(&resource->own().retire_held_stamp, static_cast<LONG64>(list->own().retire_hold_stamp));
} catch (const std::bad_alloc&) {
}
}
Expand All @@ -6136,10 +6174,12 @@ void retire_hold(Wrapper* list, Wrapper* resource)
resource->own().retire_hold_missed = true;
}
ReleaseSRWLockExclusive(&retire_lock);
return true;
}

void retire_discard_holds(Wrapper* list)
{
list->own().retire_hold_stamp = 0; // the next hold opens a new set; resources stamped with the old one miss
if (!InterlockedCompareExchange(&retire_holds, 0, 0)) return;
std::vector<ID3D12Resource*> dropped;
AcquireSRWLockExclusive(&retire_lock);
Expand Down Expand Up @@ -6272,7 +6312,7 @@ void drain_retired_resources()
InterlockedDecrement(&retire_pending);
continue;
}
if (InterlockedCompareExchange(&w->own().retire_view_refs, 0, 0) > 0) {
if (!inline_descriptors_on() && InterlockedCompareExchange(&w->own().retire_view_refs, 0, 0) > 0) {
++i;
continue;
}
Expand Down Expand Up @@ -6460,7 +6500,8 @@ void retire_reasons_collect(RetireReasonReport& report)
why = held_never[w->own().retire_never];
} else if (found == queued.end()) {
why = Held::unqueued;
} else if (InterlockedCompareExchange(&w->own().retire_view_refs, 0, 0) > 0) {
} else if (!inline_descriptors_on() && InterlockedCompareExchange(&w->own().retire_view_refs, 0, 0) > 0) {
// the drain waits on view refs only without X2W_D3D12_INLINE_DESCRIPTORS
why = Held::view_refs;
if (const auto view = viewed.find(w); view != viewed.end() && view->second) {
++report.visible_count;
Expand Down Expand Up @@ -6583,6 +6624,27 @@ extern "C" __declspec(dllexport) void x2w_d3d12_view_probe(unsigned long long ti
}
}

// Fixture export (startup_inline_retire): what a draw binds for a 32-byte texture token, step by step as the
// texture path does it (record id, as_wrapper, sampled_address_texture). wrapper: the resource wrapper the token
// names when it is still registered; texture: the desktop texture bound, or null (a null binding).
extern "C" __declspec(dllexport) BOOL x2w_d3d12_token_texture(const void* token, void** wrapper, void** texture)
{
*wrapper = *texture = nullptr;
std::uint32_t words[8];
std::memcpy(words, token, sizeof(words));
ViewRecord record{};
if (words[0] != view_token_magic) return FALSE;
AcquireSRWLockShared(&note_lock);
const bool known = words[1] < view_records().size();
if (known) record = view_records()[words[1]];
ReleaseSRWLockShared(&note_lock);
if (!known) return FALSE;
Wrapper* resource = as_wrapper(reinterpret_cast<const void*>(record.resource));
*wrapper = resource;
*texture = sampled_address_texture(resource);
return TRUE;
}

// Fixture-only: the next `count` wrapper allocations fail as an exhausted heap would (#2653).
extern "C" __declspec(dllexport) void x2w_d3d12_fail_wraps(LONG count)
{
Expand Down
Loading
Loading