From 0001bb1544bbb249a30e094279fe29dc6e9d4c9e Mon Sep 17 00:00:00 2001 From: tedin7 Date: Tue, 24 Nov 2026 20:03:48 +0100 Subject: [PATCH 1/9] startup: copy and resolve whole resources on a recording list (slots 15, 17, 19) --- CMakeLists.txt | 20 ++ docs/startup-runtime.md | 13 + src/startup_stubs/d3d12_xs_device.cpp | 5 + src/startup_stubs/list_copy.h | 195 +++++++++++++++ src/startup_stubs/list_copy.inl | 108 +++++++++ tests/startup_list_copy.cpp | 327 ++++++++++++++++++++++++++ tests/startup_list_copy_check.cpp | 136 +++++++++++ 7 files changed, 804 insertions(+) create mode 100644 src/startup_stubs/list_copy.h create mode 100644 src/startup_stubs/list_copy.inl create mode 100644 tests/startup_list_copy.cpp create mode 100644 tests/startup_list_copy_check.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 7078fc9610..c0fd85de2e 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1124,6 +1124,26 @@ foreach(backend IN ITEMS warp hardware) ENVIRONMENT "X2W_D3D12_PERMISSIVE=1;X2W_D3D12_LIST_NOOP=1;X2W_D3D12_RENDER=1;X2W_D3D12_DEBUG=1") endforeach() +# CopyResource, ResolveSubresource and CopyBufferRegion on a recording list (slots 17, 19 and 15). +add_executable(startup_list_copy tests/startup_list_copy.cpp) +target_compile_features(startup_list_copy PRIVATE cxx_std_17) +target_link_libraries(startup_list_copy PRIVATE d3d12_xs_shim d3d12 dxgi) +foreach(backend IN ITEMS warp hardware) + add_test(NAME startup_list_copy_${backend} COMMAND startup_list_copy ${backend}) + set_tests_properties(startup_list_copy_${backend} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 + ENVIRONMENT "X2W_D3D12_PERMISSIVE=1;X2W_D3D12_LIST_NOOP=1;X2W_D3D12_RENDER=1;X2W_D3D12_DEBUG=1") +endforeach() + +# Validation of the whole-resource copies (src/startup_stubs/list_copy.h); the mutated runs are negative controls. +add_executable(startup_list_copy_check tests/startup_list_copy_check.cpp) +target_include_directories(startup_list_copy_check PRIVATE src) +target_compile_features(startup_list_copy_check PRIVATE cxx_std_17) +add_test(NAME startup_list_copy_validation COMMAND startup_list_copy_check) +foreach(mutation IN ITEMS overflow typeless samples) + add_test(NAME startup_list_copy_validation_${mutation}_control COMMAND startup_list_copy_check --mutate ${mutation}) + set_tests_properties(startup_list_copy_validation_${mutation}_control PROPERTIES WILL_FAIL TRUE) +endforeach() + add_executable(startup_nv12_draw tests/startup_nv12_draw.cpp tests/desktop_gpu.cpp) target_compile_features(startup_nv12_draw PRIVATE cxx_std_17) target_include_directories(startup_nv12_draw PRIVATE src) diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index a34410adee..0ab507976f 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -419,6 +419,19 @@ inside the range, an empty view alone) and reads the counters through the `x2w_d then copies a view into an empty slot, clears the copy red and reads the target back. It does not draw. The export reads the same counters the totals line prints. +Command-list slots 15 (`CopyBufferRegion`), 17 (`CopyResource`) and 19 (`ResolveSubresource`), unshifted like slots 12 to 25, +copy whole resources in render mode (`src/startup_stubs/list_copy.inl`; the checks are in `list_copy.h`). Each argument is +mapped to its desktop resource, the pair is moved to the copy or resolve states for the call and back to COMMON at Close +(an upload buffer stays readable and a readback buffer stays a copy destination), and the call is forwarded. A call the +desktop would reject is counted, logged (first six) and not forwarded, with the reason: `unresolved`, `same_resource`, +`not_buffer`, `not_texture`, `dimension_mismatch`, `size_mismatch`, `format_mismatch`, `sample_mismatch`, +`bad_subresource`, `source_not_multisampled`, `destination_multisampled`, `bad_format`, `zero_size` or +`range_overflow`. A typeless resolve format (or an unknown one over a typeless source) resolves as the family's typed +choice: half float for `R16G16B16A16`, normalised for the 8-bit and 10-bit families. Calls on a closed list are ignored. +These slots have not been seen in a title log yet. `CopyTextureRegion` (16) and `CopyTiles` (18) are not handled. +`ctest -R '^startup_list_copy_validation'` runs the pure checks on any host; `startup_list_copy_{warp,hardware}` copies, +resolves and reads back through the `x2w_d3d12_list_copy_stats` export. + ## Composite provenance fixture Issue #1628 asks whether a uniform colour left in a composite's destination came from the composite or was diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index 9a33dcfe5d..9e38a276e6 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -35,6 +35,7 @@ #include "startup_stubs/memory_srv_report.h" #include "startup_stubs/memory_srv_buffer.h" #include "startup_stubs/single_element_srv.h" +#include "startup_stubs/list_copy.h" #include "startup_stubs/slice_footprints.h" #include "startup_stubs/present_signature_sampler.h" @@ -3404,6 +3405,7 @@ HRESULT __stdcall device_place_resource_x(Wrapper* self, void* address, const D3 } #include "d3d12_memory_srv.inl" +#include "startup_stubs/list_copy.inl" // The title exports __XMemAllocationHooks__ = {alloc(size, attributes), free(ptr, attributes), ...}. // Its alloc routine selects a hook chain by allocatorId (attribute bits 16-23). Around the creation @@ -4081,6 +4083,9 @@ void build_tables() if (render_mode()) { list_typed[9] = reinterpret_cast(&list_close); list_typed[52] = reinterpret_cast(&list_clear_target); + list_typed[15] = reinterpret_cast(&list_copy_buffer_region); + list_typed[17] = reinterpret_cast(&list_copy_resource); + list_typed[19] = reinterpret_cast(&list_resolve_subresource); list_typed[139] = reinterpret_cast(&list_reset); list_typed[148] = reinterpret_cast(&list_allocate_upload); list_typed[12] = reinterpret_cast(&list_draw); diff --git a/src/startup_stubs/list_copy.h b/src/startup_stubs/list_copy.h new file mode 100644 index 0000000000..42be90fd30 --- /dev/null +++ b/src/startup_stubs/list_copy.h @@ -0,0 +1,195 @@ +// Pure validation for the whole-resource command-list copies: CopyBufferRegion (list slot 15), +// CopyResource (17) and ResolveSubresource (19). It reads only resource descriptions, so it runs on any host. +// +// Desktop D3D12 removes the device on a copy it rejects, so a copy whose arguments the desktop would +// refuse is named and skipped instead of forwarded. Each check returns the first refusal, in the +// order listed in CopyRefusal. +#pragma once + +#include + +#include +#include + +namespace x2w_startup { + +enum class CopyRefusal { + none, + unresolved, // a null argument, or one that is not a resource + same_resource, // source and destination are one resource + not_buffer, // CopyBufferRegion on a texture + not_texture, // ResolveSubresource on something other than a 2D texture + dimension_mismatch, // CopyResource between different resource dimensions + size_mismatch, // different width, height, depth, mips or buffer size + format_mismatch, // formats that are neither equal nor members of one typeless family + sample_mismatch, // different sample count or quality + bad_subresource, // a subresource index outside the texture, or of another size + source_not_multisampled, // the resolve source has one sample + destination_multisampled, // the resolve destination has more than one sample + bad_format, // a resolve format that is unknown, or typeless with no typed choice + zero_size, // CopyBufferRegion of no bytes + range_overflow, // an offset and size that wrap, or run past a buffer +}; + +inline const char* copy_refusal_name(CopyRefusal refusal) +{ + switch (refusal) { + case CopyRefusal::unresolved: return "unresolved"; + case CopyRefusal::same_resource: return "same_resource"; + case CopyRefusal::not_buffer: return "not_buffer"; + case CopyRefusal::not_texture: return "not_texture"; + case CopyRefusal::dimension_mismatch: return "dimension_mismatch"; + case CopyRefusal::size_mismatch: return "size_mismatch"; + case CopyRefusal::format_mismatch: return "format_mismatch"; + case CopyRefusal::sample_mismatch: return "sample_mismatch"; + case CopyRefusal::bad_subresource: return "bad_subresource"; + case CopyRefusal::source_not_multisampled: return "source_not_multisampled"; + case CopyRefusal::destination_multisampled: return "destination_multisampled"; + case CopyRefusal::bad_format: return "bad_format"; + case CopyRefusal::zero_size: return "zero_size"; + case CopyRefusal::range_overflow: return "range_overflow"; + default: return "none"; + } +} + +// The typeless member of the colour format family `format` belongs to; `format` itself when it has none. +inline DXGI_FORMAT format_family(DXGI_FORMAT format) +{ + switch (format) { + case DXGI_FORMAT_R32G32B32A32_TYPELESS: case DXGI_FORMAT_R32G32B32A32_FLOAT: + case DXGI_FORMAT_R32G32B32A32_UINT: case DXGI_FORMAT_R32G32B32A32_SINT: + return DXGI_FORMAT_R32G32B32A32_TYPELESS; + case DXGI_FORMAT_R16G16B16A16_TYPELESS: case DXGI_FORMAT_R16G16B16A16_FLOAT: + case DXGI_FORMAT_R16G16B16A16_UNORM: case DXGI_FORMAT_R16G16B16A16_UINT: + case DXGI_FORMAT_R16G16B16A16_SNORM: case DXGI_FORMAT_R16G16B16A16_SINT: + return DXGI_FORMAT_R16G16B16A16_TYPELESS; + case DXGI_FORMAT_R10G10B10A2_TYPELESS: case DXGI_FORMAT_R10G10B10A2_UNORM: case DXGI_FORMAT_R10G10B10A2_UINT: + return DXGI_FORMAT_R10G10B10A2_TYPELESS; + case DXGI_FORMAT_R8G8B8A8_TYPELESS: case DXGI_FORMAT_R8G8B8A8_UNORM: case DXGI_FORMAT_R8G8B8A8_UNORM_SRGB: + case DXGI_FORMAT_R8G8B8A8_UINT: case DXGI_FORMAT_R8G8B8A8_SNORM: case DXGI_FORMAT_R8G8B8A8_SINT: + return DXGI_FORMAT_R8G8B8A8_TYPELESS; + case DXGI_FORMAT_B8G8R8A8_TYPELESS: case DXGI_FORMAT_B8G8R8A8_UNORM: case DXGI_FORMAT_B8G8R8A8_UNORM_SRGB: + return DXGI_FORMAT_B8G8R8A8_TYPELESS; + case DXGI_FORMAT_R16G16_TYPELESS: case DXGI_FORMAT_R16G16_FLOAT: case DXGI_FORMAT_R16G16_UNORM: + case DXGI_FORMAT_R16G16_UINT: case DXGI_FORMAT_R16G16_SNORM: case DXGI_FORMAT_R16G16_SINT: + return DXGI_FORMAT_R16G16_TYPELESS; + case DXGI_FORMAT_R32_TYPELESS: case DXGI_FORMAT_R32_FLOAT: case DXGI_FORMAT_R32_UINT: case DXGI_FORMAT_R32_SINT: + return DXGI_FORMAT_R32_TYPELESS; + default: + return format; + } +} + +// The typed format a typeless one resolves as; DXGI_FORMAT_UNKNOWN for a format that is not typeless or has no +// single natural choice. Floating point for the HDR families, normalised for the 8 and 10 bit ones. +inline DXGI_FORMAT typed_choice(DXGI_FORMAT typeless) +{ + switch (typeless) { + case DXGI_FORMAT_R32G32B32A32_TYPELESS: return DXGI_FORMAT_R32G32B32A32_FLOAT; + case DXGI_FORMAT_R16G16B16A16_TYPELESS: return DXGI_FORMAT_R16G16B16A16_FLOAT; + case DXGI_FORMAT_R10G10B10A2_TYPELESS: return DXGI_FORMAT_R10G10B10A2_UNORM; + case DXGI_FORMAT_R8G8B8A8_TYPELESS: return DXGI_FORMAT_R8G8B8A8_UNORM; + case DXGI_FORMAT_B8G8R8A8_TYPELESS: return DXGI_FORMAT_B8G8R8A8_UNORM; + case DXGI_FORMAT_R16G16_TYPELESS: return DXGI_FORMAT_R16G16_FLOAT; + case DXGI_FORMAT_R32_TYPELESS: return DXGI_FORMAT_R32_FLOAT; + default: return DXGI_FORMAT_UNKNOWN; + } +} + +inline bool is_typeless(DXGI_FORMAT format) +{ + switch (format) { + case DXGI_FORMAT_R32G32B32A32_TYPELESS: case DXGI_FORMAT_R32G32B32_TYPELESS: case DXGI_FORMAT_R16G16B16A16_TYPELESS: + case DXGI_FORMAT_R32G32_TYPELESS: case DXGI_FORMAT_R32G8X24_TYPELESS: case DXGI_FORMAT_R10G10B10A2_TYPELESS: + case DXGI_FORMAT_R8G8B8A8_TYPELESS: case DXGI_FORMAT_R16G16_TYPELESS: case DXGI_FORMAT_R32_TYPELESS: + case DXGI_FORMAT_R24G8_TYPELESS: case DXGI_FORMAT_R8G8_TYPELESS: case DXGI_FORMAT_R16_TYPELESS: + case DXGI_FORMAT_R8_TYPELESS: case DXGI_FORMAT_B8G8R8A8_TYPELESS: case DXGI_FORMAT_B8G8R8X8_TYPELESS: + return true; + default: + return false; + } +} + +inline bool is_typeless_choice_format(DXGI_FORMAT format) { return typed_choice(format) != DXGI_FORMAT_UNKNOWN; } + +inline bool compatible_formats(DXGI_FORMAT a, DXGI_FORMAT b) +{ + return a == b || (a != DXGI_FORMAT_UNKNOWN && format_family(a) == format_family(b)); +} + +// CopyBufferRegion(destination, destination_offset, source, source_offset, bytes). `same` is true when both +// arguments are one resource (it would need two states at once). +inline CopyRefusal check_copy_buffer_region(const D3D12_RESOURCE_DESC* destination, std::uint64_t destination_offset, + const D3D12_RESOURCE_DESC* source, std::uint64_t source_offset, + std::uint64_t bytes, bool same) +{ + if (!destination || !source) return CopyRefusal::unresolved; + if (same) return CopyRefusal::same_resource; + if (destination->Dimension != D3D12_RESOURCE_DIMENSION_BUFFER || source->Dimension != D3D12_RESOURCE_DIMENSION_BUFFER) + return CopyRefusal::not_buffer; + if (!bytes) return CopyRefusal::zero_size; + if (destination_offset > destination->Width || bytes > destination->Width - destination_offset || + source_offset > source->Width || bytes > source->Width - source_offset) + return CopyRefusal::range_overflow; + return CopyRefusal::none; +} + +// CopyResource(destination, source): the two descriptions must have one shape. +inline CopyRefusal check_copy_resource(const D3D12_RESOURCE_DESC* destination, const D3D12_RESOURCE_DESC* source, bool same) +{ + if (!destination || !source) return CopyRefusal::unresolved; + if (same) return CopyRefusal::same_resource; + if (destination->Dimension == D3D12_RESOURCE_DIMENSION_UNKNOWN || destination->Dimension != source->Dimension) + return CopyRefusal::dimension_mismatch; + if (destination->Width != source->Width) return CopyRefusal::size_mismatch; + if (destination->Dimension == D3D12_RESOURCE_DIMENSION_BUFFER) return CopyRefusal::none; + if (destination->Height != source->Height || destination->DepthOrArraySize != source->DepthOrArraySize || + destination->MipLevels != source->MipLevels) + return CopyRefusal::size_mismatch; + if (!compatible_formats(destination->Format, source->Format)) return CopyRefusal::format_mismatch; + if (destination->SampleDesc.Count != source->SampleDesc.Count || destination->SampleDesc.Quality != source->SampleDesc.Quality) + return CopyRefusal::sample_mismatch; + return CopyRefusal::none; +} + +struct ResolvePlan { + CopyRefusal refusal{}; + DXGI_FORMAT format{}; // the typed format to resolve as, when not refused +}; + +// One mip of a 2D texture: its size in texels. +inline std::uint64_t mip_extent(std::uint64_t extent, std::uint32_t mip) { return (std::max)(extent >> mip, 1); } + +// ResolveSubresource(destination, destination_subresource, source, source_subresource, format). A typeless +// `format` (or one the title left unknown over a typeless surface) resolves as the family's typed choice, so a +// half-float surface stored as typeless resolves as half float. +inline ResolvePlan plan_resolve(const D3D12_RESOURCE_DESC* destination, std::uint32_t destination_subresource, + const D3D12_RESOURCE_DESC* source, std::uint32_t source_subresource, DXGI_FORMAT format, + bool same) +{ + if (!destination || !source) return {CopyRefusal::unresolved, {}}; + if (same) return {CopyRefusal::same_resource, {}}; + if (destination->Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D || source->Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D) + return {CopyRefusal::not_texture, {}}; + if (source->SampleDesc.Count <= 1) return {CopyRefusal::source_not_multisampled, {}}; + if (destination->SampleDesc.Count != 1) return {CopyRefusal::destination_multisampled, {}}; + const std::uint32_t destination_mips = destination->MipLevels ? destination->MipLevels : 1; + const std::uint32_t source_mips = source->MipLevels ? source->MipLevels : 1; + if (destination_subresource >= std::uint64_t{destination_mips} * destination->DepthOrArraySize || + source_subresource >= std::uint64_t{source_mips} * source->DepthOrArraySize) + return {CopyRefusal::bad_subresource, {}}; + const std::uint32_t destination_mip = destination_subresource % destination_mips; + const std::uint32_t source_mip = source_subresource % source_mips; + if (mip_extent(destination->Width, destination_mip) != mip_extent(source->Width, source_mip) || + mip_extent(destination->Height, destination_mip) != mip_extent(source->Height, source_mip)) + return {CopyRefusal::bad_subresource, {}}; + DXGI_FORMAT typed = format; + if (typed == DXGI_FORMAT_UNKNOWN) typed = source->Format; + if (is_typeless_choice_format(typed)) typed = typed_choice(typed); + if (typed == DXGI_FORMAT_UNKNOWN || is_typeless(typed)) return {CopyRefusal::bad_format, {}}; + if (!compatible_formats(typed, source->Format) || !compatible_formats(typed, destination->Format)) + return {CopyRefusal::format_mismatch, {}}; + return {CopyRefusal::none, typed}; +} + +} // namespace x2w_startup diff --git a/src/startup_stubs/list_copy.inl b/src/startup_stubs/list_copy.inl new file mode 100644 index 0000000000..c78dcb4635 --- /dev/null +++ b/src/startup_stubs/list_copy.inl @@ -0,0 +1,108 @@ +// Included from d3d12_xs_device.cpp after the command-list state helpers. +// +// Whole-resource copies on a recording list (render mode): CopyBufferRegion (list slot 15), CopyResource +// (17) and ResolveSubresource (19). The title's resources are mapped to desktop ones, the pair is checked +// by src/startup_stubs/list_copy.h, and a pair the desktop would reject is counted and skipped instead of +// forwarded. Desktop resources rest in COMMON between lists, so each is moved to the copy or resolve state +// around the call and back at Close; upload and readback buffers keep the state their heap requires. +// CopyTextureRegion (16) and CopyTiles (18) carry footprints and addresses and are not handled here. + +LONG list_buffer_copies, list_resource_copies, list_resolves, list_copies_refused; + +// The desktop resource behind a copy argument; null for a null value, or a wrapper that is not a resource. +// A value that is no wrapper is taken as a desktop resource, as the view slots do. +ID3D12Resource* copy_endpoint(u64 value) +{ + if (!value) return nullptr; + if (const Wrapper* w = as_wrapper(reinterpret_cast(value))) { + if (w->own().kind != resource_kind) return nullptr; + return static_cast(w->own().real); + } + return x2w_local::readable(reinterpret_cast(value), sizeof(void*)) ? reinterpret_cast(value) : nullptr; +} + +void refuse_copy(const char* what, x2w_startup::CopyRefusal reason) +{ + InterlockedIncrement(&list_copies_refused); + static LONG logged; + if (first_calls(logged, 6)) log("x2w-d3d12 %s skipped: %s", what, x2w_startup::copy_refusal_name(reason)); +} + +// The state a copy needs from `resource`: an upload buffer stays readable and a readback buffer stays a +// copy destination, because desktop allows no other state for them. +void require_copy_state(Wrapper* self, ID3D12Resource* resource, D3D12_RESOURCE_STATES state) +{ + D3D12_HEAP_PROPERTIES heap{}; + D3D12_HEAP_FLAGS flags{}; + if (SUCCEEDED(resource->GetHeapProperties(&heap, &flags)) && + (heap.Type == D3D12_HEAP_TYPE_UPLOAD || heap.Type == D3D12_HEAP_TYPE_READBACK)) + return; + require_state(self, resource, state); +} + +// List slot 15, CopyBufferRegion(destination, destination offset, source, source offset, bytes). +void __stdcall list_copy_buffer_region(Wrapper* self, u64 destination, u64 destination_offset, u64 source, u64 source_offset, + u64 bytes) +{ + if (!self->own().list_open) return; + ID3D12Resource* const to = copy_endpoint(destination); + ID3D12Resource* const from = copy_endpoint(source); + D3D12_RESOURCE_DESC to_desc{}, from_desc{}; + if (to) to_desc = to->GetDesc(); + if (from) from_desc = from->GetDesc(); + const auto refusal = x2w_startup::check_copy_buffer_region(to ? &to_desc : nullptr, destination_offset, + from ? &from_desc : nullptr, source_offset, bytes, to == from); + if (refusal != x2w_startup::CopyRefusal::none) return refuse_copy("CopyBufferRegion", refusal); + require_copy_state(self, from, D3D12_RESOURCE_STATE_COPY_SOURCE); + require_copy_state(self, to, D3D12_RESOURCE_STATE_COPY_DEST); + static_cast(self->own().real)->CopyBufferRegion(to, destination_offset, from, source_offset, bytes); + InterlockedIncrement(&list_buffer_copies); +} + +// List slot 17, CopyResource(destination, source). +void __stdcall list_copy_resource(Wrapper* self, u64 destination, u64 source) +{ + if (!self->own().list_open) return; + ID3D12Resource* const to = copy_endpoint(destination); + ID3D12Resource* const from = copy_endpoint(source); + D3D12_RESOURCE_DESC to_desc{}, from_desc{}; + if (to) to_desc = to->GetDesc(); + if (from) from_desc = from->GetDesc(); + const auto refusal = x2w_startup::check_copy_resource(to ? &to_desc : nullptr, from ? &from_desc : nullptr, to == from); + if (refusal != x2w_startup::CopyRefusal::none) return refuse_copy("CopyResource", refusal); + require_copy_state(self, from, D3D12_RESOURCE_STATE_COPY_SOURCE); + require_copy_state(self, to, D3D12_RESOURCE_STATE_COPY_DEST); + static_cast(self->own().real)->CopyResource(to, from); + InterlockedIncrement(&list_resource_copies); +} + +// List slot 19, ResolveSubresource(destination, destination subresource, source, source subresource, format). +// The format is a console value, mapped like a resource format; a typeless one resolves as its typed choice. +void __stdcall list_resolve_subresource(Wrapper* self, u64 destination, UINT destination_subresource, u64 source, + UINT source_subresource, UINT format) +{ + if (!self->own().list_open) return; + ID3D12Resource* const to = copy_endpoint(destination); + ID3D12Resource* const from = copy_endpoint(source); + D3D12_RESOURCE_DESC to_desc{}, from_desc{}; + if (to) to_desc = to->GetDesc(); + if (from) from_desc = from->GetDesc(); + const auto plan = x2w_startup::plan_resolve(to ? &to_desc : nullptr, destination_subresource, from ? &from_desc : nullptr, + source_subresource, desktop_format(static_cast(format)), to == from); + if (plan.refusal != x2w_startup::CopyRefusal::none) return refuse_copy("ResolveSubresource", plan.refusal); + require_copy_state(self, from, D3D12_RESOURCE_STATE_RESOLVE_SOURCE); + require_copy_state(self, to, D3D12_RESOURCE_STATE_RESOLVE_DEST); + static_cast(self->own().real) + ->ResolveSubresource(to, destination_subresource, from, source_subresource, plan.format); + InterlockedIncrement(&list_resolves); +} + +// Fixtures: how many buffer copies, resource copies and resolves were forwarded, and how many were refused. +extern "C" __declspec(dllexport) void x2w_d3d12_list_copy_stats(unsigned* buffer_copies, unsigned* resource_copies, + unsigned* resolves, unsigned* refused) +{ + if (buffer_copies) *buffer_copies = static_cast(InterlockedCompareExchange(&list_buffer_copies, 0, 0)); + if (resource_copies) *resource_copies = static_cast(InterlockedCompareExchange(&list_resource_copies, 0, 0)); + if (resolves) *resolves = static_cast(InterlockedCompareExchange(&list_resolves, 0, 0)); + if (refused) *refused = static_cast(InterlockedCompareExchange(&list_copies_refused, 0, 0)); +} diff --git a/tests/startup_list_copy.cpp b/tests/startup_list_copy.cpp new file mode 100644 index 0000000000..9e272464c7 --- /dev/null +++ b/tests/startup_list_copy.cpp @@ -0,0 +1,327 @@ +// CopyResource, ResolveSubresource and CopyBufferRegion on a recording list (slots 17, 19 and 15). +// +// startup_list_copy (X2W_D3D12_PERMISSIVE=1 X2W_D3D12_LIST_NOOP=1 X2W_D3D12_RENDER=1 X2W_D3D12_DEBUG=1) +// +// Through D3D12XboxCreateDevice the probe records one list over desktop resources and reads them back on +// a desktop queue: +// +// 1. a 4x4 target cleared red, CopyResource into a second texture second texture is red +// 2. the same copy with source and destination swapped (an empty source into a blue target) +// the empty texture stays empty +// 3. a 4x4 four-sample target cleared green, ResolveSubresource into a one-sample texture green +// 4. the same with a typeless half-float pair and a typeless format argument half float 1.0 in red +// 5. an upload buffer copied to a buffer, then 64 bytes at another offset into a third exact bytes +// 6. refused and counted, forwarded to nothing: a CopyResource between different sizes, a null source, +// a resolve from a one-sample source, a buffer range that runs past its end +// 7. after Close, the same calls change no counter +// +// The desktop device must not be removed and the debug layer must store no errors. +// +// Exit codes: 0 pass, 77 no physical adapter, other values name the failing step. +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +using Microsoft::WRL::ComPtr; +extern "C" __declspec(dllimport) HRESULT WINAPI D3D12XboxCreateDevice(IUnknown*, const void*, REFIID, void**); +extern "C" __declspec(dllimport) void x2w_d3d12_list_copy_stats(unsigned* buffer_copies, unsigned* resource_copies, + unsigned* resolves, unsigned* refused); + +namespace { +using Word = std::uint64_t; +template Word arg(T* value) { return reinterpret_cast(value); } +Word invoke(void* object, unsigned index, Word a = 0, Word b = 0, Word c = 0, Word d = 0, Word e = 0, Word f = 0, Word g = 0) +{ + using Slot = Word (WINAPI*)(void*, Word, Word, Word, Word, Word, Word, Word); + return reinterpret_cast((*static_cast(object))[index])(object, a, b, c, d, e, f, g); +} +bool ok(Word hr) { return SUCCEEDED(static_cast(hr)); } + +constexpr float red[] = {1, 0, 0, 1}; +constexpr float green[] = {0, 1, 0, 1}; +constexpr float blue[] = {0, 0, 1, 1}; +constexpr std::uint32_t red_bits = 0xff0000ff; +constexpr std::uint32_t green_bits = 0xff00ff00; +constexpr std::uint32_t half_one = 0x3c00; + +struct Counts { + unsigned buffers = 0, resources = 0, resolves = 0, refused = 0; + static Counts read() + { + Counts c; + x2w_d3d12_list_copy_stats(&c.buffers, &c.resources, &c.resolves, &c.refused); + return c; + } +}; + +bool step(const char* name, Counts expected_delta, Counts& before) +{ + const Counts now = Counts::read(); + const bool good = now.buffers - before.buffers == expected_delta.buffers && now.resources - before.resources == expected_delta.resources && + now.resolves - before.resolves == expected_delta.resolves && now.refused - before.refused == expected_delta.refused; + std::printf("%s: buffers +%u (%u), resources +%u (%u), resolves +%u (%u), refused +%u (%u)\n", name, now.buffers - before.buffers, + expected_delta.buffers, now.resources - before.resources, expected_delta.resources, now.resolves - before.resolves, + expected_delta.resolves, now.refused - before.refused, expected_delta.refused); + before = now; + return good; +} + +D3D12_RESOURCE_DESC texture(UINT size, DXGI_FORMAT format, UINT samples, D3D12_RESOURCE_FLAGS flags) +{ + return {D3D12_RESOURCE_DIMENSION_TEXTURE2D, 0, size, size, 1, 1, format, {samples, 0}, D3D12_TEXTURE_LAYOUT_UNKNOWN, flags}; +} +D3D12_RESOURCE_DESC buffer(UINT64 width) +{ + return {D3D12_RESOURCE_DIMENSION_BUFFER, 0, width, 1, 1, 1, DXGI_FORMAT_UNKNOWN, {1, 0}, D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + D3D12_RESOURCE_FLAG_NONE}; +} + +struct Probe { + ComPtr desktop; + ComPtr readback; + void* queue = nullptr; + void* fence = nullptr; + Word fence_value = 0; + + bool submit(void* list) + { + void* lists[] = {list}; + invoke(queue, 10, 1, arg(lists)); + if (!ok(invoke(queue, 14, arg(fence), ++fence_value))) return false; + const auto deadline = GetTickCount64() + 10000; + while (invoke(fence, 8) < fence_value) { + if (GetTickCount64() >= deadline) return false; + Sleep(1); + } + return true; + } + UINT64 debug_errors() + { + ComPtr info; + if (FAILED(desktop.As(&info))) return 0; + UINT64 errors = 0; + for (UINT64 i = 0, n = info->GetNumStoredMessages(); i < n; ++i) { + SIZE_T bytes = 0; + if (FAILED(info->GetMessage(i, nullptr, &bytes))) continue; + std::vector storage(bytes); + auto* message = reinterpret_cast(storage.data()); + if (FAILED(info->GetMessage(i, message, &bytes))) continue; + if (message->Severity <= D3D12_MESSAGE_SEVERITY_ERROR) { + ++errors; + std::printf("debug layer: %.*s\n", static_cast(message->DescriptionByteLength), message->pDescription); + } + } + return errors; + } + // The first bytes of a resource (a buffer's first `count`, a texture's first texels), copied on a desktop queue. + bool bytes(ID3D12Resource* target, std::size_t count, std::vector& out) + { + D3D12_COMMAND_QUEUE_DESC desc{}; + ComPtr observer; + ComPtr allocator; + ComPtr copy; + ComPtr done; + if (FAILED(desktop->CreateCommandQueue(&desc, IID_PPV_ARGS(&observer))) || + FAILED(desktop->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator))) || + FAILED(desktop->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.Get(), nullptr, IID_PPV_ARGS(©))) || + FAILED(desktop->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&done)))) + return false; + const D3D12_RESOURCE_DESC described = target->GetDesc(); + if (described.Dimension == D3D12_RESOURCE_DIMENSION_BUFFER) { + copy->CopyBufferRegion(readback.Get(), 0, target, 0, count); + } else { + D3D12_TEXTURE_COPY_LOCATION to{readback.Get(), D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT}; + desktop->GetCopyableFootprints(&described, 0, 1, 0, &to.PlacedFootprint, nullptr, nullptr, nullptr); + D3D12_TEXTURE_COPY_LOCATION from{target, D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX}; + copy->CopyTextureRegion(&to, 0, 0, 0, &from, nullptr); + } + if (FAILED(copy->Close())) return false; + ID3D12CommandList* lists[] = {copy.Get()}; + observer->ExecuteCommandLists(1, lists); + HANDLE event = CreateEventW(nullptr, FALSE, FALSE, nullptr); + const bool finished = event && SUCCEEDED(observer->Signal(done.Get(), 1)) && + SUCCEEDED(done->SetEventOnCompletion(1, event)) && WaitForSingleObject(event, 10000) == WAIT_OBJECT_0; + if (event) CloseHandle(event); + void* memory = nullptr; + if (!finished || FAILED(readback->Map(0, nullptr, &memory))) return false; + out.assign(static_cast(memory), static_cast(memory) + count); + readback->Unmap(0, nullptr); + return true; + } + std::uint32_t texel(ID3D12Resource* target) + { + std::vector data; + std::uint32_t bits = 0xdeadbeef; + if (bytes(target, 4, data)) std::memcpy(&bits, data.data(), sizeof(bits)); + return bits; + } +}; +} // namespace + +int main(int argc, char** argv) +{ + if (argc != 2) return 2; + ComPtr factory; + if (FAILED(CreateDXGIFactory1(IID_PPV_ARGS(&factory)))) return 3; + ComPtr adapter; + if (std::strcmp(argv[1], "hardware") == 0) { + for (UINT n = 0;; ++n) { + ComPtr candidate; + const HRESULT hr = factory->EnumAdapterByGpuPreference(n, DXGI_GPU_PREFERENCE_HIGH_PERFORMANCE, IID_PPV_ARGS(&candidate)); + if (hr == DXGI_ERROR_NOT_FOUND) return 77; + if (FAILED(hr)) return 3; + DXGI_ADAPTER_DESC1 desc{}; + if (FAILED(candidate->GetDesc1(&desc))) return 3; + if (!(desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE) && + SUCCEEDED(D3D12CreateDevice(candidate.Get(), D3D_FEATURE_LEVEL_12_0, __uuidof(ID3D12Device), nullptr))) { + adapter = candidate; + break; + } + } + } else if (std::strcmp(argv[1], "warp") != 0 || FAILED(factory->EnumWarpAdapter(IID_PPV_ARGS(&adapter)))) { + return 3; + } + DXGI_ADAPTER_DESC adapter_desc{}; + if (FAILED(adapter->GetDesc(&adapter_desc))) return 3; + std::printf("adapter=%ls\n", adapter_desc.Description); + + Probe probe; + std::array parameters{}; + void* device = nullptr; + if (FAILED(D3D12XboxCreateDevice(adapter.Get(), parameters.data(), __uuidof(ID3D12Device), &device))) return 4; + if (FAILED(D3D12CreateDevice(adapter.Get(), D3D_FEATURE_LEVEL_12_0, IID_PPV_ARGS(&probe.desktop)))) return 4; + + // Resources. Targets that are cleared carry the render target flag and a typed clear value. + D3D12_HEAP_PROPERTIES heap{D3D12_HEAP_TYPE_DEFAULT}; + const auto create = [&](const D3D12_RESOURCE_DESC& desc, D3D12_RESOURCE_STATES state, const D3D12_CLEAR_VALUE* clear, ComPtr& out) { + return SUCCEEDED(probe.desktop->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, state, clear, IID_PPV_ARGS(&out))); + }; + const D3D12_CLEAR_VALUE clear_rgba{DXGI_FORMAT_R8G8B8A8_UNORM, {0, 0, 0, 0}}; + const D3D12_CLEAR_VALUE clear_half{DXGI_FORMAT_R16G16B16A16_FLOAT, {0, 0, 0, 0}}; + const auto rt = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET, none = D3D12_RESOURCE_FLAG_NONE; + ComPtr source_a, copy_b, source_c, empty_d, large_e, msaa_m, resolved_r, msaa_h, resolved_h; + ComPtr upload_u, buffer_x, buffer_y; + if (!create(texture(4, DXGI_FORMAT_R8G8B8A8_UNORM, 1, rt), D3D12_RESOURCE_STATE_COMMON, &clear_rgba, source_a) || + !create(texture(4, DXGI_FORMAT_R8G8B8A8_UNORM, 1, none), D3D12_RESOURCE_STATE_COMMON, nullptr, copy_b) || + !create(texture(4, DXGI_FORMAT_R8G8B8A8_UNORM, 1, rt), D3D12_RESOURCE_STATE_COMMON, &clear_rgba, source_c) || + !create(texture(4, DXGI_FORMAT_R8G8B8A8_UNORM, 1, none), D3D12_RESOURCE_STATE_COMMON, nullptr, empty_d) || + !create(texture(8, DXGI_FORMAT_R8G8B8A8_UNORM, 1, none), D3D12_RESOURCE_STATE_COMMON, nullptr, large_e) || + !create(texture(4, DXGI_FORMAT_R8G8B8A8_UNORM, 4, rt), D3D12_RESOURCE_STATE_COMMON, &clear_rgba, msaa_m) || + !create(texture(4, DXGI_FORMAT_R8G8B8A8_UNORM, 1, none), D3D12_RESOURCE_STATE_COMMON, nullptr, resolved_r) || + !create(texture(4, DXGI_FORMAT_R16G16B16A16_TYPELESS, 4, rt), D3D12_RESOURCE_STATE_COMMON, &clear_half, msaa_h) || + !create(texture(4, DXGI_FORMAT_R16G16B16A16_TYPELESS, 1, none), D3D12_RESOURCE_STATE_COMMON, nullptr, resolved_h) || + !create(buffer(256), D3D12_RESOURCE_STATE_COMMON, nullptr, buffer_x) || + !create(buffer(256), D3D12_RESOURCE_STATE_COMMON, nullptr, buffer_y)) + return 5; + heap.Type = D3D12_HEAP_TYPE_UPLOAD; + const D3D12_RESOURCE_DESC upload_desc = buffer(256); + if (FAILED(probe.desktop->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &upload_desc, D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, + IID_PPV_ARGS(&upload_u)))) + return 5; + std::array pattern{}; + for (std::size_t i = 0; i < pattern.size(); ++i) pattern[i] = static_cast(i * 3 + 1); + void* mapped = nullptr; + if (FAILED(upload_u->Map(0, nullptr, &mapped))) return 5; + std::memcpy(mapped, pattern.data(), pattern.size()); + upload_u->Unmap(0, nullptr); + heap.Type = D3D12_HEAP_TYPE_READBACK; + const D3D12_RESOURCE_DESC readback_desc = buffer(4096); + if (FAILED(probe.desktop->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &readback_desc, D3D12_RESOURCE_STATE_COPY_DEST, + nullptr, IID_PPV_ARGS(&probe.readback)))) + return 5; + + // Render target views of the four targets that are cleared. + const struct { + D3D12_DESCRIPTOR_HEAP_DESC desc; + Word backing, bytes; + } heap_desc{{D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 4}, 0, 0}; + void* rtv_heap = nullptr; + if (!ok(invoke(device, 14, arg(&heap_desc), arg(&__uuidof(ID3D12DescriptorHeap)), arg(&rtv_heap)))) return 6; + const UINT stride = probe.desktop->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_RTV); + const SIZE_T first = static_cast(invoke(rtv_heap, 9)); + const D3D12_CPU_DESCRIPTOR_HANDLE view_a{first}, view_c{first + stride}, view_m{first + 2 * stride}, view_h{first + 3 * stride}; + D3D12_RENDER_TARGET_VIEW_DESC flat{DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_RTV_DIMENSION_TEXTURE2D, {}}; + D3D12_RENDER_TARGET_VIEW_DESC multisampled{DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_RTV_DIMENSION_TEXTURE2DMS, {}}; + D3D12_RENDER_TARGET_VIEW_DESC multisampled_half{DXGI_FORMAT_R16G16B16A16_FLOAT, D3D12_RTV_DIMENSION_TEXTURE2DMS, {}}; + invoke(device, 20, arg(source_a.Get()), arg(&flat), view_a.ptr); + invoke(device, 20, arg(source_c.Get()), arg(&flat), view_c.ptr); + invoke(device, 20, arg(msaa_m.Get()), arg(&multisampled), view_m.ptr); + invoke(device, 20, arg(msaa_h.Get()), arg(&multisampled_half), view_h.ptr); + + D3D12_COMMAND_QUEUE_DESC queue_desc{}; + const unsigned list_desc[] = {D3D12_COMMAND_LIST_TYPE_DIRECT, 2, 1, 0}; + void *allocator = nullptr, *list = nullptr; + if (!ok(invoke(device, 8, arg(&queue_desc), arg(&__uuidof(ID3D12CommandQueue)), arg(&probe.queue))) || + !ok(invoke(device, 36, 0, 0, arg(&__uuidof(ID3D12Fence)), arg(&probe.fence))) || + !ok(invoke(device, 9, D3D12_COMMAND_LIST_TYPE_DIRECT, arg(&__uuidof(ID3D12CommandAllocator)), arg(&allocator))) || + !ok(invoke(device, 73, arg(list_desc), arg(allocator), 0, arg(&__uuidof(ID3D12GraphicsCommandList)), arg(&list)))) + return 7; + if (!ok(invoke(list, 139, arg(allocator), 0))) return 8; + + invoke(list, 52, view_a.ptr, arg(red)); + invoke(list, 52, view_c.ptr, arg(blue)); + invoke(list, 52, view_m.ptr, arg(green)); + invoke(list, 52, view_h.ptr, arg(red)); + + Counts seen = Counts::read(); + invoke(list, 17, arg(copy_b.Get()), arg(source_a.Get())); + if (!step("1 CopyResource", {0, 1, 0, 0}, seen)) return 10; + invoke(list, 17, arg(source_c.Get()), arg(empty_d.Get())); // swapped: the empty texture is the source + if (!step("2 CopyResource, source and destination swapped", {0, 1, 0, 0}, seen)) return 11; + invoke(list, 19, arg(resolved_r.Get()), 0, arg(msaa_m.Get()), 0, DXGI_FORMAT_R8G8B8A8_UNORM); + if (!step("3 ResolveSubresource", {0, 0, 1, 0}, seen)) return 12; + invoke(list, 19, arg(resolved_h.Get()), 0, arg(msaa_h.Get()), 0, DXGI_FORMAT_R16G16B16A16_TYPELESS); + if (!step("4 ResolveSubresource, typeless half float", {0, 0, 1, 0}, seen)) return 13; + invoke(list, 15, arg(buffer_x.Get()), 0, arg(upload_u.Get()), 0, 256); + invoke(list, 15, arg(buffer_y.Get()), 16, arg(buffer_x.Get()), 32, 64); + if (!step("5 CopyBufferRegion twice", {2, 0, 0, 0}, seen)) return 14; + + invoke(list, 17, arg(large_e.Get()), arg(source_a.Get())); + if (!step("6a CopyResource between different sizes", {0, 0, 0, 1}, seen)) return 15; + invoke(list, 17, arg(copy_b.Get()), 0); + if (!step("6b CopyResource with a null source", {0, 0, 0, 1}, seen)) return 16; + invoke(list, 19, arg(resolved_r.Get()), 0, arg(source_a.Get()), 0, DXGI_FORMAT_R8G8B8A8_UNORM); + if (!step("6c ResolveSubresource from one sample", {0, 0, 0, 1}, seen)) return 17; + invoke(list, 15, arg(buffer_y.Get()), 0, arg(buffer_x.Get()), 200, 100); + if (!step("6d CopyBufferRegion past the end", {0, 0, 0, 1}, seen)) return 18; + + invoke(list, 9); + if (!probe.submit(list)) return 19; + invoke(list, 17, arg(copy_b.Get()), arg(empty_d.Get())); + invoke(list, 19, arg(resolved_r.Get()), 0, arg(msaa_m.Get()), 0, DXGI_FORMAT_R8G8B8A8_UNORM); + invoke(list, 15, arg(buffer_y.Get()), 0, arg(buffer_x.Get()), 0, 16); + if (!step("7 calls on a closed list", {0, 0, 0, 0}, seen)) return 20; + + const std::uint32_t copied = probe.texel(copy_b.Get()); + const std::uint32_t swapped_source = probe.texel(empty_d.Get()); + const std::uint32_t swapped_target = probe.texel(source_c.Get()); + const std::uint32_t resolved = probe.texel(resolved_r.Get()); + const std::uint32_t resolved_half = probe.texel(resolved_h.Get()); + std::printf("copy: %08x (expected %08x)\n", copied, red_bits); + std::printf("swapped copy, source stays empty: %08x (expected 00000000), target now empty: %08x (expected 00000000)\n", + swapped_source, swapped_target); + std::printf("resolve: %08x (expected %08x), half float resolve: %08x (expected %08x)\n", resolved, green_bits, resolved_half, half_one); + if (copied != red_bits) return 21; + if (swapped_source != 0 || swapped_target != 0) return 22; + if (resolved != green_bits) return 23; + if (resolved_half != half_one) return 24; + + std::vector whole, moved; + if (!probe.bytes(buffer_x.Get(), 256, whole) || !probe.bytes(buffer_y.Get(), 80, moved)) return 25; + if (std::memcmp(whole.data(), pattern.data(), pattern.size()) != 0) return 26; + if (std::memcmp(moved.data() + 16, pattern.data() + 32, 64) != 0) return 27; + std::printf("buffers: whole copy and offset copy exact\n"); + + const HRESULT removed = probe.desktop->GetDeviceRemovedReason(); + const UINT64 errors = probe.debug_errors(); + std::printf("device removed reason: 0x%08lx, debug layer errors: %llu\n", static_cast(removed), + static_cast(errors)); + return removed == S_OK && errors == 0 ? 0 : 70; +} diff --git a/tests/startup_list_copy_check.cpp b/tests/startup_list_copy_check.cpp new file mode 100644 index 0000000000..ad6e887e63 --- /dev/null +++ b/tests/startup_list_copy_check.cpp @@ -0,0 +1,136 @@ +// Checks the validation of the whole-resource command-list copies (CopyBufferRegion, CopyResource, +// ResolveSubresource; src/startup_stubs/list_copy.h) without a device. +// --mutate overflow: expect an offset and size that wrap to be accepted. +// --mutate typeless: expect a typeless half-float resolve format to stay typeless instead of resolving as float. +// --mutate samples: expect CopyResource between textures of different sample counts to be accepted. +// Each mutated run is a negative control and must fail. +#include "startup_stubs/list_copy.h" + +#include +#include + +namespace { + +using namespace x2w_startup; + +int failures; +const char* mutation = ""; + +bool mutated(const char* name) +{ + return std::strcmp(mutation, name) == 0; +} + +void check(const char* name, bool condition) +{ + if (condition) return; + ++failures; + std::printf("FAIL %s\n", name); +} + +D3D12_RESOURCE_DESC buffer(UINT64 width) +{ + D3D12_RESOURCE_DESC d{}; + d.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + d.Width = width; + d.Height = 1; + d.DepthOrArraySize = 1; + d.MipLevels = 1; + d.SampleDesc.Count = 1; + d.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + return d; +} + +D3D12_RESOURCE_DESC texture(UINT64 width, UINT height, DXGI_FORMAT format, UINT samples = 1, UINT mips = 1, UINT array = 1) +{ + D3D12_RESOURCE_DESC d{}; + d.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + d.Width = width; + d.Height = height; + d.DepthOrArraySize = static_cast(array); + d.MipLevels = static_cast(mips); + d.Format = format; + d.SampleDesc.Count = samples; + return d; +} + +} // namespace + +int main(int argc, char** argv) +{ + if (argc == 3 && std::strcmp(argv[1], "--mutate") == 0) mutation = argv[2]; + + // CopyBufferRegion: ranges inside both buffers, and the first refusal in the documented order. + const auto a = buffer(256), b = buffer(128), tex = texture(4, 4, DXGI_FORMAT_R8G8B8A8_UNORM); + check("buffer copy", check_copy_buffer_region(&a, 16, &b, 32, 64, false) == CopyRefusal::none); + check("buffer copy to the end", check_copy_buffer_region(&a, 192, &b, 64, 64, false) == CopyRefusal::none); + check("buffer null", check_copy_buffer_region(nullptr, 0, &b, 0, 4, false) == CopyRefusal::unresolved); + check("buffer same", check_copy_buffer_region(&a, 0, &a, 64, 4, true) == CopyRefusal::same_resource); + check("buffer texture", check_copy_buffer_region(&a, 0, &tex, 0, 4, false) == CopyRefusal::not_buffer); + check("buffer empty", check_copy_buffer_region(&a, 0, &b, 0, 0, false) == CopyRefusal::zero_size); + check("buffer past the source", check_copy_buffer_region(&a, 0, &b, 100, 64, false) == CopyRefusal::range_overflow); + check("buffer past the destination", check_copy_buffer_region(&b, 100, &a, 0, 64, false) == CopyRefusal::range_overflow); + const CopyRefusal wrapped = check_copy_buffer_region(&a, UINT64_MAX - 1, &b, 0, 8, false); + check("buffer wrapping offset", mutated("overflow") ? wrapped == CopyRefusal::none : wrapped == CopyRefusal::range_overflow); + + // CopyResource: one shape. + const auto rgba = texture(4, 4, DXGI_FORMAT_R8G8B8A8_UNORM); + const auto tmp0 = texture(4, 4, DXGI_FORMAT_R32_FLOAT); + const auto tmp1 = texture(8, 4, DXGI_FORMAT_R8G8B8A8_UNORM); + const auto tmp2 = texture(4, 4, DXGI_FORMAT_R8G8B8A8_UNORM, 1, 2); + const auto tmp3 = texture(8, 4, DXGI_FORMAT_R8G8B8A8_UNORM); + check("resource copy", check_copy_resource(&rgba, &rgba, false) == CopyRefusal::none); + check("resource same", check_copy_resource(&rgba, &rgba, true) == CopyRefusal::same_resource); + check("resource null", check_copy_resource(&rgba, nullptr, false) == CopyRefusal::unresolved); + const auto typeless = texture(4, 4, DXGI_FORMAT_R8G8B8A8_TYPELESS); + check("resource typeless to typed", check_copy_resource(&rgba, &typeless, false) == CopyRefusal::none); + check("resource other format", check_copy_resource(&rgba, &tmp0, false) == + CopyRefusal::format_mismatch); + check("resource other size", check_copy_resource(&rgba, &tmp1, false) == + CopyRefusal::size_mismatch); + check("resource other mips", check_copy_resource(&rgba, &tmp2, false) == + CopyRefusal::size_mismatch); + check("resource buffer and texture", check_copy_resource(&a, &rgba, false) == CopyRefusal::dimension_mismatch); + check("resource other buffer size", check_copy_resource(&a, &b, false) == CopyRefusal::size_mismatch); + check("resource buffers", check_copy_resource(&a, &a, false) == CopyRefusal::none); + const auto msaa = texture(4, 4, DXGI_FORMAT_R8G8B8A8_UNORM, 4); + const CopyRefusal samples = check_copy_resource(&rgba, &msaa, false); + check("resource other samples", mutated("samples") ? samples == CopyRefusal::none : samples == CopyRefusal::sample_mismatch); + + // ResolveSubresource. + check("resolve", plan_resolve(&rgba, 0, &msaa, 0, DXGI_FORMAT_R8G8B8A8_UNORM, false).refusal == CopyRefusal::none); + check("resolve format", plan_resolve(&rgba, 0, &msaa, 0, DXGI_FORMAT_R8G8B8A8_UNORM, false).format == DXGI_FORMAT_R8G8B8A8_UNORM); + check("resolve null", plan_resolve(nullptr, 0, &msaa, 0, DXGI_FORMAT_R8G8B8A8_UNORM, false).refusal == CopyRefusal::unresolved); + check("resolve same", plan_resolve(&msaa, 0, &msaa, 0, DXGI_FORMAT_R8G8B8A8_UNORM, true).refusal == CopyRefusal::same_resource); + check("resolve from one sample", plan_resolve(&rgba, 0, &rgba, 0, DXGI_FORMAT_R8G8B8A8_UNORM, false).refusal == + CopyRefusal::source_not_multisampled); + check("resolve into samples", plan_resolve(&msaa, 0, &msaa, 0, DXGI_FORMAT_R8G8B8A8_UNORM, false).refusal == + CopyRefusal::destination_multisampled); + check("resolve a buffer", plan_resolve(&a, 0, &msaa, 0, DXGI_FORMAT_R8G8B8A8_UNORM, false).refusal == CopyRefusal::not_texture); + check("resolve other size", plan_resolve(&tmp3, 0, &msaa, 0, + DXGI_FORMAT_R8G8B8A8_UNORM, false).refusal == CopyRefusal::bad_subresource); + check("resolve subresource out of range", plan_resolve(&rgba, 1, &msaa, 0, DXGI_FORMAT_R8G8B8A8_UNORM, false).refusal == + CopyRefusal::bad_subresource); + check("resolve other format", plan_resolve(&rgba, 0, &msaa, 0, DXGI_FORMAT_R32_FLOAT, false).refusal == CopyRefusal::format_mismatch); + const auto hdr_source = texture(4, 4, DXGI_FORMAT_R16G16B16A16_TYPELESS, 4); + const auto hdr_target = texture(4, 4, DXGI_FORMAT_R16G16B16A16_TYPELESS); + const ResolvePlan hdr = plan_resolve(&hdr_target, 0, &hdr_source, 0, DXGI_FORMAT_R16G16B16A16_TYPELESS, false); + check("resolve typeless half float", hdr.refusal == CopyRefusal::none); + check("resolve typeless as float", hdr.format == (mutated("typeless") ? DXGI_FORMAT_R16G16B16A16_TYPELESS : DXGI_FORMAT_R16G16B16A16_FLOAT)); + check("resolve unknown over typeless", plan_resolve(&hdr_target, 0, &hdr_source, 0, DXGI_FORMAT_UNKNOWN, false).format == + DXGI_FORMAT_R16G16B16A16_FLOAT); + const auto small_source = texture(4, 4, DXGI_FORMAT_R16_TYPELESS, 4); + const auto small_target = texture(4, 4, DXGI_FORMAT_R16_TYPELESS); + check("resolve typeless without a choice", plan_resolve(&small_target, 0, &small_source, 0, DXGI_FORMAT_R16_TYPELESS, false).refusal == + CopyRefusal::bad_format); + const auto mips_target = texture(4, 4, DXGI_FORMAT_R8G8B8A8_UNORM, 1, 3); + const auto mip_source = texture(2, 2, DXGI_FORMAT_R8G8B8A8_UNORM, 4); + check("resolve a smaller mip", plan_resolve(&mips_target, 1, &mip_source, 0, DXGI_FORMAT_R8G8B8A8_UNORM, false).refusal == CopyRefusal::none); + + check("names", std::strcmp(copy_refusal_name(CopyRefusal::range_overflow), "range_overflow") == 0 && + std::strcmp(copy_refusal_name(CopyRefusal::none), "none") == 0); + + if (failures) return 1; + std::printf("startup_list_copy_check: ok\n"); + return 0; +} From 510fff86210719ffe725371d0676fb6d5baa98ea Mon Sep 17 00:00:00 2001 From: tedin7 Date: Wed, 25 Nov 2026 01:44:21 +0100 Subject: [PATCH 2/9] startup: sync title-backed copy sources, mark destinations GPU-written, check heap direction and DXGI families - CopyResource/CopyBufferRegion refresh a title-backed source first (texture upload, upload-buffer map copy); title-backed default buffers are refused. - Copy and resolve destinations are marked GPU-written so a later draw does not re-upload stale title memory over them. - Placed buffers that do not start in COMMON and upload/readback buffers used in the wrong direction are refused. - Resolve format is exact against a fully typed endpoint; CopyResource accepts the remaining DXGI families (BC, R8, R16, R32G32, depth). --- docs/startup-runtime.md | 9 +- src/startup_stubs/d3d12_draw.inl | 2 + src/startup_stubs/list_copy.h | 69 +++++++++++-- src/startup_stubs/list_copy.inl | 166 +++++++++++++++++++++++------- tests/startup_list_copy.cpp | 7 +- tests/startup_list_copy_check.cpp | 28 ++++- 6 files changed, 233 insertions(+), 48 deletions(-) diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index 0ab507976f..fdc4776751 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -426,7 +426,14 @@ mapped to its desktop resource, the pair is moved to the copy or resolve states desktop would reject is counted, logged (first six) and not forwarded, with the reason: `unresolved`, `same_resource`, `not_buffer`, `not_texture`, `dimension_mismatch`, `size_mismatch`, `format_mismatch`, `sample_mismatch`, `bad_subresource`, `source_not_multisampled`, `destination_multisampled`, `bad_format`, `zero_size` or -`range_overflow`. A typeless resolve format (or an unknown one over a typeless source) resolves as the family's typed +`range_overflow`, `heap_direction` (an upload buffer as a destination, a readback buffer as a source), +`initial_state` (a placed buffer that does not start in COMMON) or `title_backed_source` (a title-backed default-heap +buffer, which has no desktop copy to refresh). A source the title maps at its own memory is brought up to date first: a +texture takes the draw path's upload, an upload buffer is copied through a desktop mapping, and an aliased placed buffer +is already current. A copy or resolve destination with title memory is marked GPU-written, so a later draw does not +upload the stale title memory over the result. CopyResource accepts formats of one DXGI family (colour, depth, 8/16/32-bit +and block-compressed). A resolve format is exact against a fully typed endpoint and only family-compatible with a +typeless one; a typeless resolve format (or an unknown one over typeless endpoints) resolves as the family's typed choice: half float for `R16G16B16A16`, normalised for the 8-bit and 10-bit families. Calls on a closed list are ignored. These slots have not been seen in a title log yet. `CopyTextureRegion` (16) and `CopyTiles` (18) are not handled. `ctest -R '^startup_list_copy_validation'` runs the pure checks on any host; `startup_list_copy_{warp,hardware}` copies, diff --git a/src/startup_stubs/d3d12_draw.inl b/src/startup_stubs/d3d12_draw.inl index 44bcaf7bba..9a6b23dcac 100644 --- a/src/startup_stubs/d3d12_draw.inl +++ b/src/startup_stubs/d3d12_draw.inl @@ -771,6 +771,7 @@ struct TextureUpload { bool done = false, tiled = false; ID3D12CommandList* pending_list = nullptr; u64 revision = 0; + bool gpu_written = false; // a list copy or resolve wrote the texture; its title memory is stale and must not be uploaded }; std::unordered_map& texture_uploads() { static std::unordered_map m; return m; } u64 address_upload_revision; @@ -1024,6 +1025,7 @@ bool upload_texture(Wrapper* self, Wrapper* resource, ID3D12Resource* texture) } } if (!memory || !list || !uploadable) return !console; + if (const auto written_by_gpu = texture_uploads().find(texture); written_by_gpu != texture_uploads().end() && written_by_gpu->second.gpu_written) return !console; if (desc.Flags & (D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET | D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL | D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS)) return !console; const UINT mips = desc.MipLevels ? desc.MipLevels : 1; const UINT slices = desc.DepthOrArraySize ? desc.DepthOrArraySize : 1; diff --git a/src/startup_stubs/list_copy.h b/src/startup_stubs/list_copy.h index 42be90fd30..9113f788d8 100644 --- a/src/startup_stubs/list_copy.h +++ b/src/startup_stubs/list_copy.h @@ -29,6 +29,9 @@ enum class CopyRefusal { bad_format, // a resolve format that is unknown, or typeless with no typed choice zero_size, // CopyBufferRegion of no bytes range_overflow, // an offset and size that wrap, or run past a buffer + heap_direction, // an upload buffer used as a destination, or a readback buffer as a source + initial_state, // a placed buffer whose first state is not COMMON, which the state tracker starts from + title_backed_source, // a source whose title memory has no desktop copy the list could refresh }; inline const char* copy_refusal_name(CopyRefusal refusal) @@ -48,21 +51,33 @@ inline const char* copy_refusal_name(CopyRefusal refusal) case CopyRefusal::bad_format: return "bad_format"; case CopyRefusal::zero_size: return "zero_size"; case CopyRefusal::range_overflow: return "range_overflow"; + case CopyRefusal::heap_direction: return "heap_direction"; + case CopyRefusal::initial_state: return "initial_state"; + case CopyRefusal::title_backed_source: return "title_backed_source"; default: return "none"; } } -// The typeless member of the colour format family `format` belongs to; `format` itself when it has none. +// The typeless member of the DXGI format family `format` belongs to; `format` itself when it has none. +// Formats of one family may be copied to each other (CopyResource) and cast by a view. inline DXGI_FORMAT format_family(DXGI_FORMAT format) { switch (format) { case DXGI_FORMAT_R32G32B32A32_TYPELESS: case DXGI_FORMAT_R32G32B32A32_FLOAT: case DXGI_FORMAT_R32G32B32A32_UINT: case DXGI_FORMAT_R32G32B32A32_SINT: return DXGI_FORMAT_R32G32B32A32_TYPELESS; + case DXGI_FORMAT_R32G32B32_TYPELESS: case DXGI_FORMAT_R32G32B32_FLOAT: + case DXGI_FORMAT_R32G32B32_UINT: case DXGI_FORMAT_R32G32B32_SINT: + return DXGI_FORMAT_R32G32B32_TYPELESS; case DXGI_FORMAT_R16G16B16A16_TYPELESS: case DXGI_FORMAT_R16G16B16A16_FLOAT: case DXGI_FORMAT_R16G16B16A16_UNORM: case DXGI_FORMAT_R16G16B16A16_UINT: case DXGI_FORMAT_R16G16B16A16_SNORM: case DXGI_FORMAT_R16G16B16A16_SINT: return DXGI_FORMAT_R16G16B16A16_TYPELESS; + case DXGI_FORMAT_R32G32_TYPELESS: case DXGI_FORMAT_R32G32_FLOAT: case DXGI_FORMAT_R32G32_UINT: case DXGI_FORMAT_R32G32_SINT: + return DXGI_FORMAT_R32G32_TYPELESS; + case DXGI_FORMAT_R32G8X24_TYPELESS: case DXGI_FORMAT_D32_FLOAT_S8X24_UINT: + case DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS: case DXGI_FORMAT_X32_TYPELESS_G8X24_UINT: + return DXGI_FORMAT_R32G8X24_TYPELESS; case DXGI_FORMAT_R10G10B10A2_TYPELESS: case DXGI_FORMAT_R10G10B10A2_UNORM: case DXGI_FORMAT_R10G10B10A2_UINT: return DXGI_FORMAT_R10G10B10A2_TYPELESS; case DXGI_FORMAT_R8G8B8A8_TYPELESS: case DXGI_FORMAT_R8G8B8A8_UNORM: case DXGI_FORMAT_R8G8B8A8_UNORM_SRGB: @@ -70,11 +85,40 @@ inline DXGI_FORMAT format_family(DXGI_FORMAT format) return DXGI_FORMAT_R8G8B8A8_TYPELESS; case DXGI_FORMAT_B8G8R8A8_TYPELESS: case DXGI_FORMAT_B8G8R8A8_UNORM: case DXGI_FORMAT_B8G8R8A8_UNORM_SRGB: return DXGI_FORMAT_B8G8R8A8_TYPELESS; + case DXGI_FORMAT_B8G8R8X8_TYPELESS: case DXGI_FORMAT_B8G8R8X8_UNORM: case DXGI_FORMAT_B8G8R8X8_UNORM_SRGB: + return DXGI_FORMAT_B8G8R8X8_TYPELESS; case DXGI_FORMAT_R16G16_TYPELESS: case DXGI_FORMAT_R16G16_FLOAT: case DXGI_FORMAT_R16G16_UNORM: case DXGI_FORMAT_R16G16_UINT: case DXGI_FORMAT_R16G16_SNORM: case DXGI_FORMAT_R16G16_SINT: return DXGI_FORMAT_R16G16_TYPELESS; - case DXGI_FORMAT_R32_TYPELESS: case DXGI_FORMAT_R32_FLOAT: case DXGI_FORMAT_R32_UINT: case DXGI_FORMAT_R32_SINT: + case DXGI_FORMAT_R32_TYPELESS: case DXGI_FORMAT_D32_FLOAT: case DXGI_FORMAT_R32_FLOAT: + case DXGI_FORMAT_R32_UINT: case DXGI_FORMAT_R32_SINT: return DXGI_FORMAT_R32_TYPELESS; + case DXGI_FORMAT_R24G8_TYPELESS: case DXGI_FORMAT_D24_UNORM_S8_UINT: + case DXGI_FORMAT_R24_UNORM_X8_TYPELESS: case DXGI_FORMAT_X24_TYPELESS_G8_UINT: + return DXGI_FORMAT_R24G8_TYPELESS; + case DXGI_FORMAT_R8G8_TYPELESS: case DXGI_FORMAT_R8G8_UNORM: case DXGI_FORMAT_R8G8_UINT: + case DXGI_FORMAT_R8G8_SNORM: case DXGI_FORMAT_R8G8_SINT: + return DXGI_FORMAT_R8G8_TYPELESS; + case DXGI_FORMAT_R16_TYPELESS: case DXGI_FORMAT_R16_FLOAT: case DXGI_FORMAT_D16_UNORM: case DXGI_FORMAT_R16_UNORM: + case DXGI_FORMAT_R16_UINT: case DXGI_FORMAT_R16_SNORM: case DXGI_FORMAT_R16_SINT: + return DXGI_FORMAT_R16_TYPELESS; + case DXGI_FORMAT_R8_TYPELESS: case DXGI_FORMAT_R8_UNORM: case DXGI_FORMAT_R8_UINT: + case DXGI_FORMAT_R8_SNORM: case DXGI_FORMAT_R8_SINT: + return DXGI_FORMAT_R8_TYPELESS; + case DXGI_FORMAT_BC1_TYPELESS: case DXGI_FORMAT_BC1_UNORM: case DXGI_FORMAT_BC1_UNORM_SRGB: + return DXGI_FORMAT_BC1_TYPELESS; + case DXGI_FORMAT_BC2_TYPELESS: case DXGI_FORMAT_BC2_UNORM: case DXGI_FORMAT_BC2_UNORM_SRGB: + return DXGI_FORMAT_BC2_TYPELESS; + case DXGI_FORMAT_BC3_TYPELESS: case DXGI_FORMAT_BC3_UNORM: case DXGI_FORMAT_BC3_UNORM_SRGB: + return DXGI_FORMAT_BC3_TYPELESS; + case DXGI_FORMAT_BC4_TYPELESS: case DXGI_FORMAT_BC4_UNORM: case DXGI_FORMAT_BC4_SNORM: + return DXGI_FORMAT_BC4_TYPELESS; + case DXGI_FORMAT_BC5_TYPELESS: case DXGI_FORMAT_BC5_UNORM: case DXGI_FORMAT_BC5_SNORM: + return DXGI_FORMAT_BC5_TYPELESS; + case DXGI_FORMAT_BC6H_TYPELESS: case DXGI_FORMAT_BC6H_UF16: case DXGI_FORMAT_BC6H_SF16: + return DXGI_FORMAT_BC6H_TYPELESS; + case DXGI_FORMAT_BC7_TYPELESS: case DXGI_FORMAT_BC7_UNORM: case DXGI_FORMAT_BC7_UNORM_SRGB: + return DXGI_FORMAT_BC7_TYPELESS; default: return format; } @@ -104,6 +148,9 @@ inline bool is_typeless(DXGI_FORMAT format) case DXGI_FORMAT_R8G8B8A8_TYPELESS: case DXGI_FORMAT_R16G16_TYPELESS: case DXGI_FORMAT_R32_TYPELESS: case DXGI_FORMAT_R24G8_TYPELESS: case DXGI_FORMAT_R8G8_TYPELESS: case DXGI_FORMAT_R16_TYPELESS: case DXGI_FORMAT_R8_TYPELESS: case DXGI_FORMAT_B8G8R8A8_TYPELESS: case DXGI_FORMAT_B8G8R8X8_TYPELESS: + case DXGI_FORMAT_BC1_TYPELESS: case DXGI_FORMAT_BC2_TYPELESS: case DXGI_FORMAT_BC3_TYPELESS: + case DXGI_FORMAT_BC4_TYPELESS: case DXGI_FORMAT_BC5_TYPELESS: case DXGI_FORMAT_BC6H_TYPELESS: + case DXGI_FORMAT_BC7_TYPELESS: return true; default: return false; @@ -183,12 +230,22 @@ inline ResolvePlan plan_resolve(const D3D12_RESOURCE_DESC* destination, std::uin if (mip_extent(destination->Width, destination_mip) != mip_extent(source->Width, source_mip) || mip_extent(destination->Height, destination_mip) != mip_extent(source->Height, source_mip)) return {CopyRefusal::bad_subresource, {}}; + // An endpoint of a fully typed format fixes the resolve format exactly; family compatibility only + // satisfies a typeless endpoint. Pick the format from a typed endpoint before any typeless fallback. + const bool source_typed = source->Format != DXGI_FORMAT_UNKNOWN && !is_typeless(source->Format); + const bool destination_typed = destination->Format != DXGI_FORMAT_UNKNOWN && !is_typeless(destination->Format); DXGI_FORMAT typed = format; - if (typed == DXGI_FORMAT_UNKNOWN) typed = source->Format; - if (is_typeless_choice_format(typed)) typed = typed_choice(typed); + if (typed == DXGI_FORMAT_UNKNOWN || is_typeless(typed)) { + if (source_typed) typed = source->Format; + else if (destination_typed) typed = destination->Format; + else if (typed == DXGI_FORMAT_UNKNOWN) typed = source->Format; + if (is_typeless_choice_format(typed)) typed = typed_choice(typed); + } if (typed == DXGI_FORMAT_UNKNOWN || is_typeless(typed)) return {CopyRefusal::bad_format, {}}; - if (!compatible_formats(typed, source->Format) || !compatible_formats(typed, destination->Format)) - return {CopyRefusal::format_mismatch, {}}; + const auto fits = [typed](const D3D12_RESOURCE_DESC* endpoint, bool is_typed) { + return is_typed ? endpoint->Format == typed : compatible_formats(typed, endpoint->Format); + }; + if (!fits(source, source_typed) || !fits(destination, destination_typed)) return {CopyRefusal::format_mismatch, {}}; return {CopyRefusal::none, typed}; } diff --git a/src/startup_stubs/list_copy.inl b/src/startup_stubs/list_copy.inl index c78dcb4635..101ecbcae5 100644 --- a/src/startup_stubs/list_copy.inl +++ b/src/startup_stubs/list_copy.inl @@ -9,16 +9,23 @@ LONG list_buffer_copies, list_resource_copies, list_resolves, list_copies_refused; -// The desktop resource behind a copy argument; null for a null value, or a wrapper that is not a resource. +// One copy argument: the desktop resource, and its wrapper when the title passed one. +struct CopyEndpoint { + ID3D12Resource* resource = nullptr; + Wrapper* wrapper = nullptr; +}; + +// The desktop resource behind a copy argument; empty for a null value, or a wrapper that is not a resource. // A value that is no wrapper is taken as a desktop resource, as the view slots do. -ID3D12Resource* copy_endpoint(u64 value) +CopyEndpoint copy_endpoint(u64 value) { - if (!value) return nullptr; - if (const Wrapper* w = as_wrapper(reinterpret_cast(value))) { - if (w->own().kind != resource_kind) return nullptr; - return static_cast(w->own().real); + if (!value) return {}; + if (Wrapper* w = as_wrapper(reinterpret_cast(value))) { + if (w->own().kind != resource_kind) return {}; + return {static_cast(w->own().real), w}; } - return x2w_local::readable(reinterpret_cast(value), sizeof(void*)) ? reinterpret_cast(value) : nullptr; + return {x2w_local::readable(reinterpret_cast(value), sizeof(void*)) ? reinterpret_cast(value) : nullptr, + nullptr}; } void refuse_copy(const char* what, x2w_startup::CopyRefusal reason) @@ -28,34 +35,107 @@ void refuse_copy(const char* what, x2w_startup::CopyRefusal reason) if (first_calls(logged, 6)) log("x2w-d3d12 %s skipped: %s", what, x2w_startup::copy_refusal_name(reason)); } +// Upload and readback buffers keep the one state their heap allows, so a copy may use them in one direction only: +// an upload buffer as a source, a readback buffer as a destination. True for a heap that rests in COMMON. +bool fixed_heap(ID3D12Resource* resource, D3D12_HEAP_TYPE& type) +{ + D3D12_HEAP_PROPERTIES heap{}; + D3D12_HEAP_FLAGS flags{}; + type = D3D12_HEAP_TYPE_DEFAULT; + if (FAILED(resource->GetHeapProperties(&heap, &flags))) return false; + type = heap.Type; + return heap.Type == D3D12_HEAP_TYPE_UPLOAD || heap.Type == D3D12_HEAP_TYPE_READBACK; +} + +// The first refusal for a pair of endpoints that the descriptions did not catch: a heap used in the wrong +// direction, or a placed buffer that does not start in COMMON (the state tracker starts every resource there). +x2w_startup::CopyRefusal check_endpoint_roles(const CopyEndpoint& to, const CopyEndpoint& from) +{ + D3D12_HEAP_TYPE type; + if (fixed_heap(to.resource, type) && type == D3D12_HEAP_TYPE_UPLOAD) return x2w_startup::CopyRefusal::heap_direction; + if (fixed_heap(from.resource, type) && type == D3D12_HEAP_TYPE_READBACK) return x2w_startup::CopyRefusal::heap_direction; + for (const CopyEndpoint& endpoint : {to, from}) { + if (!endpoint.wrapper) continue; + const auto* info = resource_info(endpoint.wrapper); + if (info && info->initial_state != D3D12_RESOURCE_STATE_COMMON) return x2w_startup::CopyRefusal::initial_state; + } + return x2w_startup::CopyRefusal::none; +} + // The state a copy needs from `resource`: an upload buffer stays readable and a readback buffer stays a // copy destination, because desktop allows no other state for them. void require_copy_state(Wrapper* self, ID3D12Resource* resource, D3D12_RESOURCE_STATES state) { - D3D12_HEAP_PROPERTIES heap{}; - D3D12_HEAP_FLAGS flags{}; - if (SUCCEEDED(resource->GetHeapProperties(&heap, &flags)) && - (heap.Type == D3D12_HEAP_TYPE_UPLOAD || heap.Type == D3D12_HEAP_TYPE_READBACK)) - return; + D3D12_HEAP_TYPE type; + if (fixed_heap(resource, type)) return; require_state(self, resource, state); } +// A resource the title maps at its own memory has a desktop resource that map and unmap never touch. Before +// that resource is copied from, bring it up to date: a texture takes the draw path's upload, an upload buffer +// takes the bytes through a desktop mapping, and a placed buffer aliasing the memory is already current. +// False for a title-backed default-heap buffer, which has no desktop copy the list can refresh. +bool sync_title_source(Wrapper* self, const CopyEndpoint& source) +{ + if (!source.wrapper || !source.wrapper->own().title_memory) return true; + const D3D12_RESOURCE_DESC desc = source.resource->GetDesc(); + if (desc.Dimension != D3D12_RESOURCE_DIMENSION_BUFFER) { + upload_texture(self, source.wrapper, source.resource); + return true; + } + const auto* info = resource_info(source.wrapper); + if (info && info->placement == Placement::aliased_buffer) return true; + D3D12_HEAP_TYPE type; + if (!fixed_heap(source.resource, type) || type != D3D12_HEAP_TYPE_UPLOAD) return false; + const u64 memory = reinterpret_cast(source.wrapper->own().title_memory); + if (readable_window(memory, static_cast(desc.Width)) < desc.Width) return false; + void* mapped = nullptr; + const D3D12_RANGE none{0, 0}; + if (FAILED(source.resource->Map(0, &none, &mapped)) || !mapped) return false; + std::memcpy(mapped, reinterpret_cast(memory), static_cast(desc.Width)); + source.resource->Unmap(0, nullptr); + return true; +} + +// A copy or resolve destination now holds what the GPU wrote. A title-backed texture would otherwise be +// uploaded over it from its stale memory the first time a draw samples it. +void mark_gpu_written(const CopyEndpoint& destination) +{ + if (!destination.wrapper || !destination.wrapper->own().title_memory) return; + TextureUpload& state = texture_uploads()[destination.resource]; + state.gpu_written = true; + state.done = true; +} + +// 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) +{ + const auto roles = check_endpoint_roles(to, from); + if (roles != x2w_startup::CopyRefusal::none) return roles; + if (sync && !sync_title_source(self, from)) return x2w_startup::CopyRefusal::title_backed_source; + return x2w_startup::CopyRefusal::none; +} + // List slot 15, CopyBufferRegion(destination, destination offset, source, source offset, bytes). void __stdcall list_copy_buffer_region(Wrapper* self, u64 destination, u64 destination_offset, u64 source, u64 source_offset, u64 bytes) { if (!self->own().list_open) return; - ID3D12Resource* const to = copy_endpoint(destination); - ID3D12Resource* const from = copy_endpoint(source); + const CopyEndpoint to = copy_endpoint(destination); + const CopyEndpoint from = copy_endpoint(source); D3D12_RESOURCE_DESC to_desc{}, from_desc{}; - if (to) to_desc = to->GetDesc(); - if (from) from_desc = from->GetDesc(); - const auto refusal = x2w_startup::check_copy_buffer_region(to ? &to_desc : nullptr, destination_offset, - from ? &from_desc : nullptr, source_offset, bytes, to == from); + if (to.resource) to_desc = to.resource->GetDesc(); + if (from.resource) from_desc = from.resource->GetDesc(); + auto refusal = x2w_startup::check_copy_buffer_region(to.resource ? &to_desc : nullptr, destination_offset, + from.resource ? &from_desc : nullptr, source_offset, bytes, + to.resource == from.resource); + if (refusal == x2w_startup::CopyRefusal::none) refusal = check_roles_and_sync(self, to, from, true); if (refusal != x2w_startup::CopyRefusal::none) return refuse_copy("CopyBufferRegion", refusal); - require_copy_state(self, from, D3D12_RESOURCE_STATE_COPY_SOURCE); - require_copy_state(self, to, D3D12_RESOURCE_STATE_COPY_DEST); - static_cast(self->own().real)->CopyBufferRegion(to, destination_offset, from, source_offset, bytes); + require_copy_state(self, from.resource, D3D12_RESOURCE_STATE_COPY_SOURCE); + require_copy_state(self, to.resource, D3D12_RESOURCE_STATE_COPY_DEST); + static_cast(self->own().real) + ->CopyBufferRegion(to.resource, destination_offset, from.resource, source_offset, bytes); + mark_gpu_written(to); InterlockedIncrement(&list_buffer_copies); } @@ -63,37 +143,45 @@ void __stdcall list_copy_buffer_region(Wrapper* self, u64 destination, u64 desti void __stdcall list_copy_resource(Wrapper* self, u64 destination, u64 source) { if (!self->own().list_open) return; - ID3D12Resource* const to = copy_endpoint(destination); - ID3D12Resource* const from = copy_endpoint(source); + const CopyEndpoint to = copy_endpoint(destination); + const CopyEndpoint from = copy_endpoint(source); D3D12_RESOURCE_DESC to_desc{}, from_desc{}; - if (to) to_desc = to->GetDesc(); - if (from) from_desc = from->GetDesc(); - const auto refusal = x2w_startup::check_copy_resource(to ? &to_desc : nullptr, from ? &from_desc : nullptr, to == from); + if (to.resource) to_desc = to.resource->GetDesc(); + if (from.resource) from_desc = from.resource->GetDesc(); + auto refusal = x2w_startup::check_copy_resource(to.resource ? &to_desc : nullptr, from.resource ? &from_desc : nullptr, + to.resource == from.resource); + if (refusal == x2w_startup::CopyRefusal::none) refusal = check_roles_and_sync(self, to, from, true); if (refusal != x2w_startup::CopyRefusal::none) return refuse_copy("CopyResource", refusal); - require_copy_state(self, from, D3D12_RESOURCE_STATE_COPY_SOURCE); - require_copy_state(self, to, D3D12_RESOURCE_STATE_COPY_DEST); - static_cast(self->own().real)->CopyResource(to, from); + require_copy_state(self, from.resource, D3D12_RESOURCE_STATE_COPY_SOURCE); + require_copy_state(self, to.resource, D3D12_RESOURCE_STATE_COPY_DEST); + static_cast(self->own().real)->CopyResource(to.resource, from.resource); + mark_gpu_written(to); InterlockedIncrement(&list_resource_copies); } // List slot 19, ResolveSubresource(destination, destination subresource, source, source subresource, format). // The format is a console value, mapped like a resource format; a typeless one resolves as its typed choice. +// The source is multisampled, which no title memory can back, so it needs no synchronisation. void __stdcall list_resolve_subresource(Wrapper* self, u64 destination, UINT destination_subresource, u64 source, UINT source_subresource, UINT format) { if (!self->own().list_open) return; - ID3D12Resource* const to = copy_endpoint(destination); - ID3D12Resource* const from = copy_endpoint(source); + const CopyEndpoint to = copy_endpoint(destination); + const CopyEndpoint from = copy_endpoint(source); D3D12_RESOURCE_DESC to_desc{}, from_desc{}; - if (to) to_desc = to->GetDesc(); - if (from) from_desc = from->GetDesc(); - const auto plan = x2w_startup::plan_resolve(to ? &to_desc : nullptr, destination_subresource, from ? &from_desc : nullptr, - source_subresource, desktop_format(static_cast(format)), to == from); - if (plan.refusal != x2w_startup::CopyRefusal::none) return refuse_copy("ResolveSubresource", plan.refusal); - require_copy_state(self, from, D3D12_RESOURCE_STATE_RESOLVE_SOURCE); - require_copy_state(self, to, D3D12_RESOURCE_STATE_RESOLVE_DEST); + if (to.resource) to_desc = to.resource->GetDesc(); + if (from.resource) from_desc = from.resource->GetDesc(); + const auto plan = x2w_startup::plan_resolve(to.resource ? &to_desc : nullptr, destination_subresource, + from.resource ? &from_desc : nullptr, source_subresource, + desktop_format(static_cast(format)), to.resource == from.resource); + auto refusal = plan.refusal; + if (refusal == x2w_startup::CopyRefusal::none) refusal = check_roles_and_sync(self, to, from, false); + if (refusal != x2w_startup::CopyRefusal::none) return refuse_copy("ResolveSubresource", refusal); + require_copy_state(self, from.resource, D3D12_RESOURCE_STATE_RESOLVE_SOURCE); + require_copy_state(self, to.resource, D3D12_RESOURCE_STATE_RESOLVE_DEST); static_cast(self->own().real) - ->ResolveSubresource(to, destination_subresource, from, source_subresource, plan.format); + ->ResolveSubresource(to.resource, destination_subresource, from.resource, source_subresource, plan.format); + mark_gpu_written(to); InterlockedIncrement(&list_resolves); } diff --git a/tests/startup_list_copy.cpp b/tests/startup_list_copy.cpp index 9e272464c7..72dc51ed8b 100644 --- a/tests/startup_list_copy.cpp +++ b/tests/startup_list_copy.cpp @@ -12,7 +12,8 @@ // 4. the same with a typeless half-float pair and a typeless format argument half float 1.0 in red // 5. an upload buffer copied to a buffer, then 64 bytes at another offset into a third exact bytes // 6. refused and counted, forwarded to nothing: a CopyResource between different sizes, a null source, -// a resolve from a one-sample source, a buffer range that runs past its end +// a resolve from a one-sample source, a buffer range that runs past its end, a copy into an upload +// buffer and a copy out of a readback buffer // 7. after Close, the same calls change no counter // // The desktop device must not be removed and the debug layer must store no errors. @@ -291,6 +292,10 @@ int main(int argc, char** argv) if (!step("6c ResolveSubresource from one sample", {0, 0, 0, 1}, seen)) return 17; invoke(list, 15, arg(buffer_y.Get()), 0, arg(buffer_x.Get()), 200, 100); if (!step("6d CopyBufferRegion past the end", {0, 0, 0, 1}, seen)) return 18; + invoke(list, 15, arg(upload_u.Get()), 0, arg(buffer_x.Get()), 0, 16); + if (!step("6e CopyBufferRegion into an upload buffer", {0, 0, 0, 1}, seen)) return 28; + invoke(list, 15, arg(buffer_y.Get()), 0, arg(probe.readback.Get()), 0, 16); + if (!step("6f CopyBufferRegion out of a readback buffer", {0, 0, 0, 1}, seen)) return 29; invoke(list, 9); if (!probe.submit(list)) return 19; diff --git a/tests/startup_list_copy_check.cpp b/tests/startup_list_copy_check.cpp index ad6e887e63..fde663338e 100644 --- a/tests/startup_list_copy_check.cpp +++ b/tests/startup_list_copy_check.cpp @@ -127,7 +127,33 @@ int main(int argc, char** argv) const auto mip_source = texture(2, 2, DXGI_FORMAT_R8G8B8A8_UNORM, 4); check("resolve a smaller mip", plan_resolve(&mips_target, 1, &mip_source, 0, DXGI_FORMAT_R8G8B8A8_UNORM, false).refusal == CopyRefusal::none); - check("names", std::strcmp(copy_refusal_name(CopyRefusal::range_overflow), "range_overflow") == 0 && + // The resolve format follows a fully typed endpoint exactly; a typeless endpoint takes any member of its family. + const auto srgb_target = texture(4, 4, DXGI_FORMAT_R8G8B8A8_UNORM_SRGB); + const auto typeless_msaa = texture(4, 4, DXGI_FORMAT_R8G8B8A8_TYPELESS, 4); + const ResolvePlan typed_target = plan_resolve(&srgb_target, 0, &typeless_msaa, 0, DXGI_FORMAT_UNKNOWN, false); + check("resolve unknown over a typed destination", typed_target.refusal == CopyRefusal::none && + typed_target.format == DXGI_FORMAT_R8G8B8A8_UNORM_SRGB); + check("resolve format against a typed destination", plan_resolve(&srgb_target, 0, &typeless_msaa, 0, DXGI_FORMAT_R8G8B8A8_UNORM, + false).refusal == CopyRefusal::format_mismatch); + const auto srgb_msaa = texture(4, 4, DXGI_FORMAT_R8G8B8A8_UNORM_SRGB, 4); + check("resolve typed endpoints that differ", plan_resolve(&rgba, 0, &srgb_msaa, 0, DXGI_FORMAT_UNKNOWN, false).refusal == + CopyRefusal::format_mismatch); + + // Families beyond the colour formats the resolve choice covers. + const auto bc7_typeless = texture(8, 8, DXGI_FORMAT_BC7_TYPELESS), bc7 = texture(8, 8, DXGI_FORMAT_BC7_UNORM), + bc1 = texture(8, 8, DXGI_FORMAT_BC1_UNORM), r16_typeless = texture(4, 4, DXGI_FORMAT_R16_TYPELESS), + r16 = texture(4, 4, DXGI_FORMAT_R16_UNORM), r8 = texture(4, 4, DXGI_FORMAT_R8_UNORM), + r8_typeless = texture(4, 4, DXGI_FORMAT_R8_TYPELESS); + check("copy BC7 typeless to typed", check_copy_resource(&bc7, &bc7_typeless, false) == CopyRefusal::none); + check("copy BC7 to BC1", check_copy_resource(&bc7, &bc1, false) == CopyRefusal::format_mismatch); + check("copy R16 typeless to typed", check_copy_resource(&r16, &r16_typeless, false) == CopyRefusal::none); + check("copy R8 typeless to typed", check_copy_resource(&r8, &r8_typeless, false) == CopyRefusal::none); + check("copy R8 to R16", check_copy_resource(&r8, &r16, false) == CopyRefusal::format_mismatch); + + check("names", std::strcmp(copy_refusal_name(CopyRefusal::heap_direction), "heap_direction") == 0 && + std::strcmp(copy_refusal_name(CopyRefusal::initial_state), "initial_state") == 0 && + std::strcmp(copy_refusal_name(CopyRefusal::title_backed_source), "title_backed_source") == 0 && + std::strcmp(copy_refusal_name(CopyRefusal::range_overflow), "range_overflow") == 0 && std::strcmp(copy_refusal_name(CopyRefusal::none), "none") == 0); if (failures) return 1; From fbeda917192ce38920c8cfa6f38ddeda40fa1299 Mon Sep 17 00:00:00 2001 From: tedin7 Date: Wed, 25 Nov 2026 06:40:12 +0100 Subject: [PATCH 3/9] startup: refuse list copies from title memory that cannot be staged; drop the upload-buffer recopy A title-backed texture is copied from only when the draw path's upload staged it (or the GPU wrote it); otherwise the copy is refused and the destination is untouched. A title-backed upload buffer is refused instead of being rewritten while an earlier submission may still read it. Aliased placed buffers and direct resources are unchanged. Tests: staged and unreadable title-backed sources. --- docs/startup-runtime.md | 6 ++--- src/startup_stubs/d3d12_draw.inl | 4 ++++ src/startup_stubs/list_copy.inl | 28 ++++++++++------------ tests/startup_list_copy.cpp | 41 ++++++++++++++++++++++++++++++-- 4 files changed, 58 insertions(+), 21 deletions(-) diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index fdc4776751..4bbf94073c 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -428,9 +428,9 @@ desktop would reject is counted, logged (first six) and not forwarded, with the `bad_subresource`, `source_not_multisampled`, `destination_multisampled`, `bad_format`, `zero_size` or `range_overflow`, `heap_direction` (an upload buffer as a destination, a readback buffer as a source), `initial_state` (a placed buffer that does not start in COMMON) or `title_backed_source` (a title-backed default-heap -buffer, which has no desktop copy to refresh). A source the title maps at its own memory is brought up to date first: a -texture takes the draw path's upload, an upload buffer is copied through a desktop mapping, and an aliased placed buffer -is already current. A copy or resolve destination with title memory is marked GPU-written, so a later draw does not +buffer or an upload buffer, which have no desktop copy the list can refresh without rewriting bytes an earlier submission may +still read). A source the title maps at its own memory must be current: a texture takes the draw path's upload and is refused +when that upload cannot stage it (unreadable or unsupported memory), and an aliased placed buffer is already current. A copy or resolve destination with title memory is marked GPU-written, so a later draw does not upload the stale title memory over the result. CopyResource accepts formats of one DXGI family (colour, depth, 8/16/32-bit and block-compressed). A resolve format is exact against a fully typed endpoint and only family-compatible with a typeless one; a typeless resolve format (or an unknown one over typeless endpoints) resolves as the family's typed diff --git a/src/startup_stubs/d3d12_draw.inl b/src/startup_stubs/d3d12_draw.inl index 9a6b23dcac..30cc821cc3 100644 --- a/src/startup_stubs/d3d12_draw.inl +++ b/src/startup_stubs/d3d12_draw.inl @@ -771,6 +771,7 @@ struct TextureUpload { bool done = false, tiled = false; ID3D12CommandList* pending_list = nullptr; u64 revision = 0; + bool staged = false; // the last upload attempt put the title memory into the desktop texture bool gpu_written = false; // a list copy or resolve wrote the texture; its title memory is stale and must not be uploaded }; std::unordered_map& texture_uploads() { static std::unordered_map m; return m; } @@ -1085,6 +1086,7 @@ bool upload_texture(Wrapper* self, Wrapper* resource, ID3D12Resource* texture) if (!state.done) InterlockedIncrement(&textures_unreadable); if (console) return false; state.done = true; + state.staged = false; state.generation = generation; return true; } @@ -1110,6 +1112,7 @@ bool upload_texture(Wrapper* self, Wrapper* resource, ID3D12Resource* texture) } std::memset(owned.cpu, 0, static_cast(bytes)); } + state.staged = false; require_state(self, texture, D3D12_RESOURCE_STATE_COPY_DEST); if (console) { for (UINT slice = 0; slice < slices; ++slice) { @@ -1180,6 +1183,7 @@ bool upload_texture(Wrapper* self, Wrapper* resource, ID3D12Resource* texture) state.checked_frame = frame_number; state.tiled = tiled; state.done = true; + state.staged = true; InterlockedIncrement(&textures_uploaded); InterlockedExchangeAdd(&texture_bytes_uploaded, static_cast(total >> 10)); static LONG shown; diff --git a/src/startup_stubs/list_copy.inl b/src/startup_stubs/list_copy.inl index 101ecbcae5..66cd6420ed 100644 --- a/src/startup_stubs/list_copy.inl +++ b/src/startup_stubs/list_copy.inl @@ -72,29 +72,25 @@ void require_copy_state(Wrapper* self, ID3D12Resource* resource, D3D12_RESOURCE_ } // A resource the title maps at its own memory has a desktop resource that map and unmap never touch. Before -// that resource is copied from, bring it up to date: a texture takes the draw path's upload, an upload buffer -// takes the bytes through a desktop mapping, and a placed buffer aliasing the memory is already current. -// False for a title-backed default-heap buffer, which has no desktop copy the list can refresh. +// that resource is copied from, it must be current: a texture takes the draw path's upload, and a placed buffer +// aliasing the memory already is. False when the desktop copy cannot be trusted: a texture the upload could not +// stage, or a title-backed buffer in a default or upload heap. An upload buffer is refused because refreshing it +// would rewrite one backing that an earlier submission may still be reading. bool sync_title_source(Wrapper* self, const CopyEndpoint& source) { if (!source.wrapper || !source.wrapper->own().title_memory) return true; const D3D12_RESOURCE_DESC desc = source.resource->GetDesc(); if (desc.Dimension != D3D12_RESOURCE_DIMENSION_BUFFER) { - upload_texture(self, source.wrapper, source.resource); - return true; + // A target or UAV holds what the GPU wrote; its title memory is never uploaded. + if (desc.Flags & (D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET | D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL | D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS)) return true; + const auto written = texture_uploads().find(source.resource); + if (written != texture_uploads().end() && written->second.gpu_written) return true; + if (!upload_texture(self, source.wrapper, source.resource)) return false; + const auto found = texture_uploads().find(source.resource); + return found != texture_uploads().end() && found->second.staged; } const auto* info = resource_info(source.wrapper); - if (info && info->placement == Placement::aliased_buffer) return true; - D3D12_HEAP_TYPE type; - if (!fixed_heap(source.resource, type) || type != D3D12_HEAP_TYPE_UPLOAD) return false; - const u64 memory = reinterpret_cast(source.wrapper->own().title_memory); - if (readable_window(memory, static_cast(desc.Width)) < desc.Width) return false; - void* mapped = nullptr; - const D3D12_RANGE none{0, 0}; - if (FAILED(source.resource->Map(0, &none, &mapped)) || !mapped) return false; - std::memcpy(mapped, reinterpret_cast(memory), static_cast(desc.Width)); - source.resource->Unmap(0, nullptr); - return true; + return info && info->placement == Placement::aliased_buffer; } // A copy or resolve destination now holds what the GPU wrote. A title-backed texture would otherwise be diff --git a/tests/startup_list_copy.cpp b/tests/startup_list_copy.cpp index 72dc51ed8b..cf5bb67f4a 100644 --- a/tests/startup_list_copy.cpp +++ b/tests/startup_list_copy.cpp @@ -14,7 +14,9 @@ // 6. refused and counted, forwarded to nothing: a CopyResource between different sizes, a null source, // a resolve from a one-sample source, a buffer range that runs past its end, a copy into an upload // buffer and a copy out of a readback buffer -// 7. after Close, the same calls change no counter +// 7. a title-backed texture copied to a texture: the destination holds its texels; one whose memory cannot +// be read is refused and the destination stays empty +// 8. after Close, the same calls change no counter // // The desktop device must not be removed and the debug layer must store no errors. // @@ -256,6 +258,27 @@ int main(int argc, char** argv) invoke(device, 20, arg(msaa_m.Get()), arg(&multisampled), view_m.ptr); invoke(device, 20, arg(msaa_h.Get()), arg(&multisampled_half), view_h.ptr); + // Title-backed textures, placed at addresses of the title's own memory (device slot 133). One holds a known + // pattern; the other has its pages decommitted, so no upload can stage it. + constexpr std::uint32_t title_texel = 0x44332211; + constexpr std::size_t title_bytes = 0x10000; + auto* const readable_memory = static_cast(VirtualAlloc(nullptr, title_bytes, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); + auto* const gone_memory = static_cast(VirtualAlloc(nullptr, title_bytes, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); + if (!readable_memory || !gone_memory) return 30; + for (std::size_t i = 0; i < title_bytes / sizeof(std::uint32_t); ++i) readable_memory[i] = title_texel; + VirtualFree(gone_memory, title_bytes, MEM_DECOMMIT); + const D3D12_RESOURCE_DESC title_desc = texture(4, DXGI_FORMAT_R8G8B8A8_UNORM, 1, none); + void *title_readable = nullptr, *title_gone = nullptr; + ComPtr dest_readable, dest_gone; + if (!create(title_desc, D3D12_RESOURCE_STATE_COMMON, nullptr, dest_readable) || + !create(title_desc, D3D12_RESOURCE_STATE_COMMON, nullptr, dest_gone)) + return 31; + if (!ok(invoke(device, 133, arg(readable_memory), arg(&title_desc), D3D12_RESOURCE_STATE_COMMON, 0, arg(&__uuidof(ID3D12Resource)), + arg(&title_readable))) || !title_readable || + !ok(invoke(device, 133, arg(gone_memory), arg(&title_desc), D3D12_RESOURCE_STATE_COMMON, 0, arg(&__uuidof(ID3D12Resource)), + arg(&title_gone))) || !title_gone) + return 32; + D3D12_COMMAND_QUEUE_DESC queue_desc{}; const unsigned list_desc[] = {D3D12_COMMAND_LIST_TYPE_DIRECT, 2, 1, 0}; void *allocator = nullptr, *list = nullptr; @@ -297,12 +320,19 @@ int main(int argc, char** argv) invoke(list, 15, arg(buffer_y.Get()), 0, arg(probe.readback.Get()), 0, 16); if (!step("6f CopyBufferRegion out of a readback buffer", {0, 0, 0, 1}, seen)) return 29; + // A title-backed texture source is uploaded first, and the destination holds its texels. One whose memory + // cannot be staged is refused, and the destination keeps what it had. + invoke(list, 17, arg(dest_readable.Get()), arg(title_readable)); + if (!step("8a CopyResource from a staged title-backed texture", {0, 1, 0, 0}, seen)) return 33; + invoke(list, 17, arg(dest_gone.Get()), arg(title_gone)); + if (!step("8b CopyResource from an unreadable title-backed texture", {0, 0, 0, 1}, seen)) return 34; + invoke(list, 9); if (!probe.submit(list)) return 19; invoke(list, 17, arg(copy_b.Get()), arg(empty_d.Get())); invoke(list, 19, arg(resolved_r.Get()), 0, arg(msaa_m.Get()), 0, DXGI_FORMAT_R8G8B8A8_UNORM); invoke(list, 15, arg(buffer_y.Get()), 0, arg(buffer_x.Get()), 0, 16); - if (!step("7 calls on a closed list", {0, 0, 0, 0}, seen)) return 20; + if (!step("9 calls on a closed list", {0, 0, 0, 0}, seen)) return 20; const std::uint32_t copied = probe.texel(copy_b.Get()); const std::uint32_t swapped_source = probe.texel(empty_d.Get()); @@ -318,6 +348,13 @@ int main(int argc, char** argv) if (resolved != green_bits) return 23; if (resolved_half != half_one) return 24; + const std::uint32_t staged_copy = probe.texel(dest_readable.Get()); + const std::uint32_t refused_copy = probe.texel(dest_gone.Get()); + std::printf("title-backed source copied: %08x (expected %08x), refused source copy leaves destination: %08x (expected 00000000)\n", + staged_copy, title_texel, refused_copy); + if (staged_copy != title_texel) return 35; + if (refused_copy != 0) return 36; + std::vector whole, moved; if (!probe.bytes(buffer_x.Get(), 256, whole) || !probe.bytes(buffer_y.Get(), 80, moved)) return 25; if (std::memcmp(whole.data(), pattern.data(), pattern.size()) != 0) return 26; From 3f7b8a5f828988333a793adaaa4be1068e4d6099 Mon Sep 17 00:00:00 2001 From: tedin7 Date: Wed, 25 Nov 2026 06:41:32 +0100 Subject: [PATCH 4/9] test: create the title-backed copy destinations in a default heap --- tests/startup_list_copy.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/tests/startup_list_copy.cpp b/tests/startup_list_copy.cpp index cf5bb67f4a..298c5b9187 100644 --- a/tests/startup_list_copy.cpp +++ b/tests/startup_list_copy.cpp @@ -267,6 +267,7 @@ int main(int argc, char** argv) if (!readable_memory || !gone_memory) return 30; for (std::size_t i = 0; i < title_bytes / sizeof(std::uint32_t); ++i) readable_memory[i] = title_texel; VirtualFree(gone_memory, title_bytes, MEM_DECOMMIT); + heap.Type = D3D12_HEAP_TYPE_DEFAULT; const D3D12_RESOURCE_DESC title_desc = texture(4, DXGI_FORMAT_R8G8B8A8_UNORM, 1, none); void *title_readable = nullptr, *title_gone = nullptr; ComPtr dest_readable, dest_gone; From 0aafe6b98eae8814c59bfd5ae8d5fa7717ed1646 Mon Sep 17 00:00:00 2001 From: tedin7 Date: Wed, 25 Nov 2026 07:19:55 +0100 Subject: [PATCH 5/9] startup: mark list copy destinations GPU-written on submission, not while recording A copy recorded then discarded by Close and Reset no longer stops the destination's first upload from title memory. Pending writes are tracked per recording, read by that list, committed by ExecuteCommandLists and dropped on Reset or a failed Close. --- docs/startup-runtime.md | 4 +- src/startup_stubs/d3d12_draw.inl | 2 + src/startup_stubs/d3d12_xs_device.cpp | 5 +++ src/startup_stubs/list_copy.inl | 61 +++++++++++++++++++++++---- tests/startup_list_copy.cpp | 26 +++++++++++- 5 files changed, 86 insertions(+), 12 deletions(-) diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index 4bbf94073c..89b330ebd6 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -430,8 +430,8 @@ desktop would reject is counted, logged (first six) and not forwarded, with the `initial_state` (a placed buffer that does not start in COMMON) or `title_backed_source` (a title-backed default-heap buffer or an upload buffer, which have no desktop copy the list can refresh without rewriting bytes an earlier submission may still read). A source the title maps at its own memory must be current: a texture takes the draw path's upload and is refused -when that upload cannot stage it (unreadable or unsupported memory), and an aliased placed buffer is already current. A copy or resolve destination with title memory is marked GPU-written, so a later draw does not -upload the stale title memory over the result. CopyResource accepts formats of one DXGI family (colour, depth, 8/16/32-bit +when that upload cannot stage it (unreadable or unsupported memory), and an aliased placed buffer is already current. A copy or resolve destination with title memory is marked GPU-written when its list is submitted (on its own list at once), so a later draw does not +upload the stale title memory over the result; a list discarded by Reset or a failed Close marks nothing. CopyResource accepts formats of one DXGI family (colour, depth, 8/16/32-bit and block-compressed). A resolve format is exact against a fully typed endpoint and only family-compatible with a typeless one; a typeless resolve format (or an unknown one over typeless endpoints) resolves as the family's typed choice: half float for `R16G16B16A16`, normalised for the 8-bit and 10-bit families. Calls on a closed list are ignored. diff --git a/src/startup_stubs/d3d12_draw.inl b/src/startup_stubs/d3d12_draw.inl index 30cc821cc3..52c164203c 100644 --- a/src/startup_stubs/d3d12_draw.inl +++ b/src/startup_stubs/d3d12_draw.inl @@ -1003,6 +1003,7 @@ u64 hash_memory(const unsigned char* data, std::size_t bytes) for (std::size_t i = words * 8; i < bytes; ++i) h = (h ^ data[i]) * 0x100000001b3ull; return h; } +bool list_wrote(Wrapper* list, ID3D12Resource* resource); // list_copy.inl bool upload_texture(Wrapper* self, Wrapper* resource, ID3D12Resource* texture) { auto* const memory = static_cast(resource->own().title_memory); @@ -1026,6 +1027,7 @@ bool upload_texture(Wrapper* self, Wrapper* resource, ID3D12Resource* texture) } } if (!memory || !list || !uploadable) return !console; + if (list_wrote(self, texture)) return !console; // this recording's own copy; not yet submitted if (const auto written_by_gpu = texture_uploads().find(texture); written_by_gpu != texture_uploads().end() && written_by_gpu->second.gpu_written) return !console; if (desc.Flags & (D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET | D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL | D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS)) return !console; const UINT mips = desc.MipLevels ? desc.MipLevels : 1; diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index 9e38a276e6..264edb7c05 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -1085,6 +1085,8 @@ HRESULT __stdcall device_residency(Wrapper* self, UINT count, void* const* objec void release_targets(Wrapper* self); 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 discard_draw_sampler_heaps(ID3D12CommandList* list); void discard_address_uploads(ID3D12CommandList* list); void use_as_target(Wrapper* self, ID3D12Resource* resource); @@ -1410,6 +1412,7 @@ HRESULT __stdcall list_reset(Wrapper* self, void* allocator) ReleaseSRWLockExclusive(&allocator_lock); if (SUCCEEDED(hr)) { reset_list_dynamic_state(self); + discard_list_gpu_writes(self); discard_draw_sampler_heaps(previous); discard_address_uploads(previous); if (draw_dump_frame()) draw_dumps().discard(previous); @@ -1444,6 +1447,7 @@ HRESULT __stdcall list_close(Wrapper* self) ReleaseSRWLockExclusive(&allocator_lock); InterlockedIncrement(&render_closes); if (FAILED(hr)) { + discard_list_gpu_writes(self); discard_draw_sampler_heaps(list); discard_address_uploads(list); if (draw_dump_frame()) draw_dumps().discard(list); @@ -2726,6 +2730,7 @@ void __stdcall queue_execute(Wrapper* self, UINT count, void* const* lists) retire_address_uploads(queue, ready); retire_draw_sampler_heaps(queue, ready); note_submits(queue, submitted); + for (Wrapper* w : submitted) commit_list_gpu_writes(w); InterlockedIncrement(&render_executes); } ReleaseSRWLockExclusive(&allocator_lock); diff --git a/src/startup_stubs/list_copy.inl b/src/startup_stubs/list_copy.inl index 66cd6420ed..b144d04e9b 100644 --- a/src/startup_stubs/list_copy.inl +++ b/src/startup_stubs/list_copy.inl @@ -84,6 +84,7 @@ bool sync_title_source(Wrapper* self, const CopyEndpoint& source) // A target or UAV holds what the GPU wrote; its title memory is never uploaded. if (desc.Flags & (D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET | D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL | D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS)) return true; const auto written = texture_uploads().find(source.resource); + if (list_wrote(self, source.resource)) return true; if (written != texture_uploads().end() && written->second.gpu_written) return true; if (!upload_texture(self, source.wrapper, source.resource)) return false; const auto found = texture_uploads().find(source.resource); @@ -93,14 +94,56 @@ bool sync_title_source(Wrapper* self, const CopyEndpoint& source) return info && info->placement == Placement::aliased_buffer; } -// A copy or resolve destination now holds what the GPU wrote. A title-backed texture would otherwise be -// uploaded over it from its stale memory the first time a draw samples it. -void mark_gpu_written(const CopyEndpoint& destination) +// Copy and resolve destinations a recording wrote but no ExecuteCommandLists has submitted. A discarded +// recording (Reset or a failed Close) must leave the destination's title memory uploadable, so the state a +// draw consults changes only on submission. A closed list stays submittable until its next Reset, so +// commit leaves the records in place and only Reset or a failed Close drops them. +SRWLOCK pending_writes_lock = SRWLOCK_INIT; +std::unordered_map>& pending_gpu_writes() +{ + static std::unordered_map> m; + return m; +} + +bool list_wrote(Wrapper* list, ID3D12Resource* resource) +{ + AcquireSRWLockShared(&pending_writes_lock); + bool found = false; + if (const auto it = pending_gpu_writes().find(list); it != pending_gpu_writes().end()) + found = std::find(it->second.begin(), it->second.end(), resource) != it->second.end(); + ReleaseSRWLockShared(&pending_writes_lock); + return found; +} + +void discard_list_gpu_writes(Wrapper* self) +{ + AcquireSRWLockExclusive(&pending_writes_lock); + pending_gpu_writes().erase(self); + ReleaseSRWLockExclusive(&pending_writes_lock); +} + +void commit_list_gpu_writes(Wrapper* self) +{ + AcquireSRWLockShared(&pending_writes_lock); + if (const auto it = pending_gpu_writes().find(self); it != pending_gpu_writes().end()) { + for (ID3D12Resource* resource : it->second) { + TextureUpload& state = texture_uploads()[resource]; + state.gpu_written = true; + state.done = true; + } + } + ReleaseSRWLockShared(&pending_writes_lock); +} + +// A copy or resolve destination will hold what the GPU wrote once `self` is submitted. A title-backed texture +// would otherwise be uploaded over it from its stale memory the first time a draw samples it. +void mark_gpu_written(Wrapper* self, const CopyEndpoint& destination) { if (!destination.wrapper || !destination.wrapper->own().title_memory) return; - TextureUpload& state = texture_uploads()[destination.resource]; - state.gpu_written = true; - state.done = true; + AcquireSRWLockExclusive(&pending_writes_lock); + auto& writes = pending_gpu_writes()[self]; + if (std::find(writes.begin(), writes.end(), destination.resource) == writes.end()) writes.push_back(destination.resource); + ReleaseSRWLockExclusive(&pending_writes_lock); } // Refusal shared by the three handlers once the descriptions passed, or none. @@ -131,7 +174,7 @@ void __stdcall list_copy_buffer_region(Wrapper* self, u64 destination, u64 desti require_copy_state(self, to.resource, D3D12_RESOURCE_STATE_COPY_DEST); static_cast(self->own().real) ->CopyBufferRegion(to.resource, destination_offset, from.resource, source_offset, bytes); - mark_gpu_written(to); + mark_gpu_written(self, to); InterlockedIncrement(&list_buffer_copies); } @@ -151,7 +194,7 @@ void __stdcall list_copy_resource(Wrapper* self, u64 destination, u64 source) require_copy_state(self, from.resource, D3D12_RESOURCE_STATE_COPY_SOURCE); require_copy_state(self, to.resource, D3D12_RESOURCE_STATE_COPY_DEST); static_cast(self->own().real)->CopyResource(to.resource, from.resource); - mark_gpu_written(to); + mark_gpu_written(self, to); InterlockedIncrement(&list_resource_copies); } @@ -177,7 +220,7 @@ void __stdcall list_resolve_subresource(Wrapper* self, u64 destination, UINT des require_copy_state(self, to.resource, D3D12_RESOURCE_STATE_RESOLVE_DEST); static_cast(self->own().real) ->ResolveSubresource(to.resource, destination_subresource, from.resource, source_subresource, plan.format); - mark_gpu_written(to); + mark_gpu_written(self, to); InterlockedIncrement(&list_resolves); } diff --git a/tests/startup_list_copy.cpp b/tests/startup_list_copy.cpp index 298c5b9187..70dc5c6d61 100644 --- a/tests/startup_list_copy.cpp +++ b/tests/startup_list_copy.cpp @@ -17,6 +17,8 @@ // 7. a title-backed texture copied to a texture: the destination holds its texels; one whose memory cannot // be read is refused and the destination stays empty // 8. after Close, the same calls change no counter +// 9. a copy into a title-backed texture, discarded by Close and Reset unsubmitted: a later copy out of that +// texture still reads its own memory // // The desktop device must not be removed and the debug layer must store no errors. // @@ -267,15 +269,23 @@ int main(int argc, char** argv) if (!readable_memory || !gone_memory) return 30; for (std::size_t i = 0; i < title_bytes / sizeof(std::uint32_t); ++i) readable_memory[i] = title_texel; VirtualFree(gone_memory, title_bytes, MEM_DECOMMIT); + // A third placed texture whose only copy is recorded and then discarded without a submission. + auto* const discard_memory = static_cast(VirtualAlloc(nullptr, title_bytes, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); + if (!discard_memory) return 30; + for (std::size_t i = 0; i < title_bytes / sizeof(std::uint32_t); ++i) discard_memory[i] = title_texel; heap.Type = D3D12_HEAP_TYPE_DEFAULT; const D3D12_RESOURCE_DESC title_desc = texture(4, DXGI_FORMAT_R8G8B8A8_UNORM, 1, none); void *title_readable = nullptr, *title_gone = nullptr; - ComPtr dest_readable, dest_gone; + void* title_discarded = nullptr; + ComPtr dest_readable, dest_gone, discard_out; if (!create(title_desc, D3D12_RESOURCE_STATE_COMMON, nullptr, dest_readable) || + !create(title_desc, D3D12_RESOURCE_STATE_COMMON, nullptr, discard_out) || !create(title_desc, D3D12_RESOURCE_STATE_COMMON, nullptr, dest_gone)) return 31; if (!ok(invoke(device, 133, arg(readable_memory), arg(&title_desc), D3D12_RESOURCE_STATE_COMMON, 0, arg(&__uuidof(ID3D12Resource)), arg(&title_readable))) || !title_readable || + !ok(invoke(device, 133, arg(discard_memory), arg(&title_desc), D3D12_RESOURCE_STATE_COMMON, 0, arg(&__uuidof(ID3D12Resource)), + arg(&title_discarded))) || !title_discarded || !ok(invoke(device, 133, arg(gone_memory), arg(&title_desc), D3D12_RESOURCE_STATE_COMMON, 0, arg(&__uuidof(ID3D12Resource)), arg(&title_gone))) || !title_gone) return 32; @@ -356,6 +366,20 @@ int main(int argc, char** argv) if (staged_copy != title_texel) return 35; if (refused_copy != 0) return 36; + // A copy into a title-backed texture that is recorded, then discarded by Close and Reset without ever being + // submitted, did not happen: the texture still takes its first upload from its own memory. + invoke(list, 17, arg(title_discarded), arg(empty_d.Get())); + if (!step("10a CopyResource into a title-backed texture, then discarded", {0, 1, 0, 0}, seen)) return 37; + invoke(list, 9); + if (!ok(invoke(list, 139, arg(allocator), 0))) return 38; + invoke(list, 17, arg(discard_out.Get()), arg(title_discarded)); + if (!step("10b CopyResource out of the texture after the discard", {0, 1, 0, 0}, seen)) return 39; + invoke(list, 9); + if (!probe.submit(list)) return 40; + const std::uint32_t after_discard = probe.texel(discard_out.Get()); + std::printf("copy out after a discarded copy: %08x (expected %08x)\n", after_discard, title_texel); + if (after_discard != title_texel) return 41; + std::vector whole, moved; if (!probe.bytes(buffer_x.Get(), 256, whole) || !probe.bytes(buffer_y.Get(), 80, moved)) return 25; if (std::memcmp(whole.data(), pattern.data(), pattern.size()) != 0) return 26; From 18ec51de996281a294b225de507c7c9c0702d9e6 Mon Sep 17 00:00:00 2001 From: tedin7 Date: Wed, 25 Nov 2026 07:21:28 +0100 Subject: [PATCH 6/9] test: reopen the list before the discarded-copy case --- tests/startup_list_copy.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/tests/startup_list_copy.cpp b/tests/startup_list_copy.cpp index 70dc5c6d61..bf5d0676a1 100644 --- a/tests/startup_list_copy.cpp +++ b/tests/startup_list_copy.cpp @@ -368,6 +368,7 @@ int main(int argc, char** argv) // A copy into a title-backed texture that is recorded, then discarded by Close and Reset without ever being // submitted, did not happen: the texture still takes its first upload from its own memory. + if (!ok(invoke(list, 139, arg(allocator), 0))) return 38; invoke(list, 17, arg(title_discarded), arg(empty_d.Get())); if (!step("10a CopyResource into a title-backed texture, then discarded", {0, 1, 0, 0}, seen)) return 37; invoke(list, 9); From 38971e07f5347922ec716f02772a45c3aab94f8b Mon Sep 17 00:00:00 2001 From: Royoo <3230853833@qq.com> Date: Wed, 25 Nov 2026 14:42:04 +0800 Subject: [PATCH 7/9] startup: bind translated resources for bounded indirect draws --- CMakeLists.txt | 2 + docs/experiments.md | 21 +++ src/startup_stubs/d3d12_draw.inl | 104 +++++++++++++- src/startup_stubs/d3d12_xs_device.cpp | 16 ++- tests/startup_indirect_draw_indexed.cpp | 173 ++++++++++++++++++++++-- 5 files changed, 302 insertions(+), 14 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 4ac928ba39..1a9ed3df45 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1135,9 +1135,11 @@ target_link_libraries(startup_indirect_draw_indexed PRIVATE d3d12_xs_shim d3d12 foreach(backend IN ITEMS warp hardware) add_test(NAME startup_indirect_draw_indexed_${backend} COMMAND startup_indirect_draw_indexed ${backend}) add_test(NAME startup_indirect_draw_${backend} COMMAND startup_indirect_draw_indexed ${backend} draw) + add_test(NAME startup_indirect_translated_draw_${backend} COMMAND startup_indirect_draw_indexed ${backend} translated) add_test(NAME startup_indirect_mesh_${backend} COMMAND startup_indirect_draw_indexed ${backend} mesh) set_tests_properties(startup_indirect_draw_indexed_${backend} startup_indirect_draw_${backend} PROPERTIES TIMEOUT 30) set_tests_properties(startup_indirect_mesh_${backend} PROPERTIES TIMEOUT 30 SKIP_RETURN_CODE 77) + set_tests_properties(startup_indirect_translated_draw_${backend} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77) endforeach() set_tests_properties(startup_indirect_draw_indexed_hardware startup_indirect_draw_hardware PROPERTIES SKIP_RETURN_CODE 77) # Negative control for the x2w-render indirect line: one forwarded call too many must be reported as a mismatch. diff --git a/docs/experiments.md b/docs/experiments.md index 20b7f3182a..1c80f5ca16 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -1,5 +1,26 @@ # Experiment notes and reproduction commands +### Translated indirect triangles + +`X2W_TRANSLATED_INDIRECT_DRAW=1` lets a slot 57 cached translation record one non-indexed +`ExecuteIndirect` Draw on a direct list with triangle-list topology, one single-sample colour +target, an explicit viewport and scissor, and the root signature used to create the guest pipeline. +The translated path binds its usual pipeline, root and sampled textures, then forwards the placed +desktop argument buffer and offset. Its producer supplies legal D3D12 draw arguments. The shim checks +the placed buffer range without reading the draw fields or limiting the GPU-generated vertex count. +The path refuses vertex streams, buffer SRVs, dynamic sampler heaps, unknown texture bindings and +shaders whose reflected constants depend on the draw's start vertex or instance. It also refuses +non-reflectable shader bytecode. A missing cached translation retains the request publishing path. + +Run `cmake --build --preset release --target startup_indirect_draw_indexed` and +`ctest --preset release -j1 --no-tests=error -R '^startup_indirect_translated_draw_' -V`. +The fixture compiles source-built desktop shaders and installs their translation-cache manifest. +A compute writer records one triangle at a nonzero offset in a placed GPU buffer with separate +title backing. A fenced readback compares the argument, guard words and every colour pixel. +Changing the sampled texture from red to green changes every pixel. Omitting the writer or texture, +binding the wrong root, using a short argument range or using a shader that reads the start vertex +leaves the target clear. + ### Packed pixel position in a source-built shader Run `ctest --preset dev --no-tests=error -R '^startup_packed_screen_position_(hardware|warp)$' -V`. diff --git a/src/startup_stubs/d3d12_draw.inl b/src/startup_stubs/d3d12_draw.inl index 44bcaf7bba..e1450eca83 100644 --- a/src/startup_stubs/d3d12_draw.inl +++ b/src/startup_stubs/d3d12_draw.inl @@ -23,6 +23,7 @@ struct Translation { ID3DBlob* vs = nullptr; ID3DBlob* ps = nullptr; ID3D12RootSignature* root = nullptr; + std::optional independent_indirect_entry; std::unordered_map pipelines; // by target formats u64 key = 0; LONG logged_draws = 0, logged_bindings = 0, logged_large = 0; // diagnostics budget per translation @@ -31,6 +32,7 @@ struct Translation { // Per title pipeline: its translation and the blend state found in its state block (if any). struct BoundPipeline { Translation* translation = nullptr; + const std::vector* guest_root = nullptr; bool has_blend = false; D3D12_BLEND_DESC blend{}; bool has_depth_stencil = false; @@ -562,6 +564,7 @@ BoundPipeline* translation_for(Wrapper* pipeline) u64 words[12]; std::memcpy(words, info->desc.data(), sizeof(words)); Wrapper* root = as_wrapper(reinterpret_cast(words[0])); + bound->guest_root = root ? root_info(root) : nullptr; std::vector root_blob; if (root) { AcquireSRWLockShared(¬e_lock); @@ -1330,7 +1333,49 @@ bool d16_srvs_ready(const Translation& tr, const Pass& pass, std::uint32_t (&d16 return true; } -bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UINT start, INT base_vertex, UINT start_instance) +// FXC keeps unused entry declarations in reflection. Check actual uses so a +// generated shader which reads the draw's start vertex or instance is refused. +bool indirect_shader_entry(ID3DBlob* blob, const Translation& translation) +{ + x2w_startup::ComPtr shader; + if (!blob || FAILED(D3DReflect(blob->GetBufferPointer(), blob->GetBufferSize(), IID_PPV_ARGS(shader.GetAddressOf())))) return false; + D3D12_SHADER_DESC desc{}; + if (FAILED(shader->GetDesc(&desc)) || ((desc.Version >> 4) & 0xf) != 5) return false; + for (UINT binding = 0; binding < desc.BoundResources; ++binding) { + D3D12_SHADER_INPUT_BIND_DESC input{}; + if (FAILED(shader->GetResourceBindingDesc(binding, &input))) return false; + if (input.Type != D3D_SIT_CBUFFER) continue; + if (!input.Name || std::strcmp(input.Name, "entry") || input.Space || input.BindPoint || input.BindCount != 1) return false; + auto* buffer = shader->GetConstantBufferByName(input.Name); + D3D12_SHADER_BUFFER_DESC cb{}; + if (!buffer || FAILED(buffer->GetDesc(&cb))) return false; + for (UINT i = 0; i < cb.Variables; ++i) { + D3D12_SHADER_VARIABLE_DESC var{}; + if (FAILED(buffer->GetVariableByIndex(i)->GetDesc(&var))) return false; + if (!(var.uFlags & D3D_SVF_USED)) continue; + const auto word = var.StartOffset / sizeof(UINT); + char name[16]; + std::snprintf(name, sizeof(name), "ud%u", static_cast(word)); + if (var.StartOffset % sizeof(UINT) || var.Size != sizeof(UINT) || word >= translation.uds.size() || + !var.Name || std::strcmp(var.Name, name)) return false; + const int kind = translation.uds[word].kind; + if (kind != Translation::root_constant && kind != Translation::rect && kind != Translation::d16_unorm16) + return false; + } + } + return true; +} + +struct TranslatedIndirectDraw { + ID3D12CommandSignature* signature; + ID3D12Resource* argument; + u64 offset; + u64 shader_key = 0; + const char* refusal = "translated pipeline or target unavailable"; +}; + +bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UINT start, INT base_vertex, UINT start_instance, + TranslatedIndirectDraw* indirect) { auto* list = recording(self); Pass& pass = pass_of(self); @@ -1339,11 +1384,30 @@ bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UI AcquireSRWLockExclusive(&draw_lock); BoundPipeline* bound = translation_for(pass.pipeline); Translation* tr = bound ? translation_for_targets(bound->translation, pass) : nullptr; + if (indirect && tr) indirect->shader_key = tr->key; std::uint32_t d16_unorm16[32] = {}; if (!tr || tr->state != 1 || !d16_srvs_ready(*tr, pass, d16_unorm16)) { ReleaseSRWLockExclusive(&draw_lock); return false; } + if (indirect) { + if (!bound->guest_root || bound->guest_root != pass.root) { + indirect->refusal = "translated draw requires the guest pipeline's root signature"; + ReleaseSRWLockExclusive(&draw_lock); + return false; + } + if (!tr->independent_indirect_entry.has_value()) { + tr->independent_indirect_entry = indirect_shader_entry(tr->vs, *tr) && indirect_shader_entry(tr->ps, *tr) && + std::all_of(tr->srvs.begin(), tr->srvs.end(), [](const Translation::Srv& srv) { + return srv.kind > 0 && srv.source == 0; + }); + } + if (!*tr->independent_indirect_entry || tr->samplers.heap) { + indirect->refusal = "translated draw uses an unsupported resource or draw-dependent entry value"; + ReleaseSRWLockExclusive(&draw_lock); + return false; + } + } ID3D12PipelineState* pipeline = ensure_draw_heap(self->own().list_device) ? pipeline_for(*bound, *tr, pass) : nullptr; if (!pipeline || (tr->samplers.heap && !prepare_draw_sampler_heap(pass, list, tr->samplers.reserved_fallback))) { ReleaseSRWLockExclusive(&draw_lock); @@ -1450,6 +1514,11 @@ bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UI if (srv.kind == 2) desc.Texture2DArray.ArraySize = 1; } } + if (indirect && (!texture || record.slot != 18 || texture == pass.target0)) { + indirect->refusal = "translated draw requires a matching sampled texture distinct from the target"; + ReleaseSRWLockExclusive(&draw_lock); + return false; + } if (texture && !upload_texture(self, resource, texture)) texture = nullptr; if (texture) require_state(self, texture, sampled_state(self, texture)); const bool had_texture = texture != nullptr; @@ -1471,6 +1540,11 @@ bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UI desc.Texture2D.MipLevels = 1; if (srv.kind == 2) desc.Texture2DArray.ArraySize = 1; } + if (indirect && !texture) { + indirect->refusal = "translated draw could not bind its sampled texture"; + ReleaseSRWLockExclusive(&draw_lock); + return false; + } x2w_local::BindingFacts facts; facts.texture = facts.from_table = true; facts.entry_readable = entry_ok; @@ -1619,7 +1693,14 @@ bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UI if (samplers) list->SetGraphicsRootDescriptorTable(x2w_startup::sampler_root_parameter(n), samplers->GetGPUDescriptorHandleForHeapStart()); list->IASetPrimitiveTopology(pass.topology == 5 ? D3D_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP : D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); bool drawn = false; - if (indexed) { + if (indirect) { + require_state(self, indirect->argument, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT); + list->ExecuteIndirect(indirect->signature, 1, indirect->argument, indirect->offset, nullptr, 0); + // The translated root invalidated the desktop arguments of the tracked guest root. + list->SetGraphicsRootSignature(pass.graphics_root); + pass.srv_bound = 0; + drawn = true; + } else if (indexed) { u64 offset = 0; const u64 address = index_address; const std::size_t bytes = index_total; @@ -1635,8 +1716,9 @@ bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UI drawn = true; } if (scoped_stencil_ref) list->OMSetStencilRef(pass.stencil_reference); - if (drawn) draw_dump_after(self, list, tr->key, count); + if (drawn && !indirect) draw_dump_after(self, list, tr->key, count); ReleaseSRWLockExclusive(&draw_lock); + if (indirect) return drawn; if (first_calls(tr->logged_draws, 10) || (count > 100 && first_calls(tr->logged_large, 12))) { char indices[3 * 24 + 1] = ""; if (indexed && pass.ib.BufferLocation) hex_text(reinterpret_cast(pass.ib.BufferLocation + u64{start} * 2), 24, indices, sizeof(indices)); @@ -1649,6 +1731,22 @@ bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UI return drawn; } +bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UINT start, INT base_vertex, UINT start_instance) +{ + return draw_translated(self, indexed, count, instances, start, base_vertex, start_instance, nullptr); +} + +const char* draw_translated_indirect(Wrapper* self, ID3D12CommandSignature* signature, ID3D12Resource* argument, u64 offset) +{ + TranslatedIndirectDraw draw{signature, argument, offset}; + if (!draw_translated(self, false, 0, 0, 0, 0, 0, &draw)) return draw.refusal; + InterlockedIncrement(&translated_draws); + static LONG reported; + if (first_calls(reported, 16)) + log("x2w-render translated ExecuteIndirect Draw recorded, shader %016llx, offset 0x%llx", draw.shader_key, offset); + return nullptr; +} + // List slot 32, SetDescriptorHeaps. Track the title's shader-visible sampler // source while translated draws use their own physical descriptor heaps. void __stdcall list_set_descriptor_heaps(Wrapper* self, UINT count, void* const* heaps) diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index 0a5ee4ac33..984aa9285a 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -2202,6 +2202,8 @@ enum { indirect_forwarded, indirect_graphics_pipeline, indirect_compute_pipeline indirect_outcomes }; volatile LONG64 indirect_calls[indirect_outcomes][5]; +const char* draw_translated_indirect(Wrapper* self, ID3D12CommandSignature* signature, ID3D12Resource* argument, u64 offset); + // The guest method has independent resource and byte-offset arguments. void __stdcall list_execute_indirect(Wrapper* self, void* signature, UINT count, void* argument, u64 offset, void* count_buffer, u64 count_offset) @@ -2233,14 +2235,16 @@ void __stdcall list_execute_indirect(Wrapper* self, void* signature, UINT count, const bool mesh = command == IndirectCommand::dispatch_mesh; const bool graphics = indexed || mesh || command == IndirectCommand::draw; Pass& pass = pass_of(self); + const bool translated = command == IndirectCommand::draw && pass.pipeline && !pass.pipeline->own().real && + pass.graphics_root && x2w_local::env_on("X2W_TRANSLATED_INDIRECT_DRAW"); u64 bytes = sig->own().indirect_bytes; if (graphics && (count != 1 || count_buffer)) return refuse("indirect graphics requires one command and no count buffer"); if (graphics) { if (indexed) bytes = sizeof(D3D12_DRAW_INDEXED_ARGUMENTS); else if (mesh) bytes = sizeof(D3D12_DISPATCH_MESH_ARGUMENTS); else bytes = sizeof(D3D12_DRAW_ARGUMENTS); - if (type != D3D12_COMMAND_LIST_TYPE_DIRECT || !pass.indirect_graphics.root || - pass.indirect_graphics.root != pass.graphics_root || pass.indirect_graphics.mesh != mesh) { + if (type != D3D12_COMMAND_LIST_TYPE_DIRECT || (!translated && (!pass.indirect_graphics.root || + pass.indirect_graphics.root != pass.graphics_root || pass.indirect_graphics.mesh != mesh))) { // A console pipeline (no desktop pipeline) used only here still gets the request a direct draw writes; // nothing is drawn. if (pass.pipeline && !pass.pipeline->own().real && pass.requested_pipeline != pass.pipeline) { @@ -2251,7 +2255,7 @@ void __stdcall list_execute_indirect(Wrapper* self, void* signature, UINT count, indirect_graphics_pipeline); } if (!pass.targets_bound || pass.target_count != 1 || !pass.target0 || - pass.target_formats[0] != pass.indirect_graphics.target_format || + (!translated && pass.target_formats[0] != pass.indirect_graphics.target_format) || pass.dsv_format != DXGI_FORMAT_UNKNOWN || !pass.viewport_set || !pass.scissor_set) return refuse("indirect graphics requires one matching target, viewport and scissor"); if (!mesh && pass.topology != D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST) @@ -2282,6 +2286,12 @@ void __stdcall list_execute_indirect(Wrapper* self, void* signature, UINT count, if (!info || info->initial_state != D3D12_RESOURCE_STATE_COMMON) return refuse("argument buffer does not use COMMON state tracking"); auto* resource = static_cast(buffer->own().real); + if (translated) { + const char* failure = draw_translated_indirect(self, static_cast(sig->own().real), resource, offset); + if (failure) return refuse(failure, indirect_graphics_pipeline); + InterlockedIncrement64(&indirect_calls[indirect_forwarded][static_cast(kind)]); + return; + } auto argument_state = D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT; if (indexed) { auto view = pass.ib; diff --git a/tests/startup_indirect_draw_indexed.cpp b/tests/startup_indirect_draw_indexed.cpp index 24a1a8d038..4ac78b52b0 100644 --- a/tests/startup_indirect_draw_indexed.cpp +++ b/tests/startup_indirect_draw_indexed.cpp @@ -12,6 +12,7 @@ #include #include #include +#include #include #include #include @@ -85,6 +86,21 @@ float4 pixel(Varying input) : SV_Target { discard; return float4(0, 0, 0, 1); } +cbuffer entry : register(b0) { uint ud0; uint ud1; }; +Texture2D translated_texture : register(t0); + +float4 translated_vertex(uint id : SV_VertexID) : SV_Position { + return float4(id == 2 ? 3 : -1, id == 1 ? 3 : -1, 0, 1); +} + +float4 translated_vertex_with_start(uint id : SV_VertexID) : SV_Position { + return translated_vertex(id + ud1); +} + +float4 translated_pixel() : SV_Target { + return translated_texture.Load(int3(0, 0, 0)); +} + )"; template @@ -119,16 +135,62 @@ ComPtr compile(const char* entry, const char* profile) return code; } -ComPtr create_root(ID3D12Device* device, const D3D12_ROOT_SIGNATURE_DESC& desc) +ComPtr create_root(ID3D12Device* device, const D3D12_ROOT_SIGNATURE_DESC& desc, + ComPtr* serialized = nullptr) { ComPtr code; check(D3D12SerializeRootSignature(&desc, D3D_ROOT_SIGNATURE_VERSION_1, &code, nullptr), "serialize root"); ComPtr root; check(device->CreateRootSignature(0, code->GetBufferPointer(), code->GetBufferSize(), IID_PPV_ARGS(&root)), "create root"); + if (serialized) *serialized = code; return root; } +ComPtr translated_pipeline(ID3D12Device* guest, ID3D12RootSignature* root, ID3DBlob* root_blob, bool needs_start) +{ + // The opaque guest programs identify synthetic cache entries. The actual bound shaders are source-built DXBC. + constexpr char revision[] = "x2w-startup-shader-8"; + static std::uint32_t vertex_ids[]{0xe0000101, 0xe0000102}; + static std::uint32_t pixel_id = 0xe0000202; + auto& vertex_id = vertex_ids[needs_start]; + std::uint64_t key = 1469598103934665603ull; + const auto add = [&key](const void* data, std::size_t bytes) { + const auto* p = static_cast(data); + for (std::size_t i = 0; i < bytes; ++i) key = (key ^ p[i]) * 1099511628211ull; + }; + add(revision, sizeof(revision) - 1); + add(&vertex_id, sizeof(vertex_id)); + add(&pixel_id, sizeof(pixel_id)); + add(root_blob->GetBufferPointer(), root_blob->GetBufferSize()); + char stem[32]; + std::snprintf(stem, sizeof(stem), "%016llx", static_cast(key)); + char directory[MAX_PATH]; + const DWORD size = GetEnvironmentVariableA("X2W_SHADER_CACHE", directory, MAX_PATH); + check(size && size < MAX_PATH ? S_OK : E_FAIL, "find fixture cache"); + const std::string prefix = std::string(directory) + "\\" + stem; + const auto write = [&](const char* suffix, const void* bytes, std::size_t count) { + std::ofstream file(prefix + suffix, std::ios::binary | std::ios::trunc); + file.write(static_cast(bytes), count); + check(file.good() ? S_OK : E_FAIL, "write fixture cache"); + }; + const auto vs = compile(needs_start ? "translated_vertex_with_start" : "translated_vertex", "vs_5_1"); + const auto ps = compile("translated_pixel", "ps_5_1"); + write(".vs.cso", vs->GetBufferPointer(), vs->GetBufferSize()); + write(".ps.cso", ps->GetBufferPointer(), ps->GetBufferSize()); + constexpr char manifest[] = "x2w-manifest 1\nud 2\nudsrc 0 rect\nudsrc 1 basevertex\nsrv 0 tex2d table 0 0\nparams 0\ntargets 0\n"; + write(".txt", manifest, sizeof(manifest) - 1); + const std::array desc{ + reinterpret_cast(root), 0, 0, 0, 0, + reinterpret_cast(&vertex_id), sizeof(vertex_id), 0, 0, + reinterpret_cast(&pixel_id), sizeof(pixel_id), 0}; + using Create = HRESULT (WINAPI*)(IUnknown*, const void*, REFIID, void**); + ComPtr result; + check(slot(guest, 57)(guest, desc.data(), __uuidof(ID3D12PipelineState), + reinterpret_cast(result.GetAddressOf())), "create translated guest pipeline"); + return result; +} + ComPtr writer_pipeline(ID3D12Device* device, ID3D12RootSignature* root, const char* entry) { const auto cs = compile(entry, "cs_5_0"); @@ -237,9 +299,52 @@ void submit(ID3D12Device* device, ID3D12GraphicsCommandList* list) check(device->GetDeviceRemovedReason(), "GPU completion"); } -enum class Refusal { none, invalid_index, short_argument, missing_viewport }; +enum class Refusal { none, invalid_index, short_argument, missing_viewport, wrong_root, missing_texture, start_vertex }; enum class DrawKind { indexed, vertices, mesh }; +struct TranslatedDrawFixture { + TranslatedDrawFixture(ID3D12Device* guest, std::uint32_t colour) + : wrong_root(create_root(guest, {0, nullptr, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_NONE})), + backing(VirtualAlloc(nullptr, 65536, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)) + { + if (!backing) throw std::bad_alloc(); + std::memcpy(backing.get(), &colour, sizeof(colour)); + const D3D12_RESOURCE_DESC desc{D3D12_RESOURCE_DIMENSION_TEXTURE2D, 0, 1, 1, 1, 1, format, {1, 0}, + D3D12_TEXTURE_LAYOUT_UNKNOWN, D3D12_RESOURCE_FLAG_NONE}; + using Place = HRESULT (WINAPI*)(IUnknown*, void*, const D3D12_RESOURCE_DESC*, UINT, const void*, REFIID, void**); + check(slot(guest, 133)(guest, backing.get(), &desc, D3D12_RESOURCE_STATE_COMMON, nullptr, + __uuidof(ID3D12Resource), reinterpret_cast(texture.GetAddressOf())), "place sampled texture"); + const struct { + D3D12_DESCRIPTOR_HEAP_DESC desc; + UINT64 backing, bytes; + } heap_desc{{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 1, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE}, 0, 0}; + using CreateHeap = HRESULT (WINAPI*)(IUnknown*, const void*, REFIID, void**); + check(slot(guest, 14)(guest, &heap_desc, __uuidof(ID3D12DescriptorHeap), + reinterpret_cast(heap.GetAddressOf())), "create sampled texture heap"); + struct { + D3D12_SHADER_RESOURCE_VIEW_DESC view{}; + UINT64 address = 0, tail[2]{}; + } storage; + auto& srv = storage.view; + srv.Format = format; + srv.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; + srv.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + srv.Texture2D.MipLevels = 1; + using Handle = UINT64 (WINAPI*)(IUnknown*, void*); + const UINT64 cpu = slot(heap.Get(), 9)(heap.Get(), nullptr); + gpu = slot(heap.Get(), 10)(heap.Get(), nullptr); + check(cpu && gpu ? S_OK : E_FAIL, "get guest texture handles"); + using View = void (WINAPI*)(IUnknown*, ID3D12Resource*, const D3D12_SHADER_RESOURCE_VIEW_DESC*, UINT64, UINT64); + slot(guest, 18)(guest, texture.Get(), &srv, cpu, 0); + } + + ComPtr wrong_root; + std::unique_ptr backing; + ComPtr texture; + ComPtr heap; + UINT64 gpu = 0; +}; + constexpr UINT command_stride(DrawKind kind) { switch (kind) { @@ -259,7 +364,7 @@ bool supports_mesh(ID3D12Device* device) bool run(ID3D12Device* device, ID3D12Device* guest, ID3D12RootSignature* writer_root, ID3D12PipelineState* writer, ID3D12RootSignature* graphics_root, IUnknown* graphics, ID3D12CommandSignature* signature, - DrawKind kind, bool draw_right, Refusal refusal, const char* label) + DrawKind kind, bool draw_right, Refusal refusal, const char* label, const TranslatedDrawFixture* translated = nullptr) { const bool indexed = kind == DrawKind::indexed; const bool mesh = kind == DrawKind::mesh; @@ -335,7 +440,14 @@ bool run(ID3D12Device* device, ID3D12Device* guest, ID3D12RootSignature* writer_ slot(wrapped, 52)(wrapped, rtv.ptr, clear, 0, nullptr); slot(wrapped, 50)(wrapped, 1, &rtv, FALSE, nullptr); slot(wrapped, 25)(wrapped, graphics); - slot(wrapped, 34)(wrapped, graphics_root); + slot(wrapped, 34)(wrapped, refusal == Refusal::wrong_root ? translated->wrong_root.Get() : graphics_root); + if (translated && refusal != Refusal::missing_texture) { + ID3D12DescriptorHeap* heaps[]{translated->heap.Get()}; + using Heaps = void (WINAPI*)(IUnknown*, UINT, ID3D12DescriptorHeap* const*); + using Table = void (WINAPI*)(IUnknown*, UINT, UINT64); + slot(wrapped, 32)(wrapped, 1, heaps); + slot(wrapped, 36)(wrapped, 0, translated->gpu); + } if (!mesh) slot(wrapped, 20)(wrapped, D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); if (refusal != Refusal::missing_viewport) slot(wrapped, 21)(wrapped, 1, &viewport); slot(wrapped, 22)(wrapped, 1, &scissor); @@ -352,6 +464,14 @@ bool run(ID3D12Device* device, ID3D12Device* guest, ID3D12RootSignature* writer_ check(slot(wrapped, 9)(wrapped), "close guest command list"); submit(device, list); + if (translated) { + constexpr Words empty{}; + if (std::memcmp(arguments.address, empty.data(), sizeof(empty))) { + std::fprintf(stderr, "%s: CPU argument backing changed\n", label); + return false; + } + } + const D3D12_RANGE arg_range{0, sizeof(initial)}; check(arg_readback->Map(0, &arg_range, &memory), "map argument readback"); Words observed{}; @@ -359,7 +479,7 @@ bool run(ID3D12Device* device, ID3D12Device* guest, ID3D12RootSignature* writer_ arg_readback->Unmap(0, &untouched); Words expected = initial_words; if (writer) { - expected[1] = !indexed && draw_right ? 6 : 3; + expected[1] = !translated && !indexed && draw_right ? 6 : 3; expected[2] = 1; if (indexed) expected[3] = draw_right ? 4 : 1; if (mesh) { @@ -395,9 +515,9 @@ bool run(ID3D12Device* device, ID3D12Device* guest, ID3D12RootSignature* writer_ std::memcpy(&actual, static_cast(memory) + y * footprint.Footprint.RowPitch + x * sizeof(actual), sizeof(actual)); const bool right_half = x >= width / 2; - const bool covered = indexed ? right_half == draw_right : !right_half || draw_right; + const bool covered = translated || (indexed ? right_half == draw_right : !right_half || draw_right); const bool drawn = writer && refusal == Refusal::none && covered; - const auto wanted = drawn ? (right_half ? green : red) : black; + const auto wanted = drawn ? (translated ? (draw_right ? green : red) : (right_half ? green : red)) : black; if (actual != black) ++painted; if (actual == wanted) continue; std::fprintf(stderr, "%s: pixel (%u,%u): got 0x%08x, expected 0x%08x\n", label, x, y, actual, wanted); @@ -451,9 +571,10 @@ std::string indirect_line(ID3D12Device* guest, const std::wstring& log_path) int main(int argc, char** argv) try { DrawKind kind = DrawKind::indexed; + const bool translated = argc == 3 && std::strcmp(argv[2], "translated") == 0; // "count-control" is the negative control: it expects one forwarded call too many. const bool count_control = argc == 3 && std::strcmp(argv[2], "count-control") == 0; - if (argc == 3 && std::strcmp(argv[2], "draw") == 0) kind = DrawKind::vertices; + if (translated || (argc == 3 && std::strcmp(argv[2], "draw") == 0)) kind = DrawKind::vertices; else if (argc == 3 && std::strcmp(argv[2], "mesh") == 0) kind = DrawKind::mesh; else if (argc != 2 && !count_control) return 2; const bool indexed = kind == DrawKind::indexed; @@ -520,6 +641,42 @@ int main(int argc, char** argv) try const auto root_flags = mesh ? D3D12_ROOT_SIGNATURE_FLAG_NONE : D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT; const D3D12_ROOT_SIGNATURE_DESC graphics_desc{0, nullptr, 0, nullptr, root_flags}; const auto writer = create_root(device.Get(), writer_desc); + if (translated) { + const auto cache = std::filesystem::current_path() / ("indirect-translated-" + std::to_string(GetCurrentProcessId())); + std::filesystem::create_directory(cache); + check(SetEnvironmentVariableW(L"X2W_SHADER_CACHE", cache.c_str()) ? S_OK : E_FAIL, "set fixture cache"); + check(SetEnvironmentVariableA("X2W_TRANSLATED_INDIRECT_DRAW", "1") ? S_OK : E_FAIL, "enable fixture path"); + const D3D12_DESCRIPTOR_RANGE range{D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 1, 0, 0, 0}; + D3D12_ROOT_PARAMETER table{}; + table.ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; + table.DescriptorTable = {1, &range}; + const D3D12_ROOT_SIGNATURE_DESC title_desc{1, &table, 0, nullptr, root_flags}; + ComPtr root_blob; + const auto title_root = create_root(guest.Get(), title_desc, &root_blob); + const auto pso = translated_pipeline(guest.Get(), title_root.Get(), root_blob.Get(), false); + const auto start_pso = translated_pipeline(guest.Get(), title_root.Get(), root_blob.Get(), true); + const auto producer = writer_pipeline(device.Get(), writer.Get(), "write_one_triangle"); + D3D12_INDIRECT_ARGUMENT_DESC argument{}; + argument.Type = D3D12_INDIRECT_ARGUMENT_TYPE_DRAW; + const D3D12_COMMAND_SIGNATURE_DESC signature_desc{sizeof(D3D12_DRAW_ARGUMENTS), 1, &argument, 0}; + ComPtr signature; + check(guest->CreateCommandSignature(&signature_desc, nullptr, IID_PPV_ARGS(&signature)), "create translated draw signature"); + const TranslatedDrawFixture red_binding(guest.Get(), red), green_binding(guest.Get(), green); + const auto verify = [&](ID3D12PipelineState* gpu_writer, bool use_green, Refusal control, const char* label) { + return run(device.Get(), guest.Get(), writer.Get(), gpu_writer, title_root.Get(), + control == Refusal::start_vertex ? start_pso.Get() : pso.Get(), signature.Get(), + DrawKind::vertices, use_green, control, label, use_green ? &green_binding : &red_binding); + }; + const bool ok = verify(producer.Get(), false, Refusal::none, "translated red texture") && + verify(producer.Get(), true, Refusal::none, "translated green texture") && + verify(nullptr, false, Refusal::none, "translated omitted GPU writer") && + verify(producer.Get(), false, Refusal::wrong_root, "translated wrong guest root") && + verify(producer.Get(), false, Refusal::short_argument, "translated short argument range") && + verify(producer.Get(), false, Refusal::missing_texture, "translated missing texture") && + verify(producer.Get(), false, Refusal::start_vertex, "translated uses start vertex"); + if (ok) std::filesystem::remove_all(cache); + return ok && (!info || !info->GetNumStoredMessages()) ? 0 : 1; + } const auto graphics = create_root(guest.Get(), graphics_desc); const char* left_entry = indexed ? "write_left" : "write_one_triangle"; const char* right_entry = indexed ? "write_right" : "write_two_triangles"; From 741e2ef7f05cb3ef475806719683f0fed672963b Mon Sep 17 00:00:00 2001 From: Royoo <3230853833@qq.com> Date: Wed, 25 Nov 2026 14:52:43 +0800 Subject: [PATCH 8/9] startup: bind GPU-backed table buffers for indirect draws --- docs/experiments.md | 18 ++- src/startup_stubs/d3d12_draw.inl | 116 +++++++++++++++++++- src/startup_stubs/d3d12_xs_device.cpp | 9 +- src/startup_stubs/list_upload_pages.h | 12 +- tests/startup_indirect_draw_indexed.cpp | 139 ++++++++++++++++++++---- 5 files changed, 255 insertions(+), 39 deletions(-) diff --git a/docs/experiments.md b/docs/experiments.md index 1c80f5ca16..16c08f6eda 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -8,9 +8,16 @@ target, an explicit viewport and scissor, and the root signature used to create The translated path binds its usual pipeline, root and sampled textures, then forwards the placed desktop argument buffer and offset. Its producer supplies legal D3D12 draw arguments. The shim checks the placed buffer range without reading the draw fields or limiting the GPU-generated vertex count. -The path refuses vertex streams, buffer SRVs, dynamic sampler heaps, unknown texture bindings and -shaders whose reflected constants depend on the draw's start vertex or instance. It also refuses -non-reflectable shader bytecode. A missing cached translation retains the request publishing path. +The path refuses vertex streams, root buffer SRVs, dynamic sampler heaps, unknown bindings and shaders +whose reflected constants depend on the draw's start vertex or instance. It also refuses non-reflectable +shader bytecode. A deferred guest root can still supply the recorded tables to the translated root. +A missing cached translation retains the request publishing path. + +Table buffer views bind their complete byte range from the recording's upload allocation, one unique +aliased placed buffer, or a wrapped committed resource with desktop backing and no title shadow. +The runtime refuses non-DWORD ranges, misaligned offsets, cross-device views, views that overlap the +indirect argument resource, and copied placed buffers whose desktop contents are unproven. It binds +the accepted resource directly as a desktop raw SRV and uses its recorded stride for the shader entry. Run `cmake --build --preset release --target startup_indirect_draw_indexed` and `ctest --preset release -j1 --no-tests=error -R '^startup_indirect_translated_draw_' -V`. @@ -19,7 +26,10 @@ A compute writer records one triangle at a nonzero offset in a placed GPU buffer title backing. A fenced readback compares the argument, guard words and every colour pixel. Changing the sampled texture from red to green changes every pixel. Omitting the writer or texture, binding the wrong root, using a short argument range or using a shader that reads the start vertex -leaves the target clear. +leaves the target clear. A second compute writer supplies distinguishing colours to a table buffer. +The table's nonzero offset and stride select the second colour, the short view reads zero, and a +non-aliased placement is refused. A raw descriptor over a recording-owned upload page reads the +same colour and refuses a view that crosses its allocation. ### Packed pixel position in a source-built shader diff --git a/src/startup_stubs/d3d12_draw.inl b/src/startup_stubs/d3d12_draw.inl index e1450eca83..d13ed15a73 100644 --- a/src/startup_stubs/d3d12_draw.inl +++ b/src/startup_stubs/d3d12_draw.inl @@ -1358,8 +1358,10 @@ bool indirect_shader_entry(ID3DBlob* blob, const Translation& translation) std::snprintf(name, sizeof(name), "ud%u", static_cast(word)); if (var.StartOffset % sizeof(UINT) || var.Size != sizeof(UINT) || word >= translation.uds.size() || !var.Name || std::strcmp(var.Name, name)) return false; - const int kind = translation.uds[word].kind; - if (kind != Translation::root_constant && kind != Translation::rect && kind != Translation::d16_unorm16) + const auto& ud = translation.uds[word]; + if (ud.kind == Translation::stride && ud.a >= 0 && static_cast(ud.a) < translation.srvs.size() && + translation.srvs[ud.a].source == 0 && translation.srvs[ud.a].kind == 0) continue; + if (ud.kind != Translation::root_constant && ud.kind != Translation::rect && ud.kind != Translation::d16_unorm16) return false; } } @@ -1374,6 +1376,92 @@ struct TranslatedIndirectDraw { const char* refusal = "translated pipeline or target unavailable"; }; +struct IndirectBufferView { + ID3D12Resource* resource = nullptr; + u64 offset = 0, bytes = 0; + UINT stride = 0; + bool upload = false; +}; + +// For indirect draws, bind the complete descriptor range on a known GPU backing. There is no +// fallback to copying an unrelated or stale title allocation into the draw upload ring. +IndirectBufferView indirect_table_buffer(Wrapper* self, const std::uint32_t* words) +{ + constexpr u64 limit = 16u << 20; + u64 address = 0, offset = 0, bytes = 0; + UINT stride = 0; + const Wrapper* owner = nullptr; + if (words[0] == view_token_magic) { + ViewRecord record{}; + AcquireSRWLockShared(¬e_lock); + if (words[1] < view_records().size()) record = view_records()[words[1]]; + ReleaseSRWLockShared(¬e_lock); + if (record.slot == 17 && record.desc_bytes >= 12) { + UINT size = 0; + std::memcpy(&address, record.desc, 8); + std::memcpy(&size, record.desc + 8, 4); + bytes = size; + } else if (record.slot == 18 && record.desc_bytes >= 40) { + D3D12_SHADER_RESOURCE_VIEW_DESC view{}; + std::memcpy(&view, record.desc, 40); + owner = as_wrapper(reinterpret_cast(record.resource)); + if (!owner || owner->own().kind != resource_kind || !owner->own().real || + view.ViewDimension != D3D12_SRV_DIMENSION_BUFFER) return {}; + const bool raw = view.Buffer.Flags == D3D12_BUFFER_SRV_FLAG_RAW && !view.Buffer.StructureByteStride && + view.Format == DXGI_FORMAT_R32_TYPELESS; + const bool structured = view.Buffer.Flags == D3D12_BUFFER_SRV_FLAG_NONE && view.Buffer.StructureByteStride && + view.Format == DXGI_FORMAT_UNKNOWN; + const bool typed = view.Buffer.Flags == D3D12_BUFFER_SRV_FLAG_NONE && !view.Buffer.StructureByteStride; + const UINT element = raw ? 4 : structured ? view.Buffer.StructureByteStride : + typed ? x2w_startup::typed_buffer_format_bytes(view.Format) : 0; + if (!element || view.Buffer.FirstElement > UINT64_MAX / element) return {}; + offset = view.Buffer.FirstElement * element; + bytes = u64{view.Buffer.NumElements} * element; + stride = raw ? 0 : element; + if (const auto base = reinterpret_cast(owner->own().title_memory)) { + if (offset > UINT64_MAX - base) return {}; + address = base + offset; + } + } + } else { + address = words[0] | (u64{words[1] & 0xffff} << 32); + stride = (words[1] >> 16) & 0x3fff; + bytes = u64{stride ? stride : 1} * words[2]; + } + if (!bytes || bytes > limit || bytes % 4) return {}; + ID3D12Resource* native = nullptr; + bool upload = false; + Wrapper* device = self->own().list_device; + if (address) { + if (const auto allocation = list_upload_range(self, address, bytes); allocation.resource) { + if (!owner) return {allocation.resource, allocation.offset, bytes, stride, true}; + return {}; + } + const auto placed = placed_buffer_range(device, address, bytes); + if (placed.reject || !placed.alias || (owner && owner != placed.owner)) return {}; + owner = placed.owner; + native = placed.alias; + offset = address - reinterpret_cast(owner->own().title_memory); + } else if (owner && !owner->own().title_memory) { + native = static_cast(owner->own().real); + D3D12_HEAP_PROPERTIES props{}; + D3D12_HEAP_FLAGS flags{}; + if (FAILED(native->GetHeapProperties(&props, &flags)) || + (props.Type != D3D12_HEAP_TYPE_DEFAULT && props.Type != D3D12_HEAP_TYPE_UPLOAD)) return {}; + upload = props.Type == D3D12_HEAP_TYPE_UPLOAD; + } + if (!native || offset % D3D12_RAW_UAV_SRV_BYTE_ALIGNMENT || + !InterlockedCompareExchange(&owner->own().refs, 0, 0)) return {}; + const auto* info = resource_info(owner); + if (!info || info->initial_state != D3D12_RESOURCE_STATE_COMMON) return {}; + x2w_startup::ComPtr native_device; + if (FAILED(native->GetDevice(IID_PPV_ARGS(native_device.GetAddressOf()))) || native_device.Get() != device_of(device)) return {}; + const auto desc = native->GetDesc(); + if (desc.Dimension != D3D12_RESOURCE_DIMENSION_BUFFER || (desc.Flags & D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE) || + offset > desc.Width || bytes > desc.Width - offset) return {}; + return {native, offset, bytes, stride, upload}; +} + bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UINT start, INT base_vertex, UINT start_instance, TranslatedIndirectDraw* indirect) { @@ -1399,7 +1487,7 @@ bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UI if (!tr->independent_indirect_entry.has_value()) { tr->independent_indirect_entry = indirect_shader_entry(tr->vs, *tr) && indirect_shader_entry(tr->ps, *tr) && std::all_of(tr->srvs.begin(), tr->srvs.end(), [](const Translation::Srv& srv) { - return srv.kind > 0 && srv.source == 0; + return srv.source == 0; }); } if (!*tr->independent_indirect_entry || tr->samplers.heap) { @@ -1556,6 +1644,19 @@ bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UI device_of(the_device)->CreateShaderResourceView(texture, texture && record.desc_bytes < 40 ? nullptr : &desc, dest); continue; } + if (indirect) { + const auto view = entry_ok ? indirect_table_buffer(self, words) : IndirectBufferView{}; + if (!view.resource || view.resource == indirect->argument || view.offset % D3D12_RAW_UAV_SRV_BYTE_ALIGNMENT) { + indirect->refusal = "translated draw requires a complete GPU-backed table buffer range"; + ReleaseSRWLockExclusive(&draw_lock); + return false; + } + if (!view.upload) + require_state(self, view.resource, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE | D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE); + strides[i] = view.stride; + buffer_view(dest, view.resource, view.offset, static_cast(view.bytes)); + continue; + } if (srv.source == 0 && words[0] == view_token_magic && entry) { // A view the title created: a constant buffer view names its memory directly; a buffer // shader-resource view names a range of its resource's title memory. @@ -1697,7 +1798,7 @@ bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UI require_state(self, indirect->argument, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT); list->ExecuteIndirect(indirect->signature, 1, indirect->argument, indirect->offset, nullptr, 0); // The translated root invalidated the desktop arguments of the tracked guest root. - list->SetGraphicsRootSignature(pass.graphics_root); + if (pass.graphics_root) list->SetGraphicsRootSignature(pass.graphics_root); pass.srv_bound = 0; drawn = true; } else if (indexed) { @@ -1739,7 +1840,12 @@ bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UI const char* draw_translated_indirect(Wrapper* self, ID3D12CommandSignature* signature, ID3D12Resource* argument, u64 offset) { TranslatedIndirectDraw draw{signature, argument, offset}; - if (!draw_translated(self, false, 0, 0, 0, 0, 0, &draw)) return draw.refusal; + if (!draw_translated(self, false, 0, 0, 0, 0, 0, &draw)) { + static LONG refused; + if (draw.shader_key && first_calls(refused, 32)) + log("x2w-render translated ExecuteIndirect Draw refused, shader %016llx: %s", draw.shader_key, draw.refusal); + return draw.refusal; + } InterlockedIncrement(&translated_draws); static LONG reported; if (first_calls(reported, 16)) diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index 984aa9285a..4c5610046a 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -1225,14 +1225,15 @@ void* __stdcall list_allocate_upload(Wrapper* self, UINT64 bytes, UINT64 alignme return reinterpret_cast(allocation.cpu); } -UINT64 list_upload_gpu(Wrapper* self, UINT64 address, UINT64 bytes) +x2w_upload::Allocation list_upload_range(Wrapper* self, UINT64 address, UINT64 bytes) { AcquireSRWLockShared(&allocator_lock); const auto& state = self->own(); - const auto gpu = state.list_open && state.list_uploads ? state.list_uploads->translate(address, bytes) : 0; + const auto allocation = state.list_open && state.list_uploads ? state.list_uploads->range(address, bytes) : x2w_upload::Allocation{}; ReleaseSRWLockShared(&allocator_lock); - return gpu; + return allocation; } +UINT64 list_upload_gpu(Wrapper* self, UINT64 address, UINT64 bytes) { return list_upload_range(self, address, bytes).gpu; } // Fixture lookup. The full range must belong to this list's open recording. extern "C" __declspec(dllexport) UINT64 x2w_d3d12_upload_gpu_address(void* list, const void* cpu, UINT64 bytes) @@ -2236,7 +2237,7 @@ void __stdcall list_execute_indirect(Wrapper* self, void* signature, UINT count, const bool graphics = indexed || mesh || command == IndirectCommand::draw; Pass& pass = pass_of(self); const bool translated = command == IndirectCommand::draw && pass.pipeline && !pass.pipeline->own().real && - pass.graphics_root && x2w_local::env_on("X2W_TRANSLATED_INDIRECT_DRAW"); + (pass.graphics_root || pass.deferred_root) && x2w_local::env_on("X2W_TRANSLATED_INDIRECT_DRAW"); u64 bytes = sig->own().indirect_bytes; if (graphics && (count != 1 || count_buffer)) return refuse("indirect graphics requires one command and no count buffer"); if (graphics) { diff --git a/src/startup_stubs/list_upload_pages.h b/src/startup_stubs/list_upload_pages.h index cf8053477f..ef7ee38656 100644 --- a/src/startup_stubs/list_upload_pages.h +++ b/src/startup_stubs/list_upload_pages.h @@ -42,14 +42,18 @@ struct Arena { // The caller must retire all recordings and GPU submissions before releasing their pages. void reset() { allocations.clear(); pages.clear(); } - UINT64 translate(UINT64 cpu, UINT64 bytes) const { - if (!bytes) return 0; + Allocation range(UINT64 cpu, UINT64 bytes) const { + if (!bytes) return {}; for (auto it = allocations.rbegin(); it != allocations.rend(); ++it) { if (cpu < it->cpu) continue; UINT64 offset = cpu - it->cpu; - if (offset < it->bytes && bytes <= it->bytes - offset) return it->gpu + offset; + if (offset < it->bytes && bytes <= it->bytes - offset) + return {static_cast(cpu), it->gpu + offset, bytes, it->resource, it->offset + offset}; } - return 0; + return {}; + } + UINT64 translate(UINT64 cpu, UINT64 bytes) const { + return range(cpu, bytes).gpu; } Allocation allocate(ID3D12Device* device, UINT64 bytes, UINT64 alignment) { if (!device || !bytes || !alignment || (alignment & (alignment - 1))) return {}; diff --git a/tests/startup_indirect_draw_indexed.cpp b/tests/startup_indirect_draw_indexed.cpp index 4ac78b52b0..6671290416 100644 --- a/tests/startup_indirect_draw_indexed.cpp +++ b/tests/startup_indirect_draw_indexed.cpp @@ -57,6 +57,12 @@ void write_two_triangles() { data.Store4(4, uint4(6, 1, 0, 0)); } +[numthreads(1, 1, 1)] +void write_buffer_colour() { + data.Store(16, 0xff00ff00u); + data.Store(32, 0xff0000ffu); +} + [numthreads(1, 1, 1)] void write_one_mesh_group() { data.Store3(4, uint3(1, 1, 1)); @@ -86,8 +92,9 @@ float4 pixel(Varying input) : SV_Target { discard; return float4(0, 0, 0, 1); } -cbuffer entry : register(b0) { uint ud0; uint ud1; }; +cbuffer entry : register(b0) { uint ud0; uint ud1; uint ud2; }; Texture2D translated_texture : register(t0); +ByteAddressBuffer translated_buffer : register(t0); float4 translated_vertex(uint id : SV_VertexID) : SV_Position { return float4(id == 2 ? 3 : -1, id == 1 ? 3 : -1, 0, 1); @@ -101,6 +108,11 @@ float4 translated_pixel() : SV_Target { return translated_texture.Load(int3(0, 0, 0)); } +float4 translated_buffer_pixel() : SV_Target { + uint value = translated_buffer.Load(ud2); + return float4(value & 255, (value >> 8) & 255, (value >> 16) & 255, 255) / 255.0; +} + )"; template @@ -147,13 +159,15 @@ ComPtr create_root(ID3D12Device* device, const D3D12_ROOT_S return root; } -ComPtr translated_pipeline(ID3D12Device* guest, ID3D12RootSignature* root, ID3DBlob* root_blob, bool needs_start) +ComPtr translated_pipeline(ID3D12Device* guest, ID3D12RootSignature* root, ID3DBlob* root_blob, + bool needs_start, bool table_buffer = false) { // The opaque guest programs identify synthetic cache entries. The actual bound shaders are source-built DXBC. constexpr char revision[] = "x2w-startup-shader-8"; static std::uint32_t vertex_ids[]{0xe0000101, 0xe0000102}; - static std::uint32_t pixel_id = 0xe0000202; + static std::uint32_t pixel_ids[]{0xe0000202, 0xe0000203}; auto& vertex_id = vertex_ids[needs_start]; + auto& pixel_id = pixel_ids[table_buffer]; std::uint64_t key = 1469598103934665603ull; const auto add = [&key](const void* data, std::size_t bytes) { const auto* p = static_cast(data); @@ -175,11 +189,13 @@ ComPtr translated_pipeline(ID3D12Device* guest, ID3D12RootSignature* r check(file.good() ? S_OK : E_FAIL, "write fixture cache"); }; const auto vs = compile(needs_start ? "translated_vertex_with_start" : "translated_vertex", "vs_5_1"); - const auto ps = compile("translated_pixel", "ps_5_1"); + const auto ps = compile(table_buffer ? "translated_buffer_pixel" : "translated_pixel", "ps_5_1"); write(".vs.cso", vs->GetBufferPointer(), vs->GetBufferSize()); write(".ps.cso", ps->GetBufferPointer(), ps->GetBufferSize()); constexpr char manifest[] = "x2w-manifest 1\nud 2\nudsrc 0 rect\nudsrc 1 basevertex\nsrv 0 tex2d table 0 0\nparams 0\ntargets 0\n"; - write(".txt", manifest, sizeof(manifest) - 1); + constexpr char buffer_manifest[] = "x2w-manifest 1\nud 3\nudsrc 0 rect\nudsrc 1 basevertex\nudsrc 2 stride 0\nsrv 0 buf table 0 0\nparams 0\ntargets 0\n"; + if (table_buffer) write(".txt", buffer_manifest, sizeof(buffer_manifest) - 1); + else write(".txt", manifest, sizeof(manifest) - 1); const std::array desc{ reinterpret_cast(root), 0, 0, 0, 0, reinterpret_cast(&vertex_id), sizeof(vertex_id), 0, 0, @@ -299,21 +315,38 @@ void submit(ID3D12Device* device, ID3D12GraphicsCommandList* list) check(device->GetDeviceRemovedReason(), "GPU completion"); } -enum class Refusal { none, invalid_index, short_argument, missing_viewport, wrong_root, missing_texture, start_vertex }; +enum class Refusal { none, invalid_index, short_argument, missing_viewport, wrong_root, missing_texture, start_vertex, + insufficient_table_range, copied_table_buffer, upload_range_crossing }; enum class DrawKind { indexed, vertices, mesh }; struct TranslatedDrawFixture { - TranslatedDrawFixture(ID3D12Device* guest, std::uint32_t colour) + TranslatedDrawFixture(ID3D12Device* guest, std::uint32_t colour, ID3D12Device* desktop = nullptr, + bool short_view = false, bool copied = false) : wrong_root(create_root(guest, {0, nullptr, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_NONE})), backing(VirtualAlloc(nullptr, 65536, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)) { if (!backing) throw std::bad_alloc(); - std::memcpy(backing.get(), &colour, sizeof(colour)); - const D3D12_RESOURCE_DESC desc{D3D12_RESOURCE_DIMENSION_TEXTURE2D, 0, 1, 1, 1, 1, format, {1, 0}, - D3D12_TEXTURE_LAYOUT_UNKNOWN, D3D12_RESOURCE_FLAG_NONE}; - using Place = HRESULT (WINAPI*)(IUnknown*, void*, const D3D12_RESOURCE_DESC*, UINT, const void*, REFIID, void**); - check(slot(guest, 133)(guest, backing.get(), &desc, D3D12_RESOURCE_STATE_COMMON, nullptr, - __uuidof(ID3D12Resource), reinterpret_cast(texture.GetAddressOf())), "place sampled texture"); + if (desktop && !copied) { + const D3D12_HEAP_PROPERTIES props{D3D12_HEAP_TYPE_DEFAULT}; + const D3D12_RESOURCE_DESC desc{D3D12_RESOURCE_DIMENSION_BUFFER, 0, 64, 1, 1, 1, DXGI_FORMAT_UNKNOWN, {1, 0}, + D3D12_TEXTURE_LAYOUT_ROW_MAJOR, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS}; + using Create = HRESULT (WINAPI*)(IUnknown*, const D3D12_HEAP_PROPERTIES*, UINT, const D3D12_RESOURCE_DESC*, + UINT, const void*, void*, UINT, const void*, REFIID, void**); + check(slot(guest, 127)(guest, &props, 0, &desc, D3D12_RESOURCE_STATE_COMMON, nullptr, nullptr, + 0, nullptr, __uuidof(ID3D12Resource), reinterpret_cast(sampled.GetAddressOf())), "create GPU table buffer"); + } else { + const D3D12_RESOURCE_DESC desc = copied ? + D3D12_RESOURCE_DESC{D3D12_RESOURCE_DIMENSION_BUFFER, 0, 64, 1, 1, 1, DXGI_FORMAT_UNKNOWN, {1, 0}, + D3D12_TEXTURE_LAYOUT_ROW_MAJOR, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS} : + D3D12_RESOURCE_DESC{D3D12_RESOURCE_DIMENSION_TEXTURE2D, 0, 1, 1, 1, 1, format, {1, 0}, + D3D12_TEXTURE_LAYOUT_UNKNOWN, D3D12_RESOURCE_FLAG_NONE}; + auto* address = static_cast(backing.get()) + (copied ? 16 : 0); + std::memcpy(address + (copied ? 32 : 0), &colour, sizeof(colour)); + using Place = HRESULT (WINAPI*)(IUnknown*, void*, const D3D12_RESOURCE_DESC*, UINT, const void*, REFIID, void**); + check(slot(guest, 133)(guest, address, &desc, D3D12_RESOURCE_STATE_COMMON, nullptr, + __uuidof(ID3D12Resource), reinterpret_cast(sampled.GetAddressOf())), "place sampled resource"); + } + if (desktop) gpu_buffer = native_object(desktop, guest, sampled.Get()); const struct { D3D12_DESCRIPTOR_HEAP_DESC desc; UINT64 backing, bytes; @@ -326,22 +359,33 @@ struct TranslatedDrawFixture { UINT64 address = 0, tail[2]{}; } storage; auto& srv = storage.view; - srv.Format = format; - srv.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; srv.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; - srv.Texture2D.MipLevels = 1; + if (desktop) { + srv.Format = DXGI_FORMAT_UNKNOWN; + srv.ViewDimension = D3D12_SRV_DIMENSION_BUFFER; + srv.Buffer.FirstElement = 1; + srv.Buffer.NumElements = short_view ? 1 : 2; + srv.Buffer.StructureByteStride = 16; + } else { + srv.Format = format; + srv.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; + srv.Texture2D.MipLevels = 1; + } using Handle = UINT64 (WINAPI*)(IUnknown*, void*); - const UINT64 cpu = slot(heap.Get(), 9)(heap.Get(), nullptr); + cpu = slot(heap.Get(), 9)(heap.Get(), nullptr); gpu = slot(heap.Get(), 10)(heap.Get(), nullptr); check(cpu && gpu ? S_OK : E_FAIL, "get guest texture handles"); using View = void (WINAPI*)(IUnknown*, ID3D12Resource*, const D3D12_SHADER_RESOURCE_VIEW_DESC*, UINT64, UINT64); - slot(guest, 18)(guest, texture.Get(), &srv, cpu, 0); + slot(guest, 18)(guest, sampled.Get(), &srv, cpu, 0); } ComPtr wrong_root; std::unique_ptr backing; - ComPtr texture; + ComPtr sampled; + ComPtr gpu_buffer; + ComPtr buffer_writer; ComPtr heap; + UINT64 cpu = 0; UINT64 gpu = 0; }; @@ -364,7 +408,8 @@ bool supports_mesh(ID3D12Device* device) bool run(ID3D12Device* device, ID3D12Device* guest, ID3D12RootSignature* writer_root, ID3D12PipelineState* writer, ID3D12RootSignature* graphics_root, IUnknown* graphics, ID3D12CommandSignature* signature, - DrawKind kind, bool draw_right, Refusal refusal, const char* label, const TranslatedDrawFixture* translated = nullptr) + DrawKind kind, bool draw_right, Refusal refusal, const char* label, + const TranslatedDrawFixture* translated = nullptr, bool upload_table = false) { const bool indexed = kind == DrawKind::indexed; const bool mesh = kind == DrawKind::mesh; @@ -405,6 +450,18 @@ bool run(ID3D12Device* device, ID3D12Device* guest, ID3D12RootSignature* writer_ auto* wrapped = wrapped_list.Get(); const auto native_list = native_object(device, guest, wrapped); auto* list = native_list.Get(); + if (upload_table) { + using Allocate = void* (WINAPI*)(IUnknown*, UINT64, UINT64); + void* allocation = slot(wrapped, 148)(wrapped, 32, 16); + if (!allocation) return false; + const std::array words{green, 0, 0, 0, red, 0, 0, 0}; + std::memcpy(allocation, words.data(), sizeof(words)); + const UINT64 address = reinterpret_cast(allocation); + const std::array view{static_cast(address), + static_cast(address >> 32) | (16u << 16), + refusal == Refusal::upload_range_crossing ? 3u : 2u, 0}; + std::memcpy(reinterpret_cast(translated->cpu), view.data(), sizeof(view)); + } if (index_buffer) { transition(list, index_buffer->native.Get(), D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_DEST); list->CopyBufferRegion(index_buffer->native.Get(), 0, upload.Get(), sizeof(initial_words), index_bytes); @@ -425,6 +482,15 @@ bool run(ID3D12Device* device, ID3D12Device* guest, ID3D12RootSignature* writer_ list->CopyBufferRegion(arg_readback.Get(), 0, arguments.native.Get(), 0, sizeof(initial)); // The wrapper owns the subsequent COMMON -> INDIRECT_ARGUMENT transition. transition(list, arguments.native.Get(), D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_COMMON); + if (translated && translated->gpu_buffer && translated->buffer_writer) { + auto* table_resource = translated->gpu_buffer.Get(); + transition(list, table_resource, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + list->SetPipelineState(translated->buffer_writer.Get()); + list->SetComputeRootSignature(writer_root); + list->SetComputeRootUnorderedAccessView(0, table_resource->GetGPUVirtualAddress()); + list->Dispatch(1, 1, 1); + transition(list, table_resource, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COMMON); + } using Bind = void (WINAPI*)(IUnknown*, IUnknown*); using Clear = void (WINAPI*)(IUnknown*, SIZE_T, const float*, UINT, const D3D12_RECT*); @@ -655,25 +721,54 @@ int main(int argc, char** argv) try const auto title_root = create_root(guest.Get(), title_desc, &root_blob); const auto pso = translated_pipeline(guest.Get(), title_root.Get(), root_blob.Get(), false); const auto start_pso = translated_pipeline(guest.Get(), title_root.Get(), root_blob.Get(), true); + const auto buffer_pso = translated_pipeline(guest.Get(), title_root.Get(), root_blob.Get(), false, true); const auto producer = writer_pipeline(device.Get(), writer.Get(), "write_one_triangle"); + const auto buffer_writer = writer_pipeline(device.Get(), writer.Get(), "write_buffer_colour"); D3D12_INDIRECT_ARGUMENT_DESC argument{}; argument.Type = D3D12_INDIRECT_ARGUMENT_TYPE_DRAW; const D3D12_COMMAND_SIGNATURE_DESC signature_desc{sizeof(D3D12_DRAW_ARGUMENTS), 1, &argument, 0}; ComPtr signature; check(guest->CreateCommandSignature(&signature_desc, nullptr, IID_PPV_ARGS(&signature)), "create translated draw signature"); const TranslatedDrawFixture red_binding(guest.Get(), red), green_binding(guest.Get(), green); + TranslatedDrawFixture full_buffer(guest.Get(), 0, device.Get()), short_buffer(guest.Get(), 0, device.Get(), true), + copied_buffer(guest.Get(), green, device.Get(), false, true); + const TranslatedDrawFixture raw_upload(guest.Get(), 0); + full_buffer.buffer_writer = short_buffer.buffer_writer = copied_buffer.buffer_writer = buffer_writer; const auto verify = [&](ID3D12PipelineState* gpu_writer, bool use_green, Refusal control, const char* label) { return run(device.Get(), guest.Get(), writer.Get(), gpu_writer, title_root.Get(), control == Refusal::start_vertex ? start_pso.Get() : pso.Get(), signature.Get(), DrawKind::vertices, use_green, control, label, use_green ? &green_binding : &red_binding); }; - const bool ok = verify(producer.Get(), false, Refusal::none, "translated red texture") && + bool ok = verify(producer.Get(), false, Refusal::none, "translated red texture") && verify(producer.Get(), true, Refusal::none, "translated green texture") && verify(nullptr, false, Refusal::none, "translated omitted GPU writer") && verify(producer.Get(), false, Refusal::wrong_root, "translated wrong guest root") && verify(producer.Get(), false, Refusal::short_argument, "translated short argument range") && verify(producer.Get(), false, Refusal::missing_texture, "translated missing texture") && - verify(producer.Get(), false, Refusal::start_vertex, "translated uses start vertex"); + verify(producer.Get(), false, Refusal::start_vertex, "translated uses start vertex") && + run(device.Get(), guest.Get(), writer.Get(), producer.Get(), title_root.Get(), buffer_pso.Get(), signature.Get(), + DrawKind::vertices, false, Refusal::none, "translated GPU buffer range with nonzero offset and stride", &full_buffer) && + run(device.Get(), guest.Get(), writer.Get(), producer.Get(), title_root.Get(), buffer_pso.Get(), signature.Get(), + DrawKind::vertices, false, Refusal::insufficient_table_range, "translated table exposes only its own range", &short_buffer) && + run(device.Get(), guest.Get(), writer.Get(), producer.Get(), title_root.Get(), buffer_pso.Get(), signature.Get(), + DrawKind::vertices, false, Refusal::copied_table_buffer, "translated refuses copied GPU buffer and CPU shadow", &copied_buffer) && + run(device.Get(), guest.Get(), writer.Get(), producer.Get(), title_root.Get(), buffer_pso.Get(), signature.Get(), + DrawKind::vertices, false, Refusal::none, "translated raw table uses its recording upload page", &raw_upload, true) && + run(device.Get(), guest.Get(), writer.Get(), producer.Get(), title_root.Get(), buffer_pso.Get(), signature.Get(), + DrawKind::vertices, false, Refusal::upload_range_crossing, "translated raw table refuses crossing its upload allocation", &raw_upload, true); + auto deferred_desc = title_desc; + deferred_desc.Flags |= D3D12_ROOT_SIGNATURE_FLAG_CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED; + ComPtr deferred_blob; + ComPtr deferred_root; + if (SUCCEEDED(D3D12SerializeRootSignature(&deferred_desc, D3D_ROOT_SIGNATURE_VERSION_1, &deferred_blob, nullptr)) && + SUCCEEDED(guest->CreateRootSignature(0, deferred_blob->GetBufferPointer(), deferred_blob->GetBufferSize(), + IID_PPV_ARGS(&deferred_root)))) { + const auto deferred_pso = translated_pipeline(guest.Get(), deferred_root.Get(), deferred_blob.Get(), false, true); + if (ok) ok = run(device.Get(), guest.Get(), writer.Get(), producer.Get(), deferred_root.Get(), deferred_pso.Get(), signature.Get(), + DrawKind::vertices, false, Refusal::none, "translated table with deferred guest root", &full_buffer); + } else { + std::puts("deferred guest root capability unavailable"); + } if (ok) std::filesystem::remove_all(cache); return ok && (!info || !info->GetNumStoredMessages()) ? 0 : 1; } From 13b21704066faf51a335d1a3068efb639e6eb898 Mon Sep 17 00:00:00 2001 From: Royoo <3230853833@qq.com> Date: Wed, 25 Nov 2026 15:04:46 +0800 Subject: [PATCH 9/9] startup: carry verified copy ranges into indirect draws --- CMakeLists.txt | 4 + docs/experiments.md | 19 +++++ src/startup_stubs/d3d12_draw.inl | 5 +- src/startup_stubs/d3d12_xs_device.cpp | 34 +++++++++ src/startup_stubs/list_copy.inl | 34 ++++++++- tests/startup_indirect_draw_indexed.cpp | 98 +++++++++++++++++++++---- 6 files changed, 173 insertions(+), 21 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 56d369e264..2b9cd905a0 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1136,10 +1136,14 @@ foreach(backend IN ITEMS warp hardware) add_test(NAME startup_indirect_draw_indexed_${backend} COMMAND startup_indirect_draw_indexed ${backend}) add_test(NAME startup_indirect_draw_${backend} COMMAND startup_indirect_draw_indexed ${backend} draw) add_test(NAME startup_indirect_translated_draw_${backend} COMMAND startup_indirect_draw_indexed ${backend} translated) + add_test(NAME startup_indirect_copy_provenance_${backend} COMMAND startup_indirect_draw_indexed ${backend} copy-provenance) + add_test(NAME startup_indirect_copy_provenance_off_${backend} COMMAND startup_indirect_draw_indexed ${backend} copy-provenance-off) add_test(NAME startup_indirect_mesh_${backend} COMMAND startup_indirect_draw_indexed ${backend} mesh) set_tests_properties(startup_indirect_draw_indexed_${backend} startup_indirect_draw_${backend} PROPERTIES TIMEOUT 30) set_tests_properties(startup_indirect_mesh_${backend} PROPERTIES TIMEOUT 30 SKIP_RETURN_CODE 77) set_tests_properties(startup_indirect_translated_draw_${backend} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77) + set_tests_properties(startup_indirect_copy_provenance_${backend} startup_indirect_copy_provenance_off_${backend} + PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77) endforeach() set_tests_properties(startup_indirect_draw_indexed_hardware startup_indirect_draw_hardware PROPERTIES SKIP_RETURN_CODE 77) # Negative control for the x2w-render indirect line: one forwarded call too many must be reported as a mismatch. diff --git a/docs/experiments.md b/docs/experiments.md index 16c08f6eda..ae5720fb4a 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -31,6 +31,25 @@ The table's nonzero offset and stride select the second colour, the short view r non-aliased placement is refused. A raw descriptor over a recording-owned upload page reads the same colour and refuses a view that crosses its allocation. +### Same-recording GPU copies used by an indirect draw + +`X2W_TRANSLATED_INDIRECT_COPY_RANGES=1` enables a bounded handoff from slot 15 +`CopyBufferRegion` to the translated indirect draw. The latter still requires +`X2W_TRANSLATED_INDIRECT_DRAW=1`. A copied placed buffer qualifies only when one +validated GPU copy in the current recording completely supplied the requested view. +The source is a same-device desktop resource with no title shadow, a unique alias, +or an already covered range. Later overlapping copies invalidate earlier coverage. +The recording discards this proof at Close, so another recording needs its own writer. + +The source-built fixture reproduces a 68-byte request shape with source offset `0xbfffa0`. +Its compute writer fills the source with contrasting colours. The consumer reads red +from the second DWORD in the destination while the title-side green sentinel stays +unchanged. The disabled feature, a new recording using the same destination, a copy +of only 64 bytes, and an unproven overlapping write all leave the target clear. + +Run `cmake --build --preset release --target startup_indirect_draw_indexed` and +`ctest --preset release -j1 --no-tests=error -R '^startup_indirect_copy_provenance_' -V`. + ### Packed pixel position in a source-built shader Run `ctest --preset dev --no-tests=error -R '^startup_packed_screen_position_(hardware|warp)$' -V`. diff --git a/src/startup_stubs/d3d12_draw.inl b/src/startup_stubs/d3d12_draw.inl index 09fd877df3..2f5e38a70e 100644 --- a/src/startup_stubs/d3d12_draw.inl +++ b/src/startup_stubs/d3d12_draw.inl @@ -1446,10 +1446,11 @@ IndirectBufferView indirect_table_buffer(Wrapper* self, const std::uint32_t* wor return {}; } const auto placed = placed_buffer_range(device, address, bytes); - if (placed.reject || !placed.alias || (owner && owner != placed.owner)) return {}; + if (placed.reject || !placed.owner || (owner && owner != placed.owner)) return {}; owner = placed.owner; - native = placed.alias; + native = static_cast(owner->own().real); offset = address - reinterpret_cast(owner->own().title_memory); + if (!placed.alias && (!native || !list_copied_gpu_range(self, native, offset, bytes))) return {}; } else if (owner && !owner->own().title_memory) { native = static_cast(owner->own().real); D3D12_HEAP_PROPERTIES props{}; diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index 8bc7f42cde..d64b1835e2 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -1943,6 +1943,8 @@ std::size_t readable_window(u64 address, std::size_t wanted) // Per-list state while recording. struct Pass { + struct CopyRange { ID3D12Resource* resource; u64 offset, bytes; }; + std::vector copied_gpu_ranges; // exact CopyBufferRegion destinations on this recording bool pipeline_real = false; // the bound pipeline has a desktop pipeline bool compute_pipeline = false; ID3D12RootSignature* compute_root = nullptr; // desktop compute root set by slot 33 @@ -2004,6 +2006,38 @@ Pass& pass_of(Wrapper* self) if (!self->own().pass) self->own().pass = new Pass; return *static_cast(self->own().pass); } + +bool indirect_copy_ranges() +{ + static const bool enabled = x2w_local::env_on("X2W_TRANSLATED_INDIRECT_COPY_RANGES"); + return enabled; +} + +bool list_copied_gpu_range(Wrapper* self, ID3D12Resource* resource, u64 offset, u64 bytes) +{ + if (!indirect_copy_ranges()) return false; + const auto& ranges = pass_of(self).copied_gpu_ranges; + return std::any_of(ranges.begin(), ranges.end(), [&](const Pass::CopyRange& range) { + return range.resource == resource && offset >= range.offset && bytes <= range.bytes && + offset - range.offset <= range.bytes - bytes; + }); +} + +void note_copy_gpu_range(Wrapper* self, ID3D12Resource* resource, u64 offset, u64 bytes, bool authoritative) +{ + if (!indirect_copy_ranges()) return; + auto& ranges = pass_of(self).copied_gpu_ranges; + ranges.erase(std::remove_if(ranges.begin(), ranges.end(), [&](const Pass::CopyRange& range) { + if (range.resource != resource) return false; + return range.offset <= offset ? offset - range.offset < range.bytes : range.offset - offset < bytes; + }), ranges.end()); + if (authoritative && ranges.size() < 64) { + try { ranges.push_back({resource, offset, bytes}); } + catch (const std::bad_alloc&) { return; } + static LONG reports; + if (first_calls(reports, 16)) log("x2w-render recorded GPU buffer copy range: offset 0x%llx, %llu bytes", offset, bytes); + } +} // Desktop resources rest in COMMON between lists; a list moves them as it needs and back at Close. void require_state(Wrapper* self, ID3D12Resource* resource, D3D12_RESOURCE_STATES state) { diff --git a/src/startup_stubs/list_copy.inl b/src/startup_stubs/list_copy.inl index b144d04e9b..2e82c5bbdb 100644 --- a/src/startup_stubs/list_copy.inl +++ b/src/startup_stubs/list_copy.inl @@ -155,6 +155,24 @@ x2w_startup::CopyRefusal check_roles_and_sync(Wrapper* self, const CopyEndpoint& return x2w_startup::CopyRefusal::none; } +// A covered range in a copied placement is useful only if the recorded copy read an authoritative source. +bool copy_source_authoritative(Wrapper* self, const CopyEndpoint& from, u64 offset, u64 bytes) +{ + if (!from.wrapper || !InterlockedCompareExchange(&from.wrapper->own().refs, 0, 0)) return false; + const auto* info = resource_info(from.wrapper); + if (!info || info->initial_state != D3D12_RESOURCE_STATE_COMMON) return false; + x2w_startup::ComPtr device; + if (FAILED(from.resource->GetDevice(IID_PPV_ARGS(device.GetAddressOf()))) || device.Get() != device_of(self->own().list_device)) + return false; + if (!from.wrapper->own().title_memory) return true; + if (!info->placement_device || info->placement_device != self->own().list_device) return false; + const auto address = reinterpret_cast(from.wrapper->own().title_memory); + if (offset > UINT64_MAX - address) return false; + const auto placed = placed_buffer_range(self->own().list_device, address + offset, bytes); + if (placed.reject || placed.owner != from.wrapper) return false; + return placed.alias || list_copied_gpu_range(self, from.resource, offset, bytes); +} + // List slot 15, CopyBufferRegion(destination, destination offset, source, source offset, bytes). void __stdcall list_copy_buffer_region(Wrapper* self, u64 destination, u64 destination_offset, u64 source, u64 source_offset, u64 bytes) @@ -168,13 +186,21 @@ void __stdcall list_copy_buffer_region(Wrapper* self, u64 destination, u64 desti auto refusal = x2w_startup::check_copy_buffer_region(to.resource ? &to_desc : nullptr, destination_offset, from.resource ? &from_desc : nullptr, source_offset, bytes, to.resource == from.resource); - if (refusal == x2w_startup::CopyRefusal::none) refusal = check_roles_and_sync(self, to, from, true); + if (refusal == x2w_startup::CopyRefusal::none) refusal = check_endpoint_roles(to, from); + const bool authoritative = refusal == x2w_startup::CopyRefusal::none && indirect_copy_ranges() && + copy_source_authoritative(self, from, source_offset, bytes); + if (refusal == x2w_startup::CopyRefusal::none && !authoritative && !sync_title_source(self, from)) + refusal = x2w_startup::CopyRefusal::title_backed_source; if (refusal != x2w_startup::CopyRefusal::none) return refuse_copy("CopyBufferRegion", refusal); require_copy_state(self, from.resource, D3D12_RESOURCE_STATE_COPY_SOURCE); require_copy_state(self, to.resource, D3D12_RESOURCE_STATE_COPY_DEST); static_cast(self->own().real) ->CopyBufferRegion(to.resource, destination_offset, from.resource, source_offset, bytes); - mark_gpu_written(self, to); + if (indirect_copy_ranges()) { + const auto* info = to.wrapper ? resource_info(to.wrapper) : nullptr; + note_copy_gpu_range(self, to.resource, destination_offset, bytes, authoritative && info && + info->placement == Placement::copied_buffer && info->placement_device == self->own().list_device); + } InterlockedIncrement(&list_buffer_copies); } @@ -194,7 +220,9 @@ void __stdcall list_copy_resource(Wrapper* self, u64 destination, u64 source) require_copy_state(self, from.resource, D3D12_RESOURCE_STATE_COPY_SOURCE); require_copy_state(self, to.resource, D3D12_RESOURCE_STATE_COPY_DEST); static_cast(self->own().real)->CopyResource(to.resource, from.resource); - mark_gpu_written(self, to); + if (to_desc.Dimension == D3D12_RESOURCE_DIMENSION_BUFFER) + note_copy_gpu_range(self, to.resource, 0, to_desc.Width, false); + else mark_gpu_written(self, to); InterlockedIncrement(&list_resource_copies); } diff --git a/tests/startup_indirect_draw_indexed.cpp b/tests/startup_indirect_draw_indexed.cpp index 6671290416..564f0c3c1f 100644 --- a/tests/startup_indirect_draw_indexed.cpp +++ b/tests/startup_indirect_draw_indexed.cpp @@ -31,6 +31,7 @@ constexpr Words initial{0xa5a5a5a5, 0, 0, 0, 0, 0, 0x5a5a5a5a}; constexpr std::array indices{99, 99, 99, 0, 1, 2, 3, 4, 5, 99}; constexpr std::array wide_indices{99, 99, 99, 0, 1, 2, 3, 4, 5, 99}; constexpr UINT argument_offset = sizeof(std::uint32_t); +constexpr UINT64 replay_copy_offset = 0xbfffa0, replay_copy_bytes = 0x44; constexpr char shader[] = R"( RWByteAddressBuffer data : register(u0); @@ -63,6 +64,17 @@ void write_buffer_colour() { data.Store(32, 0xff0000ffu); } +[numthreads(1, 1, 1)] +void write_replay_colour() { + data.Store(0, 0xff00ff00u); + data.Store(4, 0xff00ff00u); + data.Store4(0xbfffa0, uint4(0xff00ff00u, 0xff0000ffu, 0, 0)); + data.Store4(0xbfffb0, uint4(0, 0, 0, 0)); + data.Store4(0xbfffc0, uint4(0, 0, 0, 0)); + data.Store4(0xbfffd0, uint4(0, 0, 0, 0)); + data.Store(0xbfffe0, 0); +} + [numthreads(1, 1, 1)] void write_one_mesh_group() { data.Store3(4, uint3(1, 1, 1)); @@ -316,32 +328,39 @@ void submit(ID3D12Device* device, ID3D12GraphicsCommandList* list) } enum class Refusal { none, invalid_index, short_argument, missing_viewport, wrong_root, missing_texture, start_vertex, - insufficient_table_range, copied_table_buffer, upload_range_crossing }; + insufficient_table_range, copied_table_buffer, upload_range_crossing, unproven_copy }; enum class DrawKind { indexed, vertices, mesh }; +ComPtr make_gpu_table_buffer(ID3D12Device* guest, UINT64 bytes) +{ + const D3D12_HEAP_PROPERTIES props{D3D12_HEAP_TYPE_DEFAULT}; + const D3D12_RESOURCE_DESC desc{D3D12_RESOURCE_DIMENSION_BUFFER, 0, bytes, 1, 1, 1, DXGI_FORMAT_UNKNOWN, {1, 0}, + D3D12_TEXTURE_LAYOUT_ROW_MAJOR, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS}; + using Create = HRESULT (WINAPI*)(IUnknown*, const D3D12_HEAP_PROPERTIES*, UINT, const D3D12_RESOURCE_DESC*, + UINT, const void*, void*, UINT, const void*, REFIID, void**); + ComPtr result; + check(slot(guest, 127)(guest, &props, 0, &desc, D3D12_RESOURCE_STATE_COMMON, nullptr, nullptr, + 0, nullptr, __uuidof(ID3D12Resource), reinterpret_cast(result.GetAddressOf())), "create GPU table buffer"); + return result; +} + struct TranslatedDrawFixture { TranslatedDrawFixture(ID3D12Device* guest, std::uint32_t colour, ID3D12Device* desktop = nullptr, - bool short_view = false, bool copied = false) + bool short_view = false, bool copied = false, bool replay = false) : wrong_root(create_root(guest, {0, nullptr, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_NONE})), backing(VirtualAlloc(nullptr, 65536, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)) { if (!backing) throw std::bad_alloc(); if (desktop && !copied) { - const D3D12_HEAP_PROPERTIES props{D3D12_HEAP_TYPE_DEFAULT}; - const D3D12_RESOURCE_DESC desc{D3D12_RESOURCE_DIMENSION_BUFFER, 0, 64, 1, 1, 1, DXGI_FORMAT_UNKNOWN, {1, 0}, - D3D12_TEXTURE_LAYOUT_ROW_MAJOR, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS}; - using Create = HRESULT (WINAPI*)(IUnknown*, const D3D12_HEAP_PROPERTIES*, UINT, const D3D12_RESOURCE_DESC*, - UINT, const void*, void*, UINT, const void*, REFIID, void**); - check(slot(guest, 127)(guest, &props, 0, &desc, D3D12_RESOURCE_STATE_COMMON, nullptr, nullptr, - 0, nullptr, __uuidof(ID3D12Resource), reinterpret_cast(sampled.GetAddressOf())), "create GPU table buffer"); + sampled = make_gpu_table_buffer(guest, 64); } else { const D3D12_RESOURCE_DESC desc = copied ? - D3D12_RESOURCE_DESC{D3D12_RESOURCE_DIMENSION_BUFFER, 0, 64, 1, 1, 1, DXGI_FORMAT_UNKNOWN, {1, 0}, + D3D12_RESOURCE_DESC{D3D12_RESOURCE_DIMENSION_BUFFER, 0, replay ? replay_copy_bytes : 64u, 1, 1, 1, DXGI_FORMAT_UNKNOWN, {1, 0}, D3D12_TEXTURE_LAYOUT_ROW_MAJOR, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS} : D3D12_RESOURCE_DESC{D3D12_RESOURCE_DIMENSION_TEXTURE2D, 0, 1, 1, 1, 1, format, {1, 0}, D3D12_TEXTURE_LAYOUT_UNKNOWN, D3D12_RESOURCE_FLAG_NONE}; auto* address = static_cast(backing.get()) + (copied ? 16 : 0); - std::memcpy(address + (copied ? 32 : 0), &colour, sizeof(colour)); + std::memcpy(address + (replay ? 4 : copied ? 32 : 0), &colour, sizeof(colour)); using Place = HRESULT (WINAPI*)(IUnknown*, void*, const D3D12_RESOURCE_DESC*, UINT, const void*, REFIID, void**); check(slot(guest, 133)(guest, address, &desc, D3D12_RESOURCE_STATE_COMMON, nullptr, __uuidof(ID3D12Resource), reinterpret_cast(sampled.GetAddressOf())), "place sampled resource"); @@ -363,9 +382,9 @@ struct TranslatedDrawFixture { if (desktop) { srv.Format = DXGI_FORMAT_UNKNOWN; srv.ViewDimension = D3D12_SRV_DIMENSION_BUFFER; - srv.Buffer.FirstElement = 1; - srv.Buffer.NumElements = short_view ? 1 : 2; - srv.Buffer.StructureByteStride = 16; + srv.Buffer.FirstElement = replay ? 0 : 1; + srv.Buffer.NumElements = replay ? static_cast(replay_copy_bytes / 4) : short_view ? 1 : 2; + srv.Buffer.StructureByteStride = replay ? 4 : 16; } else { srv.Format = format; srv.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; @@ -389,6 +408,14 @@ struct TranslatedDrawFixture { UINT64 gpu = 0; }; +struct ReplayCopy { + ID3D12Resource* producer; + ID3D12Resource* native; + ID3D12PipelineState* writer; + UINT64 bytes; + bool uncertified_overwrite = false; +}; + constexpr UINT command_stride(DrawKind kind) { switch (kind) { @@ -409,7 +436,7 @@ bool supports_mesh(ID3D12Device* device) bool run(ID3D12Device* device, ID3D12Device* guest, ID3D12RootSignature* writer_root, ID3D12PipelineState* writer, ID3D12RootSignature* graphics_root, IUnknown* graphics, ID3D12CommandSignature* signature, DrawKind kind, bool draw_right, Refusal refusal, const char* label, - const TranslatedDrawFixture* translated = nullptr, bool upload_table = false) + const TranslatedDrawFixture* translated = nullptr, bool upload_table = false, const ReplayCopy* replay = nullptr) { const bool indexed = kind == DrawKind::indexed; const bool mesh = kind == DrawKind::mesh; @@ -482,6 +509,18 @@ bool run(ID3D12Device* device, ID3D12Device* guest, ID3D12RootSignature* writer_ list->CopyBufferRegion(arg_readback.Get(), 0, arguments.native.Get(), 0, sizeof(initial)); // The wrapper owns the subsequent COMMON -> INDIRECT_ARGUMENT transition. transition(list, arguments.native.Get(), D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_COMMON); + if (replay) { + transition(list, replay->native, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + list->SetPipelineState(replay->writer); + list->SetComputeRootSignature(writer_root); + list->SetComputeRootUnorderedAccessView(0, replay->native->GetGPUVirtualAddress()); + list->Dispatch(1, 1, 1); + transition(list, replay->native, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COMMON); + using Copy = void (WINAPI*)(IUnknown*, IUnknown*, UINT64, IUnknown*, UINT64, UINT64); + slot(wrapped, 15)(wrapped, translated->sampled.Get(), 0, replay->producer, replay_copy_offset, replay->bytes); + if (replay->uncertified_overwrite) + slot(wrapped, 15)(wrapped, translated->sampled.Get(), 0, replay->native, 0, 4); + } if (translated && translated->gpu_buffer && translated->buffer_writer) { auto* table_resource = translated->gpu_buffer.Get(); transition(list, table_resource, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); @@ -637,7 +676,9 @@ std::string indirect_line(ID3D12Device* guest, const std::wstring& log_path) int main(int argc, char** argv) try { DrawKind kind = DrawKind::indexed; - const bool translated = argc == 3 && std::strcmp(argv[2], "translated") == 0; + const bool copy_on = argc == 3 && std::strcmp(argv[2], "copy-provenance") == 0; + const bool copy_off = argc == 3 && std::strcmp(argv[2], "copy-provenance-off") == 0; + const bool translated = copy_on || copy_off || (argc == 3 && std::strcmp(argv[2], "translated") == 0); // "count-control" is the negative control: it expects one forwarded call too many. const bool count_control = argc == 3 && std::strcmp(argv[2], "count-control") == 0; if (translated || (argc == 3 && std::strcmp(argv[2], "draw") == 0)) kind = DrawKind::vertices; @@ -712,6 +753,8 @@ int main(int argc, char** argv) try std::filesystem::create_directory(cache); check(SetEnvironmentVariableW(L"X2W_SHADER_CACHE", cache.c_str()) ? S_OK : E_FAIL, "set fixture cache"); check(SetEnvironmentVariableA("X2W_TRANSLATED_INDIRECT_DRAW", "1") ? S_OK : E_FAIL, "enable fixture path"); + check(SetEnvironmentVariableA("X2W_TRANSLATED_INDIRECT_COPY_RANGES", copy_on ? "1" : "0") ? S_OK : E_FAIL, + "set copy-range provenance control"); const D3D12_DESCRIPTOR_RANGE range{D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 1, 0, 0, 0}; D3D12_ROOT_PARAMETER table{}; table.ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; @@ -769,6 +812,29 @@ int main(int argc, char** argv) try } else { std::puts("deferred guest root capability unavailable"); } + if (ok && (copy_on || copy_off)) { + const TranslatedDrawFixture copied(guest.Get(), green, device.Get(), false, true, true); + const auto source = make_gpu_table_buffer(guest.Get(), replay_copy_offset + replay_copy_bytes); + const auto native = native_object(device.Get(), guest.Get(), source.Get()); + const auto replay_writer = writer_pipeline(device.Get(), writer.Get(), "write_replay_colour"); + const ReplayCopy complete{source.Get(), native.Get(), replay_writer.Get(), replay_copy_bytes}; + const ReplayCopy partial{source.Get(), native.Get(), replay_writer.Get(), replay_copy_bytes - 4}; + const ReplayCopy overwritten{source.Get(), native.Get(), replay_writer.Get(), replay_copy_bytes, true}; + const auto draw = [&](const ReplayCopy* copy, Refusal refusal, const char* label) { + return run(device.Get(), guest.Get(), writer.Get(), producer.Get(), title_root.Get(), buffer_pso.Get(), signature.Get(), + DrawKind::vertices, false, refusal, label, &copied, false, copy); + }; + ok = draw(&complete, copy_on ? Refusal::none : Refusal::unproven_copy, "complete 68-byte GPU copy") && + draw(nullptr, Refusal::unproven_copy, "new recording cannot reuse the previous GPU copy proof") && + draw(&partial, Refusal::unproven_copy, "64-byte copy cannot authorize the 68-byte view") && + draw(&overwritten, Refusal::unproven_copy, "untracked overlap invalidates the prior copy range"); + std::uint32_t title_word = 0; + std::memcpy(&title_word, static_cast(copied.backing.get()) + 20, sizeof(title_word)); + if (title_word != green) { + std::fprintf(stderr, "title-side green sentinel changed to %08x\n", title_word); + return 1; + } + } if (ok) std::filesystem::remove_all(cache); return ok && (!info || !info->GetNumStoredMessages()) ? 0 : 1; }