From 0001bb1544bbb249a30e094279fe29dc6e9d4c9e Mon Sep 17 00:00:00 2001 From: tedin7 Date: Tue, 24 Nov 2026 20:03:48 +0100 Subject: [PATCH 1/6] 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/6] 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/6] 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/6] 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/6] 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/6] 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);