From 31cc179390e805ea90fef85f787fb594d1144fa0 Mon Sep 17 00:00:00 2001 From: Roland Edi Date: Tue, 1 Dec 2026 11:12:10 +0000 Subject: [PATCH 1/7] runtime: refresh large placed Mesh86 material SRVs Adopt the existing committed desktop backing for a placed material view, refresh it from title memory at submit, and copy only changed runs. Keep the existing backing and its fences; a submitted GPU write stops refreshes. Add a source-built two-SRV fixture with range, token, stale, budget and mutant controls. Refs #3640, #3638, #3545. --- CMakePresets.json | 4 +- docs/experiments.md | 9 + docs/experiments/mesh86-pixel-execz.md | 45 +- src/startup_stubs/d3d12_compute_dispatch.inl | 1 + src/startup_stubs/d3d12_draw.inl | 18 +- src/startup_stubs/d3d12_xs_device.cpp | 64 +- src/startup_stubs/linear_buffer_backing.h | 158 ++++- src/startup_stubs/linear_buffer_report.h | 4 +- src/startup_stubs/list_copy.inl | 28 +- .../startup_mesh86_material_backing.cmake | 17 + tests/startup_mesh86_material_backing.cpp | 549 ++++++++++++++++++ 11 files changed, 861 insertions(+), 36 deletions(-) create mode 100644 tests/cmake/startup_mesh86_material_backing.cmake create mode 100644 tests/startup_mesh86_material_backing.cpp diff --git a/CMakePresets.json b/CMakePresets.json index 6bd4804f08..ec63263762 100644 --- a/CMakePresets.json +++ b/CMakePresets.json @@ -34,7 +34,7 @@ "xmem_shim_test_controls", "startup_stub_xcrdapi", "startup_stub_xcrdapi_break_window_control", "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", + "xmem_page_runs_device_check", "linear_buffer_backing_check", "startup_mesh86_material_backing", "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" ] @@ -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_mesh86_material_backing(_mutant)?_warp|startup_stage_package|startup_compute_packed_d16_x_uav_reference|native_.*_(ir|dxil|controls)|native_direct_mesh|startup_triage_run)$" } } }, diff --git a/docs/experiments.md b/docs/experiments.md index 1b446afa25..fc5d3bb935 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -11162,6 +11162,15 @@ Run `python -B tests/startup_mesh86_srv_proof_check.py` to check the load count without DXC. The synthetic DXIL dump passes with one DWORD load and is rejected when a second identical load uses the same SRV handle. +The placed material-buffer backing has its own source-built fixture: one 64 KiB +placed buffer at an unaligned title address, two raw SRVs at different offsets, +a submitted GPU readback, a stale token, a UAV token and out-of-range records. +Run `ctest --preset release --no-tests=error -R +'^startup_mesh86_material_backing_(warp|hardware)$' --output-on-failure`; the +mutant entries keep the bytes visible at adoption and must fail. The fixture +reports refresh bytes (65,536 first, 4 per changed word) and the reused backing; +see [the mesh86 note](experiments/mesh86-pixel-execz.md#material-placed-buffer-backing). + On the Release worktree at `76aeef7f` plus these changes, the combined lease, SRV proof, export and mapped-page selection passed eight tests. The two mesh cases returned 77 on the adapters listed above. `dumpbin /exports` showed diff --git a/docs/experiments/mesh86-pixel-execz.md b/docs/experiments/mesh86-pixel-execz.md index d6a8711a6d..6d3c579b00 100644 --- a/docs/experiments/mesh86-pixel-execz.md +++ b/docs/experiments/mesh86-pixel-execz.md @@ -92,8 +92,47 @@ resource. Verified GPU-backed views can span more than 16 MiB up to the desktop raw SRV limit. A local runtime sample created and selected four desktop Mesh PSOs and -observed their direct dispatch calls. All sampled scene dispatches stopped at -resource binding. One needed a 128-byte root SRV with no mapped backing. The -other three needed a large placed buffer view whose desktop backing did not +observed their direct dispatch calls. At the time of that sample, all scene +dispatches stopped at resource binding. One needed a 128-byte root SRV with no +mapped backing. The other three needed a large placed buffer view whose desktop +backing did not alias the guest memory or have a verified GPU producer. Visible scene output remains unverified. + +## Material placed-buffer backing + +A native Mesh86 material SRV on a placed buffer whose desktop backing does not +alias title memory no longer stops the bind. The material path adopts the +existing committed desktop resource through the linear-buffer refresh path +(`linear_buffer_backing.h`): the first submission before a consumer copies the +title range, later submissions compare 4 KiB blocks and copy contiguous changed +runs (runs separated by at most one block are merged; more than 1024 runs fall +back to one span). The consumer queue waits for the refresh fence, and a refresh +waits for earlier tracked submissions. The placed backing is reused, so adoption +adds no default-heap VRAM. A submitted copy or bound UAV makes the +desktop bytes authoritative and stops the refreshes. + +The source-built fixture places a 64 KiB buffer at an unaligned title address, +so slot 133 keeps a committed default backing. Two raw SRVs at offsets 0 and +`0x8000` are read by one compute dispatch; the readback distinguishes the two +values. Changing one title word changes only that SRV's value, and the refresh +copies four bytes; two disjoint changed words copy two four-byte runs. Sentinels +outside the placed range stay unchanged. The controls refuse an out-of-range +record, a record over the raw-SRV limit, a UAV view token and a released +resource. The fixture reports one adopted backing and no linear placement. + +```powershell +ctest --preset release --no-tests=error -R '^startup_mesh86_material_backing_(warp|hardware)$' --output-on-failure +ctest --preset release --no-tests=error -R '^startup_mesh86_material_backing_mutant_(warp|hardware)$' --output-on-failure +``` + +The mutant keeps the bytes visible at adoption; both normal tests must pass and +both mutant tests must fail (the CTest entries use `WILL_FAIL`). + +Limits. Adoption does not see a GPU write submitted before the first material +bind; only writes recorded on the current recording or tracked through a +submitted copy stop a refresh. The changed-run comparison runs at each submit +over the whole resource and the first refresh copies it whole, so a 174 MiB +resource still costs a 174 MiB compare per submission even when few bytes +changed. The fixture measures refresh bytes and the reused backing; it does not +measure frame time or peak VRAM against the DXGI budget on a title scene. diff --git a/src/startup_stubs/d3d12_compute_dispatch.inl b/src/startup_stubs/d3d12_compute_dispatch.inl index e32e1246d8..a58d6ddbe7 100644 --- a/src/startup_stubs/d3d12_compute_dispatch.inl +++ b/src/startup_stubs/d3d12_compute_dispatch.inl @@ -1630,6 +1630,7 @@ const char* record_translated_dispatch(Wrapper* self, const TranslatedDispatch& buffer_view(dest, view.resource, view.offset, static_cast(view.bytes)); continue; } + note_linear_gpu_write_resource(self, view.resource); require_state(self, view.resource, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); if (view.texture || view.described) { device_of(the_device)->CreateUnorderedAccessView(view.resource, nullptr, diff --git a/src/startup_stubs/d3d12_draw.inl b/src/startup_stubs/d3d12_draw.inl index 2b79836af2..d290abc259 100644 --- a/src/startup_stubs/d3d12_draw.inl +++ b/src/startup_stubs/d3d12_draw.inl @@ -2684,7 +2684,7 @@ struct IndirectBufferView { u64 offset = 0, bytes = 0; UINT stride = 0; bool upload = false; - int source = 0; // 0 aliased or any other backing, 1 a GPU copy this list made (X2W_TRANSLATED_INDIRECT_COPY_RANGES), 2 a snapshot of title memory, 3 zeros for a null descriptor + int source = 0; // 0 aliased or any other backing, 1 a GPU copy this list made (X2W_TRANSLATED_INDIRECT_COPY_RANGES) or a GPU-written backing, 2 a snapshot of title memory, 3 zeros for a null descriptor, 4 a placed material backing refreshed from title memory at submit u64 snapshot_address = 0; // title address for a pending snapshot (source 2 with no resource) }; @@ -2891,6 +2891,21 @@ IndirectBufferView indirect_table_buffer(Wrapper* self, const std::uint32_t* wor if (!placed.alias) { if (native && indirect_table_copied_gpu_range(self, native, offset, bytes)) { input_source = 1; // a GPU copy of this list filled the range: the GPU buffer is the truth + } else if (use == InputBufferUse::mesh86_material && native && linear_buffers().written_by_gpu(native)) { + input_source = 1; // a submitted GPU write filled the backing: the desktop bytes are the truth + } else if (use == InputBufferUse::mesh86_material && native) { + // The placed backing exists but does not alias title memory. Adopt that same resource: the + // linear-buffer path refreshes it from the title bytes before the recording executes, copies + // only the changed span after the first refresh, and orders the consumer behind its fence. No + // second default-heap buffer is allocated. + X2wLinearBufferInfo info{}; + if (SUCCEEDED(linear_buffers().adopt(device_of(device), native, owner->own().title_memory, + native->GetDesc().Width, &info))) + input_source = 4; + else { + diag_placed_refusal(self, native, offset, bytes, placed_context); + return refuse("a placed material buffer has no coherent desktop backing"); + } } else if (allow_title_snapshot && title_input_snapshot_enabled() && bytes <= (u64{16} << 20)) { // The desktop buffer does not alias title memory. Resolve the title range here and let the // dispatch copy it after its outputs have been validated. @@ -4050,6 +4065,7 @@ bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UI } for (UINT j = 0; j < tr->uavs.size(); ++j) { const D3D12_CPU_DESCRIPTOR_HANDLE dest{draw_heap->GetCPUDescriptorHandleForHeapStart().ptr + SIZE_T{first + n + j} * draw_heap_increment}; + note_linear_gpu_write_resource(self, uav_bindings[j].resource); require_state(self, uav_bindings[j].resource, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); if (tr->uavs[j].raw) { D3D12_RESOURCE_BARRIER barrier{}; diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index 6a852b1847..96fa7772fe 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -1468,6 +1468,13 @@ x2w_startup::LinearBuffers& linear_buffers() static x2w_startup::LinearBuffers buffers; return buffers; } + +// Linear-buffer refresh and queue ordering run when the opt-in placements are on, or once a placed +// material backing has adopted its existing desktop resource (which happens without the switch). +bool linear_tracking() +{ + return linear_buffers().ever_active(); +} // The wrappers and their desktop objects stay alive for the process (experiment scope). The one exception is // X2W_D3D12_RELEASE_RETIRED=1: the desktop object of a resource of the retire class is freed once nothing refers to it. // The wrapper stays. @@ -1509,8 +1516,8 @@ ULONG __stdcall release(Wrapper* self) drop_mesh_lease_owner(self); retire_placement(self); if (self->own().retire_when_idle) retire_note_title_release(self); - if (x2w_startup::linear_buffer_mode() != x2w_startup::LinearBufferMode::off) - linear_buffers().retire(static_cast(self->own().real)); + // Idempotent: an adopted placed material backing also has to stop reading title memory. + linear_buffers().retire(static_cast(self->own().real)); } if (self->own().kind == list_kind && self->own().real) { if (indirect_cross_list_copy()) indirect_copy_tracker().reset(self); @@ -1829,6 +1836,7 @@ void end_open_queries(Wrapper* self, ID3D12GraphicsCommandList* list); void reset_list_dynamic_state(Wrapper* self); void discard_list_gpu_writes(Wrapper* self); void commit_list_gpu_writes(Wrapper* self); +void note_linear_gpu_write_resource(Wrapper* self, ID3D12Resource* resource); void discard_address_uploads(ID3D12CommandList* list); void use_as_target(Wrapper* self, ID3D12Resource* resource); bool is_container(const void* p); @@ -2331,8 +2339,7 @@ extern "C" __declspec(dllexport) void x2w_d3d12_render_target_stats(unsigned* bi extern "C" __declspec(dllexport) bool x2w_d3d12_linear_buffer_info(void* resource, X2wLinearBufferInfo* info) { Wrapper* w = as_wrapper(resource); - if (!info || !w || w->own().kind != resource_kind || !w->own().real || - x2w_startup::linear_buffer_mode() == x2w_startup::LinearBufferMode::off) + if (!info || !w || w->own().kind != resource_kind || !w->own().real) return false; return linear_buffers().info(static_cast(w->own().real), info); } @@ -2340,7 +2347,7 @@ extern "C" __declspec(dllexport) void x2w_d3d12_linear_buffer_totals(X2wLinearBu { if (!totals) return; *totals = X2wLinearBufferTotals{}; - if (x2w_startup::linear_buffer_mode() != x2w_startup::LinearBufferMode::off) linear_buffers().totals(totals); + linear_buffers().totals(totals); } // Fixtures: the next refresh that reaches `point` (0 before staging, 1 after the title bytes are staged, // 2 after its copy was executed, before it is published), or for point 3 the next title Wait (queue slot 17) @@ -5667,8 +5674,9 @@ void __stdcall list_dispatch_mesh(Wrapper* self, UINT x, UINT y, UINT z) } #endif -// X2W_D3D12_LINEAR_BUFFERS: the copied linear buffers are refreshed from title memory on the internal -// refresh queue, and queue waits for those refreshes, just before the title's lists. A refresh that +// X2W_D3D12_LINEAR_BUFFERS, or an adopted placed material backing: the copied buffers are refreshed +// from title memory on the internal refresh queue, and queue waits for those refreshes, just before +// the title's lists. A refresh that // fails leaves that buffer stale (logged, counted); the lists run either way. False: a refresh had no // safe completion order and the submission is refused (logged, counted): nothing was enqueued, and the // caller drops the title's lists without executing them or committing their bookkeeping. The title's @@ -5676,20 +5684,21 @@ void __stdcall list_dispatch_mesh(Wrapper* self, UINT x, UINT y, UINT z) // waits on it. bool linear_refresh(ID3D12CommandQueue* queue) { - return x2w_startup::linear_buffer_mode() == x2w_startup::LinearBufferMode::off || linear_buffers().before_submit(queue); + return !linear_tracking() || linear_buffers().before_submit(queue); } // After the title's lists on queue: a later refresh's copy waits for this submission (the producer wait). void linear_submitted(ID3D12CommandQueue* queue) { - if (x2w_startup::linear_buffer_mode() != x2w_startup::LinearBufferMode::off) linear_buffers().after_submit(queue); + if (linear_tracking()) linear_buffers().after_submit(queue); } // The queue's order lock (linear_buffer_backing.h), so its title waits and user fence values are recorded in // the order the desktop queue receives them: held by a submission from its ExecuteCommandLists through // linear_submitted, and by queue slot 17 from the desktop Wait through note_title_wait. Taken before -// draw_lock and allocator_lock and with no other lock held; nothing while the switch is off. +// draw_lock and allocator_lock and with no other lock held; nothing until the switch or an adoption +// enables tracking. x2w_startup::LinearBuffers::QueueOrder linear_queue_order(ID3D12CommandQueue* queue, bool title_wait) { - if (x2w_startup::linear_buffer_mode() == x2w_startup::LinearBufferMode::off) return {}; + if (!linear_tracking()) return {}; return linear_buffers().queue_order(queue, title_wait); } @@ -5928,8 +5937,7 @@ u64 __stdcall queue_wait(Wrapper* self, u64 rdx, u64 r8, u64 r9) { const auto order = linear_queue_order(queue, true); hr = queue->Wait(static_cast(fence->own().real), r8); - if (SUCCEEDED(hr) && x2w_startup::linear_buffer_mode() != x2w_startup::LinearBufferMode::off) - linear_buffers().note_title_wait(queue, static_cast(fence->own().real), r8); + if (SUCCEEDED(hr)) linear_buffers().note_title_wait(queue, static_cast(fence->own().real), r8); } static LONG calls; if (first_calls(calls, 2)) @@ -9436,3 +9444,33 @@ HRESULT x2w_d3d12_permissive_create_device(IUnknown* adapter, const void* parame if (debug) device->QueryInterface(IID_PPV_ARGS(&info_queue)); return S_OK; } + +// Fixture-only entry point: resolve one eight-word material table record through the production +// Mesh86 material path (indirect_table_buffer with InputBufferUse::mesh86_material), on an open +// recording. The fixture can then submit a read of the returned backing through the queue wrapper, +// which exercises the refresh and its fences without needing a captured guest shader. +extern "C" __declspec(dllexport) HRESULT x2w_d3d12_mesh86_material_resolve( + void* guest_list, const UINT* words, ID3D12Resource** out_resource, UINT64* out_offset, UINT64* out_bytes, + int* out_source, const char** out_reason) +{ + if (!out_resource || !out_offset || !out_bytes || !out_source || !out_reason) return E_POINTER; + *out_resource = nullptr; + *out_offset = *out_bytes = 0; + *out_source = 0; + *out_reason = nullptr; + Wrapper* self = as_wrapper(guest_list); + if (!self || self->own().kind != list_kind || !self->own().list_open || !render_mode()) return E_UNEXPECTED; + const char* why = nullptr; + const auto view = indirect_table_buffer(self, words, false, &why, u64{4} << D3D12_REQ_BUFFER_RESOURCE_TEXEL_COUNT_2_TO_EXP, + D3D12_RAW_UAV_SRV_BYTE_ALIGNMENT, true, false, nullptr, nullptr, nullptr, + InputBufferUse::mesh86_material); + *out_resource = view.resource; + *out_offset = view.offset; + *out_bytes = view.bytes; + *out_source = view.source; + if (!view.resource) { + *out_reason = why ? why : "a material buffer has no desktop resource"; + return E_FAIL; + } + return S_OK; +} diff --git a/src/startup_stubs/linear_buffer_backing.h b/src/startup_stubs/linear_buffer_backing.h index 18c9a9278e..8c6f234952 100644 --- a/src/startup_stubs/linear_buffer_backing.h +++ b/src/startup_stubs/linear_buffer_backing.h @@ -35,6 +35,17 @@ // record. Only the bytes that differ from the last upload are copied, through an upload staging // buffer. // +// Adoption. A placed buffer that already has a committed default backing (slot 133's placement when +// the title memory cannot be aliased) can be adopted for a read-only material view instead of being +// refused. The existing backing is reused, so adoption adds no default-heap VRAM; its first refresh +// copies the title range because nothing is known about the backing's bytes yet, and later +// submissions copy only the changed runs. Adoption is only for a range validated against the +// resource, whose backing has no recorded GPU write, and which the caller binds as an SRV. A recorded +// GPU write (copy or bound UAV) makes the desktop backing authoritative: refreshes stop, as +// they do for a copied placement. The caller still owns placement, retention and range validation; +// this file owns the refresh and its fences. A GPU write already submitted before the first adoption +// is not seen; the caller may only adopt a range whose earlier GPU use was read-only. +// // Every refresh runs on one internal COPY queue per device, which never waits on a title fence. A // refresh's copy (staging -> backing) is executed there and signals an internal fence value; the // buffer remembers the value of its last refresh. Every submission through a queue wrapper, on any @@ -423,6 +434,99 @@ class LinearBuffers { } } + // A placed material view resolved a buffer whose desktop backing does not alias title memory and + // whose range has no recorded GPU producer. Adopt that existing backing for refresh at submit: + // no new default-heap resource is created, and the first refresh establishes the authoritative + // copy from the title bytes. S_FALSE: this resource is shared/aliased, so no refresh is needed. + // Failure: the caller refuses the material view. + HRESULT adopt(ID3D12Device* device, ID3D12Resource* resource, const void* title, UINT64 bytes, + X2wLinearBufferInfo* report) + { + if (report) *report = X2wLinearBufferInfo{}; + if (!device || !resource || !title || !bytes) return E_INVALIDARG; + const auto desc = resource->GetDesc(); + if (desc.Dimension != D3D12_RESOURCE_DIMENSION_BUFFER || bytes > desc.Width) return E_INVALIDARG; + std::lock_guard lock(mutex_); + if (const auto found = records_.find(resource); found != records_.end()) { + if (found->second.info.path == shared_path) { + if (report) *report = found->second.info; + return S_FALSE; + } + if (const Copied* copy = found->second.copy.get()) { + if (copy->gpu_written) return E_INVALIDARG; + if (!found->second.info.adopted) { + found->second.info.adopted = 1; + ++totals_.adopted; + } + adopted_.store(true); + if (report) *report = found->second.info; + return S_OK; + } + } + if (x2w_local::probe_readable(reinterpret_cast(title), static_cast(bytes)) < bytes) + return E_INVALIDARG; // a partial title range cannot establish a coherent whole backing + const HRESULT internal = linear_detail::submit_fence_forced_off() ? E_NOT_VALID_STATE : internal_ready(device); + if (FAILED(internal)) { + if (report) { + report->path = kept_default_path; + report->refusal_hr = internal; + report->backing = resource; + } + return internal; + } + Record record{}; + record.info.use = gpu_read; + record.info.path = copied_path; + record.info.refusal_hr = S_OK; + record.info.feature_hr = S_FALSE; + record.info.share_hr = S_FALSE; + record.info.backing = resource; + record.info.adopted = 1; + try { + record.copy = std::make_shared(); + record.copy->title = static_cast(title); + record.copy->bytes = bytes; + if (linear_detail::mutant("skip-refresh")) { + // Negative control: the bytes at adoption are all every submission gets. + record.copy->bound.resize(static_cast(bytes)); + if (!x2w_local::guarded_memcpy(record.copy->bound.data(), title, static_cast(bytes), false)) + return E_INVALIDARG; + } + records_.insert_or_assign(resource, std::move(record)); + } catch (const std::bad_alloc&) { + return E_OUTOFMEMORY; + } + ++totals_.adopted; + adopted_.store(true); + if (x2w_local::first_calls(adopt_logged_, 8)) + x2w_local::logf("x2w-d3d12 linear buffer %p: adopted its existing placed backing for material refresh, " + "%llu bytes", static_cast(resource), static_cast(bytes)); + if (report) *report = records_.at(resource).info; + return S_OK; + } + + // A queue submission (or a title wait) can name an adopted or copied backing. Once true, queue + // submissions and slot 17 waits take the per-queue order lock for the process lifetime, so a + // wait recorded after the first adoption is still ordered with submissions. + bool ever_active() const { return adopted_.load() || linear_buffer_mode() != LinearBufferMode::off; } + + // This resource has an adopted or copied backing that a later GPU write must stop refreshing. + bool watching(ID3D12Resource* resource) + { + std::lock_guard lock(mutex_); + const auto found = records_.find(resource); + return found != records_.end() && found->second.copy && found->second.copy->live && + !found->second.copy->gpu_written; + } + + // The desktop backing holds bytes a submitted GPU command wrote; title memory is stale from then on. + bool written_by_gpu(ID3D12Resource* resource) + { + std::lock_guard lock(mutex_); + const auto found = records_.find(resource); + return found != records_.end() && found->second.copy && found->second.copy->gpu_written; + } + // A submitted recording writes the backing of `resource` (list_copy.inl, after its ExecuteCommandLists): // if it is a copied buffer, it keeps the GPU's bytes from now on and is no longer refreshed from the // title memory. @@ -501,20 +605,42 @@ class LinearBuffers { ++totals_.unreadable; continue; } - std::size_t first = 0, last = bytes; - if (copy->uploaded.size() == bytes) { - if (std::memcmp(copy->uploaded.data(), source, bytes) == 0) { - copy->stale = false; - continue; - } - while (first < bytes && copy->uploaded[first] == source[first]) ++first; - while (last > first && copy->uploaded[last - 1] == source[last - 1]) --last; - first &= ~std::size_t{3}; - last = (std::min)(bytes, (last + 3) & ~std::size_t{3}); - } + // The first refresh copies the whole range: the backing's bytes are not known. After that, + // compare 4 KiB blocks and copy contiguous changed runs. Runs with a gap of at most one + // block are merged, so a scattered set of changed pages costs one copy per region rather + // than one copy from the first to the last changed byte. More than 1024 runs fall back to + // one span; every work item has its own staging buffer, so this bounds the pool. + const std::size_t work_before = work.size(); try { - work.push_back({resource, copy, source, first, last - first}); + std::vector> runs; + if (copy->uploaded.size() == bytes) { + constexpr UINT64 block = 4096; + for (UINT64 at = 0; at < bytes; at += block) { + const UINT64 size = (std::min)(block, bytes - at); + const unsigned char* old_bytes = copy->uploaded.data() + at; + const unsigned char* new_bytes = source + at; + if (std::memcmp(old_bytes, new_bytes, static_cast(size)) == 0) continue; + UINT64 first = 0, last = size; + while (first < size && old_bytes[first] == new_bytes[first]) ++first; + while (last > first && old_bytes[last - 1] == new_bytes[last - 1]) --last; + first = at + (first & ~UINT64{3}); + last = (std::min)(bytes, at + ((last + 3) & ~UINT64{3})); + if (!runs.empty() && first - runs.back().second <= block) runs.back().second = last; + else runs.push_back({first, last}); + } + if (runs.empty()) { + copy->stale = false; + continue; + } + if (runs.size() > 1024) runs = {{runs.front().first, runs.back().second}}; + } else { + runs.push_back({0, bytes}); + } + for (const auto& [offset, end] : runs) { + work.push_back({resource, copy, source, offset, end - offset}); + } } catch (const std::bad_alloc&) { + work.resize(work_before); refresh_failed(resource, *copy, E_OUTOFMEMORY); } } @@ -680,6 +806,7 @@ class LinearBuffers { out->gpu_written = copy->gpu_written ? 1 : 0; out->refresh_failures = copy->refresh_failures; out->last_refresh_hr = copy->last_refresh_hr; + out->adopted = found->second.info.adopted; } return true; } @@ -744,7 +871,8 @@ class LinearBuffers { UINT64 generation, bytes; x2w_budget::Ticket* budget; // the heap's budget ticket (X2W_D3D12_BUDGET), counted while a buffer uses it }; - // 256 staging buffers; X2W_TEST_LINEAR_STAGING_LIMIT= (fixtures) lowers it, to make the pool fill. + // 2048 staging buffers (one per changed run); X2W_TEST_LINEAR_STAGING_LIMIT= (fixtures) lowers it, + // to make the pool fill. static std::size_t staging_limit() { static const std::size_t limit = [] { @@ -753,7 +881,7 @@ class LinearBuffers { const DWORD n = GetEnvironmentVariableA("X2W_TEST_LINEAR_STAGING_LIMIT", value, sizeof(value)); SetLastError(saved); const unsigned long parsed = n && n < sizeof(value) ? std::strtoul(value, nullptr, 10) : 0; - return parsed ? static_cast(parsed) : std::size_t{256}; + return parsed ? static_cast(parsed) : std::size_t{2048}; }(); return limit; } @@ -1255,10 +1383,12 @@ class LinearBuffers { std::atomic pauses_armed_{false}; ID3D12Device* feature_device_ = nullptr; HRESULT feature_hr_ = S_FALSE; + std::atomic adopted_{false}; // a placed material backing adopted its existing desktop resource UINT64 generation_ = 0, staging_ids_ = 0, staging_requests_ = 0; std::size_t creating_ = 0; // staging buffers being created outside the lock X2wLinearBufferTotals totals_{}; volatile LONG unreadable_logged_ = 0, wait_logged_ = 0, refresh_logged_ = 0, gpu_write_logged_ = 0, unsafe_logged_ = 0; + volatile LONG adopt_logged_ = 0; }; } // namespace x2w_startup diff --git a/src/startup_stubs/linear_buffer_report.h b/src/startup_stubs/linear_buffer_report.h index 107ca76e28..2ec2d27efd 100644 --- a/src/startup_stubs/linear_buffer_report.h +++ b/src/startup_stubs/linear_buffer_report.h @@ -15,17 +15,19 @@ struct X2wLinearBufferInfo { std::uint32_t stale; // copied: 1 while the backing holds an older upload than the title's bytes std::uint64_t heap_generation; // shared: generation of the opened heap void* backing; // the desktop ID3D12Resource - std::uint64_t refreshes; // copied: submissions that copied bytes into the backing + std::uint64_t refreshes; // copied: changed spans copied into the backing (a submission may have several) std::uint64_t bytes_copied; // copied: bytes copied from title memory into the backing std::uint64_t last_staging; // copied: id of the staging buffer of the last refresh (0: none) std::uint64_t last_fence; // copied: internal fence value of the last refresh (0: none) std::uint64_t refresh_failures; // copied: submissions that ran without this buffer's refresh std::int32_t last_refresh_hr; // copied: HRESULT of the last failed refresh; S_OK if none std::uint32_t gpu_written; // copied: 1 once a submitted copy wrote it; it is no longer refreshed + std::uint32_t adopted; // copied: 1 when a placed material view adopted this existing backing }; struct X2wLinearBufferTotals { std::uint64_t placements, shared, copied, kept_default; + std::uint64_t adopted; // existing placed backings refreshed for material views std::uint64_t feature_queries, heap_opens, heap_open_failures, heap_cache_hits, place_failures; std::uint64_t submissions, refreshes, bytes_copied, staging_created, staging_reused, unreadable; std::uint64_t refresh_failures; diff --git a/src/startup_stubs/list_copy.inl b/src/startup_stubs/list_copy.inl index 6d3ac77b6e..69f90cbfd3 100644 --- a/src/startup_stubs/list_copy.inl +++ b/src/startup_stubs/list_copy.inl @@ -170,8 +170,7 @@ void mark_gpu_written(Wrapper* self, const CopyEndpoint& destination) // Until then the write is pending on the recording: Reset or a failed Close drops it with the texture writes. void note_linear_gpu_write(Wrapper* self, const CopyEndpoint& destination) { - if (!destination.wrapper || !destination.wrapper->own().title_memory || - x2w_startup::linear_buffer_mode() == x2w_startup::LinearBufferMode::off) + if (!destination.wrapper || !destination.wrapper->own().title_memory) return; if (x2w_startup::linear_detail::mutant("gpuw-at-record")) { // Mutant: the backing changes at recording, so a discarded recording still stops its refreshes. @@ -184,6 +183,31 @@ void note_linear_gpu_write(Wrapper* self, const CopyEndpoint& destination) ReleaseSRWLockExclusive(&pending_writes_lock); } +// A translated draw or dispatch binds `resource` as a UAV. Keep the write pending on the recording, +// like a recorded copy: only a submitted recording makes the desktop bytes authoritative, and a +// discarded recording leaves the adopted backing refreshed from title memory. +void note_linear_gpu_write_resource(Wrapper* self, ID3D12Resource* resource) +{ + if (!resource) return; + if (x2w_startup::linear_detail::mutant("gpuw-at-record")) { + linear_buffers().note_gpu_write(resource); + return; + } + AcquireSRWLockExclusive(&pending_writes_lock); + auto& writes = pending_linear_writes()[self]; + if (std::find(writes.begin(), writes.end(), resource) == writes.end()) { + try { + writes.push_back(resource); + } catch (const std::bad_alloc&) { + // The refresh cannot know about this write: stop refreshing the resource now. + ReleaseSRWLockExclusive(&pending_writes_lock); + linear_buffers().note_gpu_write(resource); + return; + } + } + ReleaseSRWLockExclusive(&pending_writes_lock); +} + // Refusal shared by the three handlers once the descriptions passed, or none. x2w_startup::CopyRefusal check_roles_and_sync(Wrapper* self, const CopyEndpoint& to, const CopyEndpoint& from, bool sync) { diff --git a/tests/cmake/startup_mesh86_material_backing.cmake b/tests/cmake/startup_mesh86_material_backing.cmake new file mode 100644 index 0000000000..d7adf9ade5 --- /dev/null +++ b/tests/cmake/startup_mesh86_material_backing.cmake @@ -0,0 +1,17 @@ +# A placed buffer whose desktop backing does not alias title memory: the Mesh86 material path adopts +# the existing backing, refreshes it at submit, and two GPU SRVs read distinct offsets. The mutant +# test keeps the bytes visible at adoption, so a stale second read must fail. +add_executable(startup_mesh86_material_backing tests/startup_mesh86_material_backing.cpp) +target_compile_features(startup_mesh86_material_backing PRIVATE cxx_std_17) +target_include_directories(startup_mesh86_material_backing PRIVATE src) +target_link_libraries(startup_mesh86_material_backing PRIVATE d3d12_xs_shim d3d12 dxgi d3dcompiler) + +foreach(backend IN ITEMS warp hardware) + add_test(NAME startup_mesh86_material_backing_${backend} COMMAND startup_mesh86_material_backing ${backend}) + set_tests_properties(startup_mesh86_material_backing_${backend} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 + ENVIRONMENT "X2W_D3D12_PERMISSIVE=1;X2W_D3D12_LIST_NOOP=1;X2W_D3D12_RENDER=1") + add_test(NAME startup_mesh86_material_backing_mutant_${backend} COMMAND startup_mesh86_material_backing ${backend}) + set_tests_properties(startup_mesh86_material_backing_mutant_${backend} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 + WILL_FAIL TRUE + ENVIRONMENT "X2W_D3D12_PERMISSIVE=1;X2W_D3D12_LIST_NOOP=1;X2W_D3D12_RENDER=1;X2W_TEST_LINEAR_BUFFER_MUTANT=skip-refresh") +endforeach() diff --git a/tests/startup_mesh86_material_backing.cpp b/tests/startup_mesh86_material_backing.cpp new file mode 100644 index 0000000000..132b265fbd --- /dev/null +++ b/tests/startup_mesh86_material_backing.cpp @@ -0,0 +1,549 @@ +// A placed buffer whose desktop backing does not alias title memory, read through the Mesh86 +// material path. The test adopts the existing backing, records two raw SRVs at distinct offsets, +// and reads both through a compute dispatch submitted through the queue wrapper. The first +// submission copies the title range; later submissions copy only the changed span. Controls cover +// an out-of-range record, an oversized record, a UAV view token (wrong type) and a released +// resource. Sentinels outside the placed buffer catch reads of unrelated title memory. +// +// startup_mesh86_material_backing +// +// X2W_TEST_LINEAR_BUFFER_MUTANT=skip-refresh makes adoption keep the bytes visible at adoption, so +// the second and third readbacks are stale; the registered mutant test expects that failure. + +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +#include "../src/startup_stubs/linear_buffer_report.h" +#include "../src/startup_stubs/resource_budget.h" + +extern "C" __declspec(dllimport) HRESULT WINAPI D3D12XboxCreateDevice(IUnknown*, const void*, REFIID, void**); +extern "C" __declspec(dllimport) bool x2w_d3d12_linear_buffer_info(void*, X2wLinearBufferInfo*); +extern "C" __declspec(dllimport) void x2w_d3d12_linear_buffer_totals(X2wLinearBufferTotals*); +extern "C" __declspec(dllimport) BOOL x2w_d3d12_budget_snapshot(x2w_budget::Snapshot*, SIZE_T); +extern "C" __declspec(dllimport) HRESULT x2w_d3d12_mesh86_material_resolve( + void*, const UINT*, ID3D12Resource**, UINT64*, UINT64*, int*, const char**); + +using Microsoft::WRL::ComPtr; + +namespace { +constexpr UINT64 page = 64 * 1024; +constexpr UINT64 buffer_bytes = page; +constexpr UINT64 buffer_offset = 0x1000; // private allocation, not 64 KiB aligned: the default copied placement +constexpr UINT64 second_srv_offset = 0x8000; +constexpr UINT64 allocation_bytes = 3 * page; +constexpr std::uint32_t sentinel = 0xa5a5a5a5u; +constexpr std::uint32_t a0 = 0x11112222u, b0 = 0x33334444u, c0 = 0x55556666u, d0 = 0x77778888u; +constexpr std::uint32_t e0 = 0x9999aaaau, f0 = 0xbbbbccccu; + +unsigned failures = 0; + +void check(bool pass, const char* what) +{ + std::printf("%s: %s\n", pass ? "PASS" : "FAIL", what); + if (!pass) ++failures; +} + +std::string hex(HRESULT hr) +{ + char text[16]; + std::snprintf(text, sizeof(text), "0x%08lx", static_cast(hr)); + return text; +} + +template +Method slot(IUnknown* object, unsigned index) +{ + return reinterpret_cast((*reinterpret_cast(object))[index]); +} + +using Word = std::uint64_t; +Word invoke(void* object, unsigned index, Word a = 0, Word b = 0, Word c = 0, Word d = 0, Word e = 0) +{ + using Slot = Word(WINAPI*)(void*, Word, Word, Word, Word, Word); + return reinterpret_cast((*static_cast(object))[index])(object, a, b, c, d, e); +} +template Word arg(T* value) { return reinterpret_cast(value); } + +// The desktop object behind a wrapper: SetPrivateDataInterface unwraps its argument before the +// call reaches the shared desktop device. +template +ComPtr underlying(ID3D12Device* desktop, ID3D12Device* guest, IUnknown* object) +{ + constexpr GUID key{0x6c1f0a3e, 0x2b51, 0x4d0e, {0x9b, 0x31, 0x5e, 0x0c, 0x72, 0x14, 0x88, 0x19}}; + ComPtr result; + if (FAILED(guest->SetPrivateDataInterface(key, object))) return result; + ComPtr stored; + UINT bytes = sizeof(IUnknown*); + const HRESULT read = desktop->GetPrivateData(key, &bytes, stored.GetAddressOf()); + guest->SetPrivateDataInterface(key, nullptr); + if (SUCCEEDED(read)) stored.As(&result); + return result; +} + +D3D12_RESOURCE_DESC buffer_desc(UINT64 bytes, D3D12_RESOURCE_FLAGS flags) +{ + D3D12_RESOURCE_DESC desc{}; + desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + desc.Width = bytes; + desc.Height = 1; + desc.DepthOrArraySize = 1; + desc.MipLevels = 1; + desc.Format = DXGI_FORMAT_UNKNOWN; + desc.SampleDesc.Count = 1; + desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + desc.Flags = flags; + return desc; +} + +struct Device { + ComPtr desktop, guest; + ComPtr guest_queue, native_queue; + ComPtr completed; + UINT64 completed_value = 0; +}; + +bool init_device(bool warp, Device& device) +{ + ComPtr factory; + if (FAILED(CreateDXGIFactory1(IID_PPV_ARGS(&factory)))) return false; + ComPtr adapter; + if (warp) { + if (FAILED(factory->EnumWarpAdapter(IID_PPV_ARGS(&adapter)))) return false; + } else { + for (UINT i = 0; factory->EnumAdapters1(i, adapter.ReleaseAndGetAddressOf()) == S_OK; ++i) { + DXGI_ADAPTER_DESC1 desc{}; + if (SUCCEEDED(adapter->GetDesc1(&desc)) && !(desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE)) break; + } + if (!adapter) return false; + } + DXGI_ADAPTER_DESC1 adapter_desc{}; + if (SUCCEEDED(adapter->GetDesc1(&adapter_desc))) + std::printf("adapter %ls vendor=%04x device=%04x\n", adapter_desc.Description, adapter_desc.VendorId, + adapter_desc.DeviceId); + if (FAILED(D3D12XboxCreateDevice(adapter.Get(), nullptr, IID_PPV_ARGS(&device.desktop)))) return false; + unsigned char parameters[64]{}; + if (FAILED(D3D12XboxCreateDevice(adapter.Get(), parameters, IID_PPV_ARGS(&device.guest)))) return false; + const D3D12_COMMAND_QUEUE_DESC queue_desc{D3D12_COMMAND_LIST_TYPE_DIRECT}; + if (FAILED(device.guest->CreateCommandQueue(&queue_desc, IID_PPV_ARGS(&device.guest_queue)))) return false; + device.native_queue = underlying(device.desktop.Get(), device.guest.Get(), device.guest_queue.Get()); + return device.native_queue && + SUCCEEDED(device.desktop->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&device.completed))); +} + +bool wait_fence(ID3D12Fence* fence, UINT64 value) +{ + if (fence->GetCompletedValue() >= value) return true; + HANDLE event = CreateEventW(nullptr, FALSE, FALSE, nullptr); + if (!event) return false; + const bool ok = SUCCEEDED(fence->SetEventOnCompletion(value, event)) && + WaitForSingleObject(event, 20000) == WAIT_OBJECT_0; + CloseHandle(event); + return ok; +} + +struct TitleList { + Device* device = nullptr; + ComPtr allocator; + ComPtr list; + ComPtr native; + + bool begin(Device& d) + { + device = &d; + if (FAILED(d.guest->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator)))) + return false; + using CreateList = HRESULT(WINAPI*)(IUnknown*, const void*, IUnknown*, IUnknown*, REFIID, void**); + const UINT list_desc[]{static_cast(D3D12_COMMAND_LIST_TYPE_DIRECT), 2, 1, 0}; + auto* create = reinterpret_cast((*reinterpret_cast(d.guest.Get()))[73]); + if (FAILED(create(d.guest.Get(), list_desc, allocator.Get(), nullptr, __uuidof(ID3D12GraphicsCommandList), + reinterpret_cast(list.GetAddressOf())))) + return false; + if (FAILED(static_cast(invoke(list.Get(), 139, arg(allocator.Get()))))) return false; + native = underlying(d.desktop.Get(), d.guest.Get(), list.Get()); + return native != nullptr; + } + + void barrier(ID3D12Resource* resource, D3D12_RESOURCE_STATES before, D3D12_RESOURCE_STATES after) + { + D3D12_RESOURCE_BARRIER barrier{}; + barrier.Transition = {resource, D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, before, after}; + native->ResourceBarrier(1, &barrier); + } + + bool close() { return SUCCEEDED(static_cast(invoke(list.Get(), 9))); } + + bool submit() + { + void* lists[] = {list.Get()}; + invoke(device->guest_queue.Get(), 10, 1, arg(lists)); + if (FAILED(device->native_queue->Signal(device->completed.Get(), ++device->completed_value))) return false; + return wait_fence(device->completed.Get(), device->completed_value); + } +}; + +struct ComputeRead { + ComPtr root; + ComPtr pipeline; + ComPtr srv_heap; + ComPtr output, readback; +}; + +// Compile the two-SRV read program and create its descriptor heap over the adopted backing. +bool init_read(Device& device, ID3D12Resource* backing, ComputeRead& read) +{ + constexpr char shader[] = R"( +ByteAddressBuffer first : register(t0); +ByteAddressBuffer second : register(t1); +RWByteAddressBuffer result : register(u0); +[numthreads(1, 1, 1)] +void main() { result.Store2(0, uint2(first.Load(0), second.Load(0))); } +)"; + D3D12_DESCRIPTOR_RANGE range{}; + range.RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_SRV; + range.NumDescriptors = 2; + range.BaseShaderRegister = 0; + D3D12_ROOT_PARAMETER params[2]{}; + params[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; + params[0].DescriptorTable = {1, &range}; + params[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_UAV; + params[1].Descriptor.ShaderRegister = 0; + const D3D12_ROOT_SIGNATURE_DESC root_desc{2, params, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_NONE}; + ComPtr blob, code, errors; + if (FAILED(D3D12SerializeRootSignature(&root_desc, D3D_ROOT_SIGNATURE_VERSION_1, &blob, nullptr)) || + FAILED(device.desktop->CreateRootSignature(0, blob->GetBufferPointer(), blob->GetBufferSize(), + IID_PPV_ARGS(&read.root))) || + FAILED(D3DCompile(shader, sizeof(shader) - 1, nullptr, nullptr, nullptr, "main", "cs_5_0", 0, 0, + &code, &errors))) + return false; + D3D12_COMPUTE_PIPELINE_STATE_DESC pso{}; + pso.pRootSignature = read.root.Get(); + pso.CS = {code->GetBufferPointer(), code->GetBufferSize()}; + if (FAILED(device.desktop->CreateComputePipelineState(&pso, IID_PPV_ARGS(&read.pipeline)))) return false; + const D3D12_DESCRIPTOR_HEAP_DESC heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 2, + D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE}; + if (FAILED(device.desktop->CreateDescriptorHeap(&heap_desc, IID_PPV_ARGS(&read.srv_heap)))) return false; + auto at = read.srv_heap->GetCPUDescriptorHandleForHeapStart(); + const UINT increment = device.desktop->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); + for (UINT i = 0; i < 2; ++i) { + D3D12_SHADER_RESOURCE_VIEW_DESC view{DXGI_FORMAT_R32_TYPELESS, D3D12_SRV_DIMENSION_BUFFER, + D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING}; + view.Buffer.FirstElement = static_cast((i ? second_srv_offset : 0) / 4); + view.Buffer.NumElements = 4; + view.Buffer.Flags = D3D12_BUFFER_SRV_FLAG_RAW; + device.desktop->CreateShaderResourceView(backing, &view, at); + at.ptr += increment; + } + const D3D12_HEAP_PROPERTIES default_heap{D3D12_HEAP_TYPE_DEFAULT}; + const auto output_desc = buffer_desc(16, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS); + if (FAILED(device.desktop->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &output_desc, + D3D12_RESOURCE_STATE_COMMON, nullptr, IID_PPV_ARGS(&read.output)))) + return false; + const D3D12_HEAP_PROPERTIES readback_heap{D3D12_HEAP_TYPE_READBACK}; + const auto readback_desc = buffer_desc(16, D3D12_RESOURCE_FLAG_NONE); + return SUCCEEDED(device.desktop->CreateCommittedResource(&readback_heap, D3D12_HEAP_FLAG_NONE, &readback_desc, + D3D12_RESOURCE_STATE_COPY_DEST, nullptr, + IID_PPV_ARGS(&read.readback))); +} + +bool record_read(TitleList& list, ComputeRead& read, ID3D12Resource* backing, std::array& values) +{ + list.barrier(backing, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE); + list.barrier(read.output.Get(), D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + ID3D12DescriptorHeap* heap = read.srv_heap.Get(); + list.native->SetDescriptorHeaps(1, &heap); + list.native->SetComputeRootSignature(read.root.Get()); + list.native->SetPipelineState(read.pipeline.Get()); + list.native->SetComputeRootDescriptorTable(0, read.srv_heap->GetGPUDescriptorHandleForHeapStart()); + list.native->SetComputeRootUnorderedAccessView(1, read.output->GetGPUVirtualAddress()); + list.native->Dispatch(1, 1, 1); + list.barrier(backing, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE, D3D12_RESOURCE_STATE_COMMON); + list.barrier(read.output.Get(), D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE); + list.native->CopyBufferRegion(read.readback.Get(), 0, read.output.Get(), 0, 8); + list.barrier(read.output.Get(), D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_COMMON); + if (!list.close() || !list.submit()) return false; + + void* mapped = nullptr; + const D3D12_RANGE range{0, 8}; + if (FAILED(read.readback->Map(0, &range, &mapped))) return false; + std::memcpy(values.data(), mapped, 8); + const D3D12_RANGE none{0, 0}; + read.readback->Unmap(0, &none); + return true; +} + +void write_word(std::uint8_t* base, UINT64 offset, std::uint32_t value) +{ + std::memcpy(base + offset, &value, sizeof(value)); +} + +bool resolve_words(Device& device, TitleList& list, const UINT* words, ID3D12Resource** resource, UINT64* offset, + UINT64* bytes, int* source, std::string& reason) +{ + (void)device; + const char* why = nullptr; + const HRESULT hr = x2w_d3d12_mesh86_material_resolve(list.list.Get(), words, resource, offset, bytes, source, &why); + reason = why ? why : ""; + return SUCCEEDED(hr) && *resource; +} + +std::array raw_record(const std::uint8_t* address, UINT64 bytes) +{ + const auto value = reinterpret_cast(address); + return {static_cast(value), static_cast(value >> 32) | (4u << 16), + static_cast(bytes / 4), 0x31016facu, 0, 0, 0, 0}; +} + +} // namespace + +int main(int argc, char** argv) +{ + if (argc != 2) { + std::puts("usage: startup_mesh86_material_backing "); + return 2; + } + const bool warp = std::strcmp(argv[1], "warp") == 0; + if (!warp && std::strcmp(argv[1], "hardware") != 0) return 2; + SetEnvironmentVariableW(L"X2W_D3D12_PERMISSIVE", L"1"); + SetEnvironmentVariableW(L"X2W_D3D12_LIST_NOOP", L"1"); + SetEnvironmentVariableW(L"X2W_D3D12_RENDER", L"1"); + SetEnvironmentVariableW(L"X2W_D3D12_LINEAR_BUFFERS", nullptr); + SetEnvironmentVariableW(L"X2W_D3D12_BUDGET", L"1"); + + Device device; + if (!init_device(warp, device)) { + std::puts(warp ? "WARP device not created" : "no D3D12 hardware adapter"); + return warp ? 1 : 77; + } + + auto* allocation = static_cast(VirtualAlloc(nullptr, allocation_bytes, MEM_RESERVE | MEM_COMMIT, + PAGE_READWRITE)); + if (!allocation) { + std::puts("FAIL: title allocation"); + return 1; + } + std::memset(allocation, 0xa5, allocation_bytes); + std::uint8_t* title = allocation + buffer_offset; + std::memset(title, 0, buffer_bytes); + write_word(title, 0, a0); + write_word(title, second_srv_offset, b0); + + const D3D12_RESOURCE_DESC placed_desc = buffer_desc(buffer_bytes, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS); + ComPtr placed; + using Place = HRESULT(WINAPI*)(IUnknown*, void*, const D3D12_RESOURCE_DESC*, UINT, const void*, REFIID, void**); + const HRESULT placed_hr = slot(device.guest.Get(), 133)( + device.guest.Get(), title, &placed_desc, D3D12_RESOURCE_STATE_COMMON, nullptr, + __uuidof(ID3D12Resource), reinterpret_cast(placed.GetAddressOf())); + check(SUCCEEDED(placed_hr), "slot 133 places the 64 KiB title buffer"); + if (FAILED(placed_hr)) return 1; + ComPtr backing = underlying(device.desktop.Get(), device.guest.Get(), placed.Get()); + check(backing != nullptr, "the placed wrapper has a desktop resource"); + if (!backing) return 1; + x2w_budget::Snapshot placed_budget{}, adopted_budget{}; + check(x2w_d3d12_budget_snapshot(&placed_budget, sizeof(placed_budget)), "budget snapshot before adoption"); + + ComputeRead read; + check(init_read(device, backing.Get(), read), "compute read program and readback"); + if (failures) return 1; + + std::array first_record = raw_record(title, 16); + std::array second_record = raw_record(title + second_srv_offset, 16); + TitleList list; + check(list.begin(device), "open fixture recording"); + if (failures) return 1; + ID3D12Resource* first_resource = nullptr; + ID3D12Resource* second_resource = nullptr; + UINT64 first_offset = 0, first_bytes = 0, second_offset = 0, second_bytes = 0; + int first_source = 0, second_source = 0; + std::string reason; + const bool first_ok = resolve_words(device, list, first_record.data(), &first_resource, &first_offset, &first_bytes, + &first_source, reason); + check(first_ok && first_resource == backing.Get() && first_offset == 0 && first_bytes == 16 && first_source == 4, + "first raw SRV is adopted on the placed backing"); + const bool second_ok = resolve_words(device, list, second_record.data(), &second_resource, &second_offset, + &second_bytes, &second_source, reason); + check(second_ok && second_resource == backing.Get() && second_offset == second_srv_offset && second_bytes == 16 && + second_source == 4, + "second raw SRV names a distinct offset of the same backing"); + if (failures) return 1; + + X2wLinearBufferInfo info{}; + check(x2w_d3d12_linear_buffer_info(placed.Get(), &info) && info.path == 2 && info.adopted == 1 && + info.backing == backing.Get() && info.refusal_hr == S_OK, + "the existing desktop backing is adopted, without a linear placement"); + check(x2w_d3d12_budget_snapshot(&adopted_budget, sizeof(adopted_budget)) && + adopted_budget.live[x2w_budget::buffer].objects == placed_budget.live[x2w_budget::buffer].objects && + adopted_budget.live[x2w_budget::buffer].bytes == placed_budget.live[x2w_budget::buffer].bytes, + "adoption grows no default-heap buffer in the budget"); + std::printf("budget buffer: %llu objects / %llu bytes before and after adoption\n", + static_cast(adopted_budget.live[x2w_budget::buffer].objects), + static_cast(adopted_budget.live[x2w_budget::buffer].bytes)); + X2wLinearBufferTotals before_totals{}; + x2w_d3d12_linear_buffer_totals(&before_totals); + + std::array values{}; + check(record_read(list, read, backing.Get(), values), "first GPU read submits and completes"); + check(values[0] == a0 && values[1] == b0, "two GPU-selected SRVs read distinct first-upload values"); + check(x2w_d3d12_linear_buffer_info(placed.Get(), &info) && info.bytes_copied == buffer_bytes && + info.refreshes >= 1 && info.last_fence != 0, + "first refresh copies the full title range and signals its fence"); + const UINT64 first_copied = info.bytes_copied; + const UINT64 first_staging = info.last_staging; + + write_word(title, 0, c0); + TitleList second_list; + check(second_list.begin(device), "open second recording"); + if (failures) return 1; + ID3D12Resource* again = nullptr; + UINT64 again_offset = 0, again_bytes = 0; + int again_source = 0; + check(resolve_words(device, second_list, first_record.data(), &again, &again_offset, &again_bytes, &again_source, reason) && + again == backing.Get() && again_offset == 0 && again_source == 4, + "second recording reuses the adopted backing"); + check(record_read(second_list, read, backing.Get(), values), "second GPU read submits and completes"); + check(values[0] == c0 && values[1] == b0, "the changed SRV reads its new value and the other keeps its own"); + check(x2w_d3d12_linear_buffer_info(placed.Get(), &info) && info.bytes_copied - first_copied == 4 && + info.last_staging == first_staging, + "the second refresh copies only the four changed bytes and reuses the staging buffer"); + const UINT64 second_copied = info.bytes_copied; + + write_word(title, second_srv_offset, d0); + TitleList third_list; + check(third_list.begin(device), "open third recording"); + if (failures) return 1; + check(resolve_words(device, third_list, second_record.data(), &again, &again_offset, &again_bytes, &again_source, reason), + "third recording resolves the second SRV"); + check(record_read(third_list, read, backing.Get(), values), "third GPU read submits and completes"); + check(values[0] == c0 && values[1] == d0, "the second SRV reads its new value independently"); + check(x2w_d3d12_linear_buffer_info(placed.Get(), &info), "third refresh reports its bytes"); + const UINT64 third_copied = info.bytes_copied; + X2wLinearBufferTotals after_totals{}; + x2w_d3d12_linear_buffer_totals(&after_totals); + check(after_totals.copied == 0 && after_totals.adopted == 1 && + after_totals.bytes_copied == first_copied + 8 && after_totals.consumer_waits >= 1, + "totals report one adopted backing, no second default buffer and fenced consumers"); + check(after_totals.staging_reused >= 2, "staging buffers are reused across submissions"); + + // Two changed words more than one compare block apart: each contiguous run is copied, not the + // span between them. The read sees both the changed first SRV and the unchanged second one. + { + write_word(title, 0, e0); + write_word(title, 0x4000, f0); + X2wLinearBufferInfo before_runs{}; + x2w_d3d12_linear_buffer_info(placed.Get(), &before_runs); + TitleList fourth; + check(fourth.begin(device), "open multi-run recording"); + ID3D12Resource* resource = nullptr; + UINT64 offset = 0, bytes = 0; + int source = 0; + check(resolve_words(device, fourth, first_record.data(), &resource, &offset, &bytes, &source, reason), + "multi-run recording resolves the first SRV"); + check(record_read(fourth, read, backing.Get(), values), "multi-run read submits"); + check(values[0] == e0 && values[1] == d0, "the multi-run read sees both SRV values"); + X2wLinearBufferInfo after_runs{}; + check(x2w_d3d12_linear_buffer_info(placed.Get(), &after_runs) && + after_runs.bytes_copied - before_runs.bytes_copied == 8, + "two disjoint changed words copy two four-byte runs"); + std::printf("material backing: first %llu bytes, one-word change %llu bytes, second one-word change %llu bytes, " + "two disjoint words %llu bytes; adopted %llu, linear placements %llu\n", + static_cast(first_copied), + static_cast(second_copied - first_copied), + static_cast(third_copied - second_copied), + static_cast(after_runs.bytes_copied - before_runs.bytes_copied), + static_cast(after_totals.adopted), + static_cast(after_totals.copied)); + } + + const auto untouched = [&](const std::uint8_t* begin, const std::uint8_t* end) { + for (const std::uint8_t* at = begin; at < end; ++at) + if (*at != 0xa5) return false; + return true; + }; + check(untouched(allocation, title) && untouched(title + buffer_bytes, allocation + allocation_bytes), + "bytes outside the placed range are never read or copied"); + check(std::memcmp(title, &e0, sizeof(e0)) == 0, + "the title bytes used by the GPU views keep their sentinels"); + + TitleList control_list; + check(control_list.begin(device), "open control recording"); + if (failures) return 1; + { + std::array outside = raw_record(title + buffer_bytes - 8, 16); + ID3D12Resource* resource = nullptr; + UINT64 offset = 0, bytes = 0; + int source = 0; + const bool refused = !resolve_words(device, control_list, outside.data(), &resource, &offset, &bytes, &source, reason); + check(refused && reason.find("crosses the end") != std::string::npos, + ("out-of-range record is refused: " + reason).c_str()); + } + { + std::array oversized = raw_record(title, 16); + oversized[2] = 0xffffffffu; + ID3D12Resource* resource = nullptr; + UINT64 offset = 0, bytes = 0; + int source = 0; + const bool refused = !resolve_words(device, control_list, oversized.data(), &resource, &offset, &bytes, &source, reason); + check(refused && reason.find("raw SRV limit") != std::string::npos, + ("oversized record is refused: " + reason).c_str()); + } + { + alignas(64) static UINT table[4096 / 4]{}; + struct { D3D12_DESCRIPTOR_HEAP_DESC desc; UINT64 address, bytes; } heap_desc{ + {D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 128, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE}, + reinterpret_cast(table), sizeof(table)}; + ComPtr heap; + const HRESULT heap_hr = device.guest->CreateDescriptorHeap(&heap_desc.desc, IID_PPV_ARGS(&heap)); + check(SUCCEEDED(heap_hr), "create a guest view heap for the wrong-type control"); + if (SUCCEEDED(heap_hr)) { + using Handle = UINT64(WINAPI*)(IUnknown*); + const UINT64 title_cpu = slot(heap.Get(), 9)(heap.Get()); + auto* token_words = reinterpret_cast(title_cpu); + D3D12_UNORDERED_ACCESS_VIEW_DESC uav{DXGI_FORMAT_R32_TYPELESS, D3D12_UAV_DIMENSION_BUFFER}; + uav.Buffer.NumElements = 4; + uav.Buffer.Flags = D3D12_BUFFER_UAV_FLAG_RAW; + using Uav = void(WINAPI*)(IUnknown*, IUnknown*, IUnknown*, const D3D12_UNORDERED_ACCESS_VIEW_DESC*, UINT64); + slot(device.guest.Get(), 19)(device.guest.Get(), placed.Get(), nullptr, &uav, title_cpu); + ID3D12Resource* resource = nullptr; + UINT64 offset = 0, bytes = 0; + int source = 0; + const bool refused = !resolve_words(device, control_list, token_words, &resource, &offset, &bytes, &source, reason); + check(refused && reason.find("unordered access view") != std::string::npos, + ("wrong-type (UAV) descriptor is refused: " + reason).c_str()); + } + } + { + alignas(64) static UINT table[4096 / 4]{}; + struct { D3D12_DESCRIPTOR_HEAP_DESC desc; UINT64 address, bytes; } heap_desc{ + {D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 128, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE}, + reinterpret_cast(table), sizeof(table)}; + ComPtr heap; + if (SUCCEEDED(device.guest->CreateDescriptorHeap(&heap_desc.desc, IID_PPV_ARGS(&heap)))) { + using Handle = UINT64(WINAPI*)(IUnknown*); + const UINT64 title_cpu = slot(heap.Get(), 9)(heap.Get()); + auto* token_words = reinterpret_cast(title_cpu); + D3D12_SHADER_RESOURCE_VIEW_DESC srv{DXGI_FORMAT_R32_TYPELESS, D3D12_SRV_DIMENSION_BUFFER, + D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING}; + srv.Buffer.NumElements = 4; + srv.Buffer.Flags = D3D12_BUFFER_SRV_FLAG_RAW; + using View = void(WINAPI*)(IUnknown*, IUnknown*, const D3D12_SHADER_RESOURCE_VIEW_DESC*, UINT64); + slot(device.guest.Get(), 18)(device.guest.Get(), placed.Get(), &srv, title_cpu); + placed.Reset(); // the title's final Release retires the placement and the wrapper + ID3D12Resource* resource = nullptr; + UINT64 offset = 0, bytes = 0; + int source = 0; + const bool refused = !resolve_words(device, control_list, token_words, &resource, &offset, &bytes, &source, reason); + check(refused && !reason.empty(), ("released-resource descriptor is refused: " + reason).c_str()); + } + } + + std::printf("startup_mesh86_material_backing %s: %s (%u failed)\n", argv[1], failures ? "FAIL" : "PASS", failures); + return failures ? 1 : 0; +} From f71199638d5da5be9c57effda30f4275f92587fa Mon Sep 17 00:00:00 2001 From: Roland Edi Date: Tue, 1 Dec 2026 11:21:02 +0000 Subject: [PATCH 2/7] tooling: allow-list the placed material backing reason --- tools/startup/triage_run.py | 1 + 1 file changed, 1 insertion(+) diff --git a/tools/startup/triage_run.py b/tools/startup/triage_run.py index 055cb037c4..6f30d735a9 100644 --- a/tools/startup/triage_run.py +++ b/tools/startup/triage_run.py @@ -91,6 +91,7 @@ 'a heap index word is outside its table buffer', "a heap record is outside the list's view heap", 'a null input could not get its zero bytes', + 'a placed material buffer has no coherent desktop backing', 'a raw buffer writer was bound to a non-buffer UAV', 'a raw buffer writer was bound to a non-buffer backing', 'a resource heap range outside the supported layout', From 715b84f07685d8a969c3b2ac158ea405af67a4cc Mon Sep 17 00:00:00 2001 From: Roland Edi Date: Tue, 1 Dec 2026 11:49:43 +0000 Subject: [PATCH 3/7] runtime: fail closed when a material backing was GPU-written before adoption --- docs/experiments/mesh86-pixel-execz.md | 11 ++- src/startup_stubs/linear_buffer_backing.h | 32 +++++++- .../startup_mesh86_material_backing.cmake | 3 + tests/startup_mesh86_material_backing.cpp | 77 ++++++++++++++++++- 4 files changed, 118 insertions(+), 5 deletions(-) diff --git a/docs/experiments/mesh86-pixel-execz.md b/docs/experiments/mesh86-pixel-execz.md index 6d3c579b00..43a1238e89 100644 --- a/docs/experiments/mesh86-pixel-execz.md +++ b/docs/experiments/mesh86-pixel-execz.md @@ -124,14 +124,19 @@ resource. The fixture reports one adopted backing and no linear placement. ```powershell ctest --preset release --no-tests=error -R '^startup_mesh86_material_backing_(warp|hardware)$' --output-on-failure ctest --preset release --no-tests=error -R '^startup_mesh86_material_backing_mutant_(warp|hardware)$' --output-on-failure +ctest --preset release --no-tests=error -R '^startup_mesh86_material_backing_provenance_(warp|hardware)$' --output-on-failure ``` The mutant keeps the bytes visible at adoption; both normal tests must pass and both mutant tests must fail (the CTest entries use `WILL_FAIL`). -Limits. Adoption does not see a GPU write submitted before the first material -bind; only writes recorded on the current recording or tracked through a -submitted copy stop a refresh. The changed-run comparison runs at each submit +A GPU write submitted before the first material bind is remembered by +`note_gpu_write` even when linear-buffer tracking is off; adoption then fails +closed with the named refusal instead of refreshing the GPU bytes from stale +title memory. The provenance control seeds a GPU copy while tracking is off, +resolves the first material view (refused) and verifies the GPU bytes survive. +A write performed outside the shim, for example through a desktop list that +bypasses the copy slots, is still not visible. The changed-run comparison runs at each submit over the whole resource and the first refresh copies it whole, so a 174 MiB resource still costs a 174 MiB compare per submission even when few bytes changed. The fixture measures refresh bytes and the reused backing; it does not diff --git a/src/startup_stubs/linear_buffer_backing.h b/src/startup_stubs/linear_buffer_backing.h index 8c6f234952..5882e5db56 100644 --- a/src/startup_stubs/linear_buffer_backing.h +++ b/src/startup_stubs/linear_buffer_backing.h @@ -190,6 +190,7 @@ #include #include #include +#include #include #include "startup_stubs/linear_buffer_report.h" @@ -447,6 +448,16 @@ class LinearBuffers { const auto desc = resource->GetDesc(); if (desc.Dimension != D3D12_RESOURCE_DIMENSION_BUFFER || bytes > desc.Width) return E_INVALIDARG; std::lock_guard lock(mutex_); + // A submitted GPU write on a backing that was not tracked yet makes its desktop bytes + // authoritative; refreshing it from title memory would overwrite them. Fail closed. + if (untracked_gpu_write_overflow_ || untracked_gpu_writes_.count(resource)) { + if (report) { + report->path = kept_default_path; + report->refusal_hr = E_INVALIDARG; + report->backing = resource; + } + return E_INVALIDARG; + } if (const auto found = records_.find(resource); found != records_.end()) { if (found->second.info.path == shared_path) { if (report) *report = found->second.info; @@ -535,7 +546,21 @@ class LinearBuffers { if (linear_detail::mutant("refresh-gpu-written")) return; std::lock_guard lock(mutex_); const auto found = records_.find(resource); - if (found == records_.end() || !found->second.copy || found->second.copy->gpu_written) return; + if (found == records_.end() || !found->second.copy) { + // The backing is not tracked yet. Remember the submitted write so a later adoption + // refuses instead of refreshing the GPU's bytes from stale title memory. + if (untracked_gpu_writes_.size() >= (1u << 16)) { + untracked_gpu_write_overflow_ = true; + } else { + try { + untracked_gpu_writes_.insert(resource); + } catch (const std::bad_alloc&) { + untracked_gpu_write_overflow_ = true; + } + } + return; + } + if (found->second.copy->gpu_written) return; found->second.copy->gpu_written = true; ++totals_.gpu_written; if (x2w_local::first_calls(gpu_write_logged_, 8)) @@ -548,6 +573,7 @@ class LinearBuffers { { std::lock_guard lock(mutex_); records_.erase(resource); + untracked_gpu_writes_.erase(resource); } // The title released the resource: its memory is not read again. The desktop backing stays (as @@ -555,6 +581,7 @@ class LinearBuffers { void retire(ID3D12Resource* resource) { std::lock_guard lock(mutex_); + untracked_gpu_writes_.erase(resource); const auto found = records_.find(resource); if (found == records_.end() || !found->second.copy) return; found->second.copy->live = false; @@ -1363,6 +1390,9 @@ class LinearBuffers { std::mutex mutex_; std::unordered_map records_; + // Submitted GPU writes on a resource without a tracked backing: a later adoption must fail closed. + std::unordered_set untracked_gpu_writes_; + bool untracked_gpu_write_overflow_ = false; std::mutex internal_mutex_; // the internal queue's ExecuteCommandLists and Signal, in value order ID3D12Device* internal_device_ = nullptr; ID3D12CommandQueue* internal_queue_ = nullptr; diff --git a/tests/cmake/startup_mesh86_material_backing.cmake b/tests/cmake/startup_mesh86_material_backing.cmake index d7adf9ade5..9d1776fae7 100644 --- a/tests/cmake/startup_mesh86_material_backing.cmake +++ b/tests/cmake/startup_mesh86_material_backing.cmake @@ -14,4 +14,7 @@ foreach(backend IN ITEMS warp hardware) set_tests_properties(startup_mesh86_material_backing_mutant_${backend} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 WILL_FAIL TRUE ENVIRONMENT "X2W_D3D12_PERMISSIVE=1;X2W_D3D12_LIST_NOOP=1;X2W_D3D12_RENDER=1;X2W_TEST_LINEAR_BUFFER_MUTANT=skip-refresh") + add_test(NAME startup_mesh86_material_backing_provenance_${backend} COMMAND startup_mesh86_material_backing ${backend}) + set_tests_properties(startup_mesh86_material_backing_provenance_${backend} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 + ENVIRONMENT "X2W_D3D12_PERMISSIVE=1;X2W_D3D12_LIST_NOOP=1;X2W_D3D12_RENDER=1;X2W_TEST_LINEAR_BUFFER_PROVENANCE=1") endforeach() diff --git a/tests/startup_mesh86_material_backing.cpp b/tests/startup_mesh86_material_backing.cpp index 132b265fbd..9b2d894b99 100644 --- a/tests/startup_mesh86_material_backing.cpp +++ b/tests/startup_mesh86_material_backing.cpp @@ -179,6 +179,14 @@ struct TitleList { native->ResourceBarrier(1, &barrier); } + void guest_barrier(ID3D12Resource* resource, D3D12_RESOURCE_STATES before, D3D12_RESOURCE_STATES after) + { + D3D12_RESOURCE_BARRIER barrier{}; + barrier.Transition = {resource, D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, before, after}; + using Barrier = void (WINAPI*)(IUnknown*, UINT, const D3D12_RESOURCE_BARRIER*); + slot(list.Get(), 26)(list.Get(), 1, &barrier); + } + bool close() { return SUCCEEDED(static_cast(invoke(list.Get(), 9))); } bool submit() @@ -336,11 +344,13 @@ int main(int argc, char** argv) write_word(title, 0, a0); write_word(title, second_srv_offset, b0); + const bool provenance = GetEnvironmentVariableA("X2W_TEST_LINEAR_BUFFER_PROVENANCE", nullptr, 0) != 0; const D3D12_RESOURCE_DESC placed_desc = buffer_desc(buffer_bytes, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS); ComPtr placed; using Place = HRESULT(WINAPI*)(IUnknown*, void*, const D3D12_RESOURCE_DESC*, UINT, const void*, REFIID, void**); const HRESULT placed_hr = slot(device.guest.Get(), 133)( - device.guest.Get(), title, &placed_desc, D3D12_RESOURCE_STATE_COMMON, nullptr, + device.guest.Get(), title, &placed_desc, + provenance ? D3D12_RESOURCE_STATE_COPY_DEST : D3D12_RESOURCE_STATE_COMMON, nullptr, __uuidof(ID3D12Resource), reinterpret_cast(placed.GetAddressOf())); check(SUCCEEDED(placed_hr), "slot 133 places the 64 KiB title buffer"); if (FAILED(placed_hr)) return 1; @@ -364,6 +374,71 @@ int main(int argc, char** argv) UINT64 first_offset = 0, first_bytes = 0, second_offset = 0, second_bytes = 0; int first_source = 0, second_source = 0; std::string reason; + if (provenance) { + // A submitted GPU write precedes the first material bind while linear tracking is off. + // Its desktop bytes are authoritative; adoption must fail closed and leave them intact. + const D3D12_HEAP_PROPERTIES default_heap{D3D12_HEAP_TYPE_DEFAULT}; + const auto source_desc = buffer_desc(sizeof(d0), D3D12_RESOURCE_FLAG_NONE); + ComPtr source; + check(SUCCEEDED(device.guest->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &source_desc, + D3D12_RESOURCE_STATE_COMMON, nullptr, IID_PPV_ARGS(&source))), "provenance source buffer"); + if (failures) return 1; + ComPtr source_native = + underlying(device.desktop.Get(), device.guest.Get(), source.Get()); + check(source_native != nullptr, "provenance source has a desktop resource"); + if (failures) return 1; + const D3D12_HEAP_PROPERTIES upload_heap{D3D12_HEAP_TYPE_UPLOAD}; + ComPtr upload; + check(SUCCEEDED(device.desktop->CreateCommittedResource(&upload_heap, D3D12_HEAP_FLAG_NONE, &source_desc, + D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, IID_PPV_ARGS(&upload))), "provenance upload resource"); + if (failures) return 1; + const D3D12_RANGE empty_range{}; + void* mapped = nullptr; + check(SUCCEEDED(upload->Map(0, &empty_range, &mapped)), "map provenance upload"); + if (failures) return 1; + std::memcpy(mapped, &d0, sizeof(d0)); + upload->Unmap(0, nullptr); + TitleList seed; + check(seed.begin(device), "open provenance seed recording"); + if (failures) return 1; + D3D12_RESOURCE_BARRIER transition{}; + transition.Transition = {source_native.Get(), D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, + D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_DEST}; + seed.native->ResourceBarrier(1, &transition); + seed.native->CopyBufferRegion(source_native.Get(), 0, upload.Get(), 0, sizeof(d0)); + transition.Transition = {source_native.Get(), D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, + D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_COMMON}; + seed.native->ResourceBarrier(1, &transition); + check(seed.close() && seed.submit(), "seed the provenance source"); + if (failures) return 1; + TitleList copy_list; + check(copy_list.begin(device), "open provenance copy recording"); + if (failures) return 1; + using Copy = void (WINAPI*)(IUnknown*, IUnknown*, UINT64, IUnknown*, UINT64, UINT64); + slot(copy_list.list.Get(), 15)(copy_list.list.Get(), placed.Get(), 0, source.Get(), 0, sizeof(d0)); + transition.Transition = {backing.Get(), D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, + D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_COMMON}; + copy_list.native->ResourceBarrier(1, &transition); + check(copy_list.close() && copy_list.submit(), "submit the provenance GPU write"); + if (failures) return 1; + ID3D12Resource* resolved = nullptr; + UINT64 resolved_offset = 0, resolved_bytes = 0; + int resolved_source = 0; + const bool refused = !resolve_words(device, list, first_record.data(), &resolved, &resolved_offset, + &resolved_bytes, &resolved_source, reason); + check(refused, "a GPU-written backing refuses its first adoption"); + std::printf("provenance refusal: %s\n", reason.c_str()); + check(reason.find("no coherent desktop backing") != std::string::npos, + "the refusal names the missing coherent backing"); + std::array provenance_values{}; + TitleList read_list; + check(read_list.begin(device) && record_read(read_list, read, backing.Get(), provenance_values), + "read the GPU-written backing after the refusal"); + std::printf("provenance values: %08x %08x\n", provenance_values[0], provenance_values[1]); + check(provenance_values[0] == d0 && provenance_values[1] == 0, + "the submitted GPU bytes survive the refused adoption"); + return failures ? 1 : 0; + } const bool first_ok = resolve_words(device, list, first_record.data(), &first_resource, &first_offset, &first_bytes, &first_source, reason); check(first_ok && first_resource == backing.Get() && first_offset == 0 && first_bytes == 16 && first_source == 4, From 617b5d1f4ee92593de4600d3dd7893f8e27dcbe3 Mon Sep 17 00:00:00 2001 From: Roland Edi Date: Wed, 2 Dec 2026 01:18:35 +0000 Subject: [PATCH 4/7] runtime: bind whole dwords for byte Mesh86 material descriptors --- src/startup_stubs/d3d12_draw.inl | 7 ++++++- tests/startup_mesh86_material_backing.cpp | 25 +++++++++++++++++++++++ 2 files changed, 31 insertions(+), 1 deletion(-) diff --git a/src/startup_stubs/d3d12_draw.inl b/src/startup_stubs/d3d12_draw.inl index d4b19464ff..3d14d0e210 100644 --- a/src/startup_stubs/d3d12_draw.inl +++ b/src/startup_stubs/d3d12_draw.inl @@ -2862,7 +2862,12 @@ IndirectBufferView indirect_table_buffer(Wrapper* self, const std::uint32_t* wor if (!bytes) return refuse("an input buffer descriptor has zero records"); if (use == InputBufferUse::mesh86_material) { if (bytes > limit) return refuse("material buffer size exceeds the D3D12 raw SRV limit"); - if (bytes % 4) return refuse("material buffer size is not a whole number of dwords"); + // A material descriptor can be a byte view (stride 1). The material path builds a raw + // dword SRV, so bind the whole dwords the view covers; a tail smaller than one dword is + // not addressable by that SRV. The caller still checks the view against the shader's + // minimum read. + bytes &= ~u64{3}; + if (!bytes) return refuse("material buffer range has no whole dwords"); } else if (bytes > limit || bytes % 4) { return refuse(limit == (16u << 20) ? "an input buffer range is over 16 MiB or not whole dwords" diff --git a/tests/startup_mesh86_material_backing.cpp b/tests/startup_mesh86_material_backing.cpp index 9b2d894b99..cc71cfc4e2 100644 --- a/tests/startup_mesh86_material_backing.cpp +++ b/tests/startup_mesh86_material_backing.cpp @@ -310,6 +310,13 @@ std::array raw_record(const std::uint8_t* address, UINT64 bytes) static_cast(bytes / 4), 0x31016facu, 0, 0, 0, 0}; } +std::array byte_record(const std::uint8_t* address, UINT64 bytes) +{ + const auto value = reinterpret_cast(address); + return {static_cast(value), static_cast(value >> 32) | (1u << 16), + static_cast(bytes), 0x31016facu, 0, 0, 0, 0}; +} + } // namespace int main(int argc, char** argv) @@ -448,6 +455,24 @@ int main(int argc, char** argv) check(second_ok && second_resource == backing.Get() && second_offset == second_srv_offset && second_bytes == 16 && second_source == 4, "second raw SRV names a distinct offset of the same backing"); + { + std::array byte_view = byte_record(title, 18); + ID3D12Resource* resource = nullptr; + UINT64 offset = 0, bytes = 0; + int source = 0; + const bool ok = resolve_words(device, list, byte_view.data(), &resource, &offset, &bytes, &source, reason); + check(ok && resource == backing.Get() && offset == 0 && bytes == 16, + ("an 18-byte material descriptor binds as four dwords: " + reason).c_str()); + } + { + std::array byte_view = byte_record(title, 3); + ID3D12Resource* resource = nullptr; + UINT64 offset = 0, bytes = 0; + int source = 0; + const bool refused = !resolve_words(device, list, byte_view.data(), &resource, &offset, &bytes, &source, reason); + check(refused && reason.find("no whole dwords") != std::string::npos, + ("a three-byte material descriptor is refused: " + reason).c_str()); + } if (failures) return 1; X2wLinearBufferInfo info{}; From 2e49817f08fa4ecab71311d398e6b30c81170850 Mon Sep 17 00:00:00 2001 From: Roland Edi Date: Wed, 2 Dec 2026 01:39:39 +0000 Subject: [PATCH 5/7] tests: refresh the Mesh86 standin export count --- tests/standin_exports_check.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/tests/standin_exports_check.py b/tests/standin_exports_check.py index 53031b94a0..0ecd33cc5b 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": 80, "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": 45}), "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 0839ddcc50632b92ea56fb8b869c02ca038de2cd Mon Sep 17 00:00:00 2001 From: Roland Edi Date: Wed, 2 Dec 2026 11:44:29 +0000 Subject: [PATCH 6/7] runtime: align material buffer use with main --- src/startup_stubs/d3d12_draw.inl | 4 ++-- src/startup_stubs/d3d12_xs_device.cpp | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/startup_stubs/d3d12_draw.inl b/src/startup_stubs/d3d12_draw.inl index c8b4520107..25e4de5341 100644 --- a/src/startup_stubs/d3d12_draw.inl +++ b/src/startup_stubs/d3d12_draw.inl @@ -3009,9 +3009,9 @@ IndirectBufferView indirect_table_buffer(Wrapper* self, const std::uint32_t* wor if (!placed.alias) { if (native && indirect_table_copied_gpu_range(self, native, offset, bytes)) { input_source = 1; // a GPU copy of this list filled the range: the GPU buffer is the truth - } else if (use == InputBufferUse::mesh86_material && native && linear_buffers().written_by_gpu(native)) { + } else if (use == InputBufferUse::mesh_material && native && linear_buffers().written_by_gpu(native)) { input_source = 1; // a submitted GPU write filled the backing: the desktop bytes are the truth - } else if (use == InputBufferUse::mesh86_material && native) { + } else if (use == InputBufferUse::mesh_material && native) { // The placed backing exists but does not alias title memory. Adopt that same resource: the // linear-buffer path refreshes it from the title bytes before the recording executes, copies // only the changed span after the first refresh, and orders the consumer behind its fence. No diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index f50c8a98ca..0192c1d012 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -9489,7 +9489,7 @@ HRESULT x2w_d3d12_permissive_create_device(IUnknown* adapter, const void* parame } // Fixture-only entry point: resolve one eight-word material table record through the production -// Mesh86 material path (indirect_table_buffer with InputBufferUse::mesh86_material), on an open +// Mesh86 material path (indirect_table_buffer with InputBufferUse::mesh_material), on an open // recording. The fixture can then submit a read of the returned backing through the queue wrapper, // which exercises the refresh and its fences without needing a captured guest shader. extern "C" __declspec(dllexport) HRESULT x2w_d3d12_mesh86_material_resolve( @@ -9506,7 +9506,7 @@ extern "C" __declspec(dllexport) HRESULT x2w_d3d12_mesh86_material_resolve( const char* why = nullptr; const auto view = indirect_table_buffer(self, words, false, &why, u64{4} << D3D12_REQ_BUFFER_RESOURCE_TEXEL_COUNT_2_TO_EXP, D3D12_RAW_UAV_SRV_BYTE_ALIGNMENT, true, false, nullptr, nullptr, nullptr, - InputBufferUse::mesh86_material); + InputBufferUse::mesh_material); *out_resource = view.resource; *out_offset = view.offset; *out_bytes = view.bytes; From 3aeb40f72b793b050510519cfc669b1304a83bc3 Mon Sep 17 00:00:00 2001 From: Roland Edi Date: Wed, 2 Dec 2026 12:05:11 +0000 Subject: [PATCH 7/7] shader: fix mesh interpolation test fixture --- tests/native_direct_mesh_check.py | 11 ++++------- 1 file changed, 4 insertions(+), 7 deletions(-) diff --git a/tests/native_direct_mesh_check.py b/tests/native_direct_mesh_check.py index 3f61b20585..5b2e8ce21d 100644 --- a/tests/native_direct_mesh_check.py +++ b/tests/native_direct_mesh_check.py @@ -868,15 +868,12 @@ def run_offen(name, words, error=None): assert 'TEXCOORD' in text and 'COLOR' in text, text # A DXIL row has one interpolation mode. A float packed beside an # integer is constant; a float beside another float stays linear. - body[io + 0xc8:io + 0xce] = bytes((6, 1, 0, 0, 0, 0)) - code = isa_words(*program[:11], 0xf80000cf, program[12], - 0xf8000203, program[12], *program[13:]) - struct.pack_into('