From 3b27011f65f4933ec873ebb3e55aee1a44a3ac24 Mon Sep 17 00:00:00 2001 From: Taffyyy-ops <359860351+Taffyyy-ops@users.noreply.github.com> Date: Tue, 24 Nov 2026 20:54:44 +0100 Subject: [PATCH] runtime: support placed buffers in OpenExistingHeapFromAddress heaps (RT-EXISTING-HEAP-PLACED) Implement CreatePlacedResource/1/2 for buffers inside existing heaps backed by VK_EXT_external_memory_host, enforce host D3D12 SHARED_CROSS_ADAPTER -> ALLOW_CROSS_ADAPTER validation, and flush Intel WDDM asynchronous host-import unpins before VirtualFree. AI-assisted; 100% synthetic tests only, no game data. --- docs/README.md | 1 + docs/existing_heaps.md | 46 ++ runtime/CMakeLists.txt | 7 + runtime/shims/d3d12_vulkan_device.cpp | 178 ++++- .../test/d3d12_existing_heap_placed_test.cpp | 731 ++++++++++++++++++ runtime/test/d3d12_existing_heap_test.cpp | 18 +- 6 files changed, 949 insertions(+), 32 deletions(-) create mode 100644 docs/existing_heaps.md create mode 100644 runtime/test/d3d12_existing_heap_placed_test.cpp diff --git a/docs/README.md b/docs/README.md index de581b8653..d144b334dc 100644 --- a/docs/README.md +++ b/docs/README.md @@ -103,6 +103,7 @@ method, scope and caveats. No game data is included. | [coder.md](coder.md) | The compressed mass in `story000_script.rpf`: entry framing (`align16(entry+8)` payload), the 32-value tag alphabet, deflate-shaped but proprietary, variable-length 7/8-bit LSB-first codes with no stored table, and the `n7 = 116..127` search that finishes it. | | [mission_logic.md](mission_logic.md) | Mission state tables: 0x20 record layout (band counter, byte offsets), the 64-byte pool element with world transforms, case-folding joaat keys, 53.5 % of states named, 113 state-set clusters covering 82.4 % of files. | | [gbuffer.md](gbuffer.md) | Deferred G-buffer targets (`PS_DeferredTextured` and all 2,989 `*Deferred*` pixel shaders, `PROC-146`): 5- and 6-target `OSG1`/`PSV0` signatures (`float32` + `exp ... compr` on all outputs), the 24-bit octahedral normal split across `mrt1.gba` (`2047.5` scale, `1/255` byte packing), sqrt-encoded `mrt2`, byte IDs in `mrt3.zw`, float motion in `mrt4`, and why binding `f16` targets mangles the normal bytes. | +| [existing_heaps.md](existing_heaps.md) | Placed buffers inside `ID3D12Device3::OpenExistingHeapFromAddress` existing heaps (`RT-EXISTING-HEAP-PLACED`): measured Windows D3D12 `SHARED_CROSS_ADAPTER` / `ALLOW_CROSS_ADAPTER` rules, zero-copy `Map()` and `HOST_READ` barrier contract, synchronous teardown order, and Intel WDDM asynchronous host-import unpin mitigation (`DeviceState::flush_host_import_unpin`). | ## Other languages diff --git a/docs/existing_heaps.md b/docs/existing_heaps.md new file mode 100644 index 0000000000..d3518ba9ff --- /dev/null +++ b/docs/existing_heaps.md @@ -0,0 +1,46 @@ +# Placed buffers in `OpenExistingHeapFromAddress` heaps (`RT-EXISTING-HEAP-PLACED`) + +This note records the measured Windows D3D12 contract, Vulkan host-memory import rules, and Intel WDDM residency findings for placing buffers inside `ID3D12Device3::OpenExistingHeapFromAddress` heaps (`runtime/shims/d3d12_vulkan_device.cpp`). + +## 1. Host D3D12 cross-adapter and creation rules + +An `OpenExistingHeapFromAddress` heap opens a `VirtualAlloc` region whose entire committed span is `PAGE_READWRITE` or `PAGE_READWRITE | PAGE_WRITECOMBINE` and reports `D3D12_HEAP_TYPE_CUSTOM`, `D3D12_MEMORY_POOL_L0`, `D3D12_CPU_PAGE_PROPERTY_WRITE_BACK` (or `WRITE_COMBINE`), alignment `64 KiB`, and flags `SHARED | SHARED_CROSS_ADAPTER | ALLOW_SHADER_ATOMICS` (`0x421`). + +Measured across live Windows 11 D3D12 adapters (NVIDIA GeForce RTX 5060 Laptop GPU, Intel UHD Graphics / RaptorLake-S, and WARP): + +| Case on an existing heap | Windows host D3D12 | Vulkan layer (`create_placed`) | Notes | +|---|---|---|---| +| Buffer with `D3D12_RESOURCE_FLAG_ALLOW_CROSS_ADAPTER` (`0x10`) at 64 KiB-aligned offset | `S_OK` | `S_OK` | Same `GetHeapProperties` (`CUSTOM / WRITE_BACK or WRITE_COMBINE / L0`, node masks `1 / 1`, flags `0x421`). | +| Buffer without `ALLOW_CROSS_ADAPTER` (e.g. `NONE` or `ALLOW_UNORDERED_ACCESS` alone) | `E_INVALIDARG` | `E_INVALIDARG` | Applies to `CreatePlacedResource`, `CreatePlacedResource1`, and `CreatePlacedResource2`. | +| Unaligned offset (`4096`), out-of-bounds range, zero width, clear value on buffer | `E_INVALIDARG` | `E_INVALIDARG` | Checked before `E_NOTIMPL` or `out == nullptr`. | +| Valid buffer args with `ppvResource == nullptr` | `E_UNEXPECTED` | `E_UNEXPECTED` | Nothing created. | +| `CreatePlacedResource2` with `D3D12_BARRIER_LAYOUT_COMMON` or castable format list on buffer | `E_INVALIDARG` | `E_INVALIDARG` | `D3D12_BARRIER_LAYOUT_UNDEFINED` succeeds. | +| Placed texture (`TEXTURE2D`) with `ALLOW_CROSS_ADAPTER` | driver-dependent | `E_NOTIMPL` | Only placed buffers in existing heaps are implemented; placed textures stay unimplemented cleanly. | + +On heaps without `D3D12_HEAP_FLAG_SHARED_CROSS_ADAPTER` (and in `CreateCommittedResource`), `D3D12_RESOURCE_FLAG_ALLOW_CROSS_ADAPTER` remains refused (`E_INVALIDARG`), matching Windows host D3D12. + +Through the Xbox-ABI proxy (`runtime/shims/d3d12_xs_device.cpp`), vtable slot `48` is shadowed by Xbox `CreateCommandQueueX`, whereas slot `29` (`CreatePlacedResource`) forwards directly to the backing PC device and accepts heaps opened on that device. + +## 2. Vulkan backing, `Map()`, and GPU virtual addresses + +- **Memory type selection:** `OpenExistingHeapFromAddress` probes a temporary `VkBuffer` configured with `VK_EXTERNAL_MEMORY_HANDLE_TYPE_HOST_ALLOCATION_BIT_EXT` (`DeviceState::host_buffer_info`) and intersects `VkMemoryHostPointerPropertiesEXT::memoryTypeBits & probe_req.memoryTypeBits` before `vkAllocateMemory`. `VK_MEMORY_ALLOCATE_DEVICE_ADDRESS_BIT` and `VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT` are attached only when `DeviceState::need_buffer_device_address()` is true (explicit `buffer_device_address` or live GPU address arena). +- **Zero-copy buffer placement (`Resource::create_existing_heap_buffer`):** `CreatePlacedResource`, `CreatePlacedResource1`, and `CreatePlacedResource2` create a `VkBuffer` with `VK_EXTERNAL_MEMORY_HANDLE_TYPE_HOST_ALLOCATION_BIT_EXT` and bind it directly to the heap's imported `VkDeviceMemory` at `heap_offset`. +- **Preservation and visibility:** Pre-filled host pages are never zeroed on heap creation or buffer placement. `Map(0, nullptr, &ptr)` returns the caller's live address (`heap_host_address + heap_offset`). `ResourceBinding::host_readable` is set `true` so GPU writes into placed buffers emit a `TRANSFER -> HOST_READ` barrier (`runtime/src/vulkan_backend.h` and `runtime/src/vulkan_replay.h`) before completion, making GPU writes immediately visible to direct CPU reads on `VirtualAlloc` pages. +- **Address tracking and aliasing:** When the host address sits above `arena.size`, `va_` takes the host virtual address (`buffer_va_ - arena.address` otherwise), keeping `GetGPUVirtualAddress()` monotonically offset by `heap_offset` without colliding with arena offsets. Overlapping placed buffers in the same existing heap are registered in `BufferVaIndex` (`runtime/src/buffer_va_index.h`), which resolves replay lookups to a binding covering the requested byte range. + +## 3. Teardown safety and the Intel WDDM unpin bug + +`VK_EXT_external_memory_host` requires caller pages to outlive the imported `VkDeviceMemory`, and `ID3D12Resource` holds a `std::shared_ptr` reference so releasing `ID3D12Heap` before releasing placed buffers keeps the imported `VkDeviceMemory` alive until the last placed buffer dies. On destruction: + +1. `Resource::~Resource()` waits on `context->wait_retire_ticket(context->submitted_retire_ticket())`, calls `vkDestroyBuffer` **before** `heap_range_.reset()` so buffers always die before the heap's `VkDeviceMemory`. +2. When the last reference to the existing heap's `TileHeapAllocation` drops, its deleter waits for the latest submitted retire ticket and calls `vkFreeMemory`. + +**Intel WDDM finding (RaptorLake-S, vendor `0x8086`):** Direct Vulkan probes showed that calling `vkFreeMemory` on a `VK_EXT_external_memory_host` import and immediately returning the pages with `VirtualFree` without a real GPU submission in between leaves Intel's Windows WDDM driver asynchronously unpinning `ExistingSysMem` against freed pages, driving subsequent `vkQueueSubmit` calls into `VK_ERROR_DEVICE_LOST` (`-4`). Calling `vkDeviceWaitIdle`, `vkQueueWaitIdle`, or submitting an empty command buffer did not clear the unpin, whereas submitting a single barrier-only command buffer (`vkCmdPipelineBarrier` via `DeviceState::flush_host_import_unpin()` on `staging_queue`) and idling the queue resolves it deterministically across both `PAGE_READWRITE` and `PAGE_READWRITE | PAGE_WRITECOMBINE`. + +## 4. Verification + +All checks run with `runtime/test/d3d12_existing_heap_test.cpp` and `runtime/test/d3d12_existing_heap_placed_test.cpp` (`0` compiler warnings under MSVC `/W4 /permissive-`, `0` Vulkan errors): + +- **NVIDIA GeForce RTX 5060 Laptop GPU (driver `621.24`):** `8/8` `OpenExistingHeapFromAddress` parity cases + `15/15` placed existing-heap parity cases (`CreatePlacedResource`/`1`/`2` + `GetHeapProperties`), `no-bda` and `bda+arena` bidirectional CPU↔GPU coherence, overlapping aliases, heap-before-buffer release, `64`-iteration `VirtualAlloc`→`VirtualFree` stress loop, and Xbox device proxy (`slot 29`) all pass. +- **Intel(R) RaptorLake-S Mobile Graphics Controller:** Same `8/8` and `15/15` parity cases plus all coherence, aliasing, lifetime, `64`-iteration stress, and Xbox proxy checks pass; pre-existing failure in `d3d12_existing_heap` after `open_cases` is eliminated by `flush_host_import_unpin()`. +- **Microsoft Basic Render Driver (WARP):** `8/8` `OpenExistingHeapFromAddress` parity cases and `15/15` existing-heap `CreatePlacedResource`/`1`/`2` + `GetHeapProperties` parity cases match identically. diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index e1dc137723..2d92acd88d 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -2068,6 +2068,13 @@ if(TARGET Vulkan::Headers) target_compile_options(d3d12_existing_heap_test PRIVATE /W4 /permissive- /utf-8) add_test(NAME d3d12_existing_heap COMMAND d3d12_existing_heap_test) set_tests_properties(d3d12_existing_heap PROPERTIES SKIP_RETURN_CODE 77) + # Placed buffers inside OpenExistingHeapFromAddress existing heaps (RT-EXISTING-HEAP-PLACED). + add_executable(d3d12_existing_heap_placed_test test/d3d12_existing_heap_placed_test.cpp) + target_link_libraries(d3d12_existing_heap_placed_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) + target_compile_definitions(d3d12_existing_heap_placed_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(d3d12_existing_heap_placed_test PRIVATE /W4 /permissive- /utf-8) + add_test(NAME d3d12_existing_heap_placed COMMAND d3d12_existing_heap_placed_test) + set_tests_properties(d3d12_existing_heap_placed PROPERTIES SKIP_RETURN_CODE 77) # Slot 133 on untouched xmem physical pages: committed through the pages hook, then imported. xmem.cpp and # registry.cpp are compiled in, as xmem_test does, to reach the registered XMem* exports. add_executable(d3d12_xmem_placed_test test/d3d12_xmem_placed_test.cpp shims/xmem.cpp shims/registry.cpp) diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index e9bc191952..2edc4a7c93 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -675,6 +675,40 @@ struct DeviceState { bool sparse_image_tiles = false; bool tiles_share_arena() const { return (sparse_buffer_memory_types & (1u << arena.memory_type)) != 0; } + bool need_buffer_device_address() const { return info.buffer_device_address || arena.buffer != VK_NULL_HANDLE; } + + VkBufferCreateInfo host_buffer_info(VkDeviceSize bytes, const void* next = nullptr) const { + VkBufferCreateInfo result{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO, next}; + result.size = bytes; + result.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT | + VK_BUFFER_USAGE_VERTEX_BUFFER_BIT | VK_BUFFER_USAGE_INDEX_BUFFER_BIT | + VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | + VK_BUFFER_USAGE_INDIRECT_BUFFER_BIT; + if (info.conditional_rendering) result.usage |= VK_BUFFER_USAGE_CONDITIONAL_RENDERING_BIT_EXT; + if (need_buffer_device_address()) result.usage |= VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT; + share(result); + return result; + } + + // Intel's Windows Vulkan driver (measured on RaptorLake-S) updates WDDM residency for + // VK_EXT_external_memory_host allocations asynchronously: calling vkFreeMemory and then VirtualFree + // without a real queue submission in between leaves WDDM's paging engine referencing the freed pages and + // puts the device into VK_ERROR_DEVICE_LOST. Submitting a barrier-only empty list through staging_queue + // and waiting for the queue to idle drains the unpin before the caller returns the pages to Windows. + void flush_host_import_unpin() { + constexpr std::uint32_t kIntelVendorId = 0x8086; + if (pso_identity.vendor != kIntelVendorId || !context || context->is_device_lost()) return; + leonida::CommandList list; + if (!list.close()) return; + std::lock_guard lock(staging_mutex); + if (!staging_queue) { + staging_queue = std::make_unique(*context, info.queue, info.queue_family); + } + if (staging_queue->ok()) { + const leonida::CommandList* lists[] = {&list}; + if (staging_queue->execute(lists) == leonida::ReplayResult::success) staging_queue->idle(); + } + } VkBufferCreateInfo sparse_buffer_info(VkDeviceSize bytes) const { VkBufferCreateInfo result{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO}; @@ -1802,13 +1836,17 @@ class Resource final // VK_EXT_external_memory_host needs the caller's pages to stay valid for the imported memory's whole // lifetime, and a title may free them right after releasing the resource. So the memory is not left to // the deferred queue (freed after the *next* submission retires): wait for what was submitted, then - // free it now (found in review). + // destroy the buffer and release the memory (or the placed heap range) now (found in review). device_.context->wait_retire_ticket(device_.context->submitted_retire_ticket()); auto& vk = device_.context->vk; if (buffer_) vk.vkDestroyBuffer(device_.info.device, buffer_, nullptr); - if (memory_) vk.vkFreeMemory(device_.info.device, memory_, nullptr); + if (memory_) { + vk.vkFreeMemory(device_.info.device, memory_, nullptr); + device_.flush_host_import_unpin(); + } buffer_ = VK_NULL_HANDLE; memory_ = VK_NULL_HANDLE; + heap_range_.reset(); } if (in_arena_) device_.arena_release(arena_offset_, desc_.Width, DeviceState::arena_buffer); if (image_ && !sparse_image_) @@ -2014,18 +2052,10 @@ class Resource final at = region_end - base; } if (!importable) return E_NOTIMPL; - const bool need_bda = device_.info.buffer_device_address || device_.arena.buffer != VK_NULL_HANDLE; + const bool need_bda = device_.need_buffer_device_address(); VkExternalMemoryBufferCreateInfo external{VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_BUFFER_CREATE_INFO}; external.handleTypes = VK_EXTERNAL_MEMORY_HANDLE_TYPE_HOST_ALLOCATION_BIT_EXT; - VkBufferCreateInfo info{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO, &external}; - info.size = desc_.Width; - info.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT | - VK_BUFFER_USAGE_VERTEX_BUFFER_BIT | VK_BUFFER_USAGE_INDEX_BUFFER_BIT | - VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | - VK_BUFFER_USAGE_INDIRECT_BUFFER_BIT; - if (device_.info.conditional_rendering) info.usage |= VK_BUFFER_USAGE_CONDITIONAL_RENDERING_BIT_EXT; - if (need_bda) info.usage |= VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT; - device_.share(info); + VkBufferCreateInfo info = device_.host_buffer_info(desc_.Width, &external); if (vk.vkCreateBuffer(device_.info.device, &info, nullptr, &buffer_) != VK_SUCCESS) return E_OUTOFMEMORY; VkMemoryRequirements requirements{}; vk.vkGetBufferMemoryRequirements(device_.info.device, buffer_, &requirements); @@ -2184,6 +2214,62 @@ class Resource final return S_OK; } + // A placed buffer inside an OpenExistingHeapFromAddress existing heap: binds a VkBuffer directly to the heap's + // imported VkDeviceMemory at `heap_offset`, keeping the caller's host pages intact (nothing zeroed) and exposing + // `heap_host_address + heap_offset` through Map(). + HRESULT create_existing_heap_buffer(std::shared_ptr heap_range, + const void* heap_host_address, UINT64 heap_offset) { + if (!heap_range || heap_range->memory == VK_NULL_HANDLE || !heap_host_address || !desc_.Width || + desc_.Width > heap_range->size || heap_offset > heap_range->size - desc_.Width) + return E_INVALIDARG; + auto& vk = device_.context->vk; + const bool need_bda = device_.need_buffer_device_address(); + VkExternalMemoryBufferCreateInfo external{VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_BUFFER_CREATE_INFO}; + external.handleTypes = VK_EXTERNAL_MEMORY_HANDLE_TYPE_HOST_ALLOCATION_BIT_EXT; + VkBufferCreateInfo info = device_.host_buffer_info(desc_.Width, &external); + if (vk.vkCreateBuffer(device_.info.device, &info, nullptr, &buffer_) != VK_SUCCESS) return E_OUTOFMEMORY; + VkMemoryRequirements requirements{}; + vk.vkGetBufferMemoryRequirements(device_.info.device, buffer_, &requirements); + if (!(requirements.memoryTypeBits & (1u << heap_range->memory_type)) || + (requirements.alignment && (heap_offset % requirements.alignment) != 0) || + requirements.size > heap_range->size || heap_offset > heap_range->size - requirements.size) { + vk.vkDestroyBuffer(device_.info.device, buffer_, nullptr); + buffer_ = VK_NULL_HANDLE; + return E_NOTIMPL; + } + if (vk.vkBindBufferMemory(device_.info.device, buffer_, heap_range->memory, heap_offset) != VK_SUCCESS) { + vk.vkDestroyBuffer(device_.info.device, buffer_, nullptr); + buffer_ = VK_NULL_HANDLE; + return E_OUTOFMEMORY; + } + void* const cpu_ptr = static_cast(const_cast(heap_host_address)) + heap_offset; + heap_range_ = std::move(heap_range); + mapped_ = cpu_ptr; + host_import_ = true; + memory_flags_ = device_.memory.memoryTypes[heap_range_->memory_type].propertyFlags; + const auto host_va = reinterpret_cast(cpu_ptr); + if (need_bda && vk.vkGetBufferDeviceAddress) { + VkBufferDeviceAddressInfo bda{VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO}; + bda.buffer = buffer_; + buffer_va_ = vk.vkGetBufferDeviceAddress(device_.info.device, &bda); + gpu_va_ = buffer_va_; + } + if (host_va >= device_.arena.size) + va_ = host_va; + else if (buffer_va_ && device_.arena.buffer != VK_NULL_HANDLE) + va_ = buffer_va_ - device_.arena.address; + else + va_ = host_va; + leonida::ResourceBinding binding{}; + binding.buffer = buffer_; + binding.size = desc_.Width; + binding.host = cpu_writable() ? static_cast(cpu_ptr) : nullptr; + binding.host_readable = true; + binding.va = va_; + device_.context->add_resource(id(), binding); + return S_OK; + } + HRESULT create_texture(const Format& format, const std::vector& castable = {}) { auto& vk = device_.context->vk; const bool volume = desc_.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D; @@ -2812,9 +2898,10 @@ class Heap final : device_(device), desc_(desc), host_address_(address) { allocation_ = std::shared_ptr( new leonida::TileHeapAllocation{memory, 0, desc_.SizeInBytes, memory_type}, - [device = device_.info.device, free = device_.context->vk.vkFreeMemory] - (const leonida::TileHeapAllocation* allocation) { - free(device, allocation->memory, nullptr); + [&device](const leonida::TileHeapAllocation* allocation) { + device.context->wait_retire_ticket(device.context->submitted_retire_ticket()); + device.context->vk.vkFreeMemory(device.info.device, allocation->memory, nullptr); + device.flush_host_import_unpin(); delete allocation; }); } @@ -7047,6 +7134,7 @@ class Device final int(alignment)); return d3d12_trace::result(method, E_NOTIMPL); } + auto& vk = state_.context->vk; VkMemoryHostPointerPropertiesEXT host{VK_STRUCTURE_TYPE_MEMORY_HOST_POINTER_PROPERTIES_EXT}; if (state_.get_host_pointer_properties(state_.info.device, VK_EXTERNAL_MEMORY_HANDLE_TYPE_HOST_ALLOCATION_BIT_EXT, address, @@ -7055,6 +7143,21 @@ class Device final log_once("OpenExistingHeapFromAddress: no memory type imports this host range", 0); return d3d12_trace::result(method, E_NOTIMPL); } + const bool need_bda = state_.need_buffer_device_address(); + VkMemoryRequirements probe_req{}; + { + VkExternalMemoryBufferCreateInfo probe_ext{VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_BUFFER_CREATE_INFO}; + probe_ext.handleTypes = VK_EXTERNAL_MEMORY_HANDLE_TYPE_HOST_ALLOCATION_BIT_EXT; + const VkBufferCreateInfo probe_info = + state_.host_buffer_info(D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT, &probe_ext); + VkBuffer probe = VK_NULL_HANDLE; + if (vk.vkCreateBuffer(state_.info.device, &probe_info, nullptr, &probe) == VK_SUCCESS) { + vk.vkGetBufferMemoryRequirements(state_.info.device, probe, &probe_req); + vk.vkDestroyBuffer(state_.info.device, probe, nullptr); + } + } + const std::uint32_t buffer_types = host.memoryTypeBits & probe_req.memoryTypeBits; + const std::uint32_t candidate_types = buffer_types ? buffer_types : host.memoryTypeBits; VkImportMemoryHostPointerInfoEXT import{VK_STRUCTURE_TYPE_IMPORT_MEMORY_HOST_POINTER_INFO_EXT}; import.handleType = VK_EXTERNAL_MEMORY_HANDLE_TYPE_HOST_ALLOCATION_BIT_EXT; import.pHostPointer = const_cast(address); @@ -7067,13 +7170,14 @@ class Device final {VkMemoryPropertyFlags(VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT), VkMemoryPropertyFlags(0)}) { for (std::uint32_t i = 0; i < state_.memory.memoryTypeCount && !memory; ++i) { - if (!(host.memoryTypeBits & (1u << i)) || + if (!(candidate_types & (1u << i)) || (state_.memory.memoryTypes[i].propertyFlags & want) != want) continue; - VkMemoryAllocateInfo allocate{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO, &flags}; + VkMemoryAllocateInfo allocate{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO, + need_bda ? static_cast(&flags) : &import}; allocate.allocationSize = size; allocate.memoryTypeIndex = i; - if (state_.context->vk.vkAllocateMemory(state_.info.device, &allocate, nullptr, &memory) == + if (vk.vkAllocateMemory(state_.info.device, &allocate, nullptr, &memory) == VK_SUCCESS) memory_type = i; else @@ -7297,13 +7401,6 @@ class Device final if (out) *out = nullptr; auto* heap = Heap::from(heap_interface); if (!heap || !desc) return d3d12_trace::result(method, E_INVALIDARG); - if (heap->host_address()) { - // An existing heap is not an arena range, and the placed path addresses resources by arena offset. - log_once("a placed resource in an existing heap (OpenExistingHeapFromAddress) is not supported yet; " - "dimension", - int(desc->Dimension)); - return d3d12_trace::result(method, E_NOTIMPL); - } if (castable_count && castable && desc->Dimension == D3D12_RESOURCE_DIMENSION_BUFFER) { log_once("castable formats on a placed buffer are invalid; count", int(castable_count)); return d3d12_trace::result(method, E_INVALIDARG); @@ -7312,8 +7409,22 @@ class Device final // DENY flags are checked against the resource below, and the host takes any initial state for a buffer in // an upload or readback heap (COPY_DEST in an upload heap, GENERIC_READ in a readback heap), where a // committed buffer must start in GENERIC_READ or COPY_DEST. UAV access is refused there all the same. + // Cross-adapter heaps (including OpenExistingHeapFromAddress) require D3D12_RESOURCE_FLAG_ALLOW_CROSS_ADAPTER. + const bool cross_adapter_heap = (heap->flags() & D3D12_HEAP_FLAG_SHARED_CROSS_ADAPTER) != 0; + const bool cross_adapter_res = (desc->Flags & D3D12_RESOURCE_FLAG_ALLOW_CROSS_ADAPTER) != 0; + if (cross_adapter_heap && !cross_adapter_res) { + log_once((std::string(method) + " refused (cross-adapter heap requires ALLOW_CROSS_ADAPTER), dimension") + .c_str(), + int(desc->Dimension)); + return d3d12_trace::result(method, E_INVALIDARG); + } + D3D12_RESOURCE_DESC checked_desc = *desc; + if (cross_adapter_heap) { + checked_desc.Flags = + D3D12_RESOURCE_FLAGS(UINT(checked_desc.Flags) & ~UINT(D3D12_RESOURCE_FLAG_ALLOW_CROSS_ADAPTER)); + } const D3D12_HEAP_PROPERTIES default_heap{D3D12_HEAP_TYPE_DEFAULT}; - const char* why = committed_resource_refusal(default_heap, D3D12_HEAP_FLAG_NONE, *desc, state, clear, + const char* why = committed_resource_refusal(default_heap, D3D12_HEAP_FLAG_NONE, checked_desc, state, clear, acceleration_structures(), state_.uma); const D3D12_HEAP_TYPE heap_type = heap->properties().Type; if (!why && (heap_type == D3D12_HEAP_TYPE_UPLOAD || heap_type == D3D12_HEAP_TYPE_READBACK) && @@ -7376,18 +7487,27 @@ class Device final } if (!out) return d3d12_trace::result(method, E_UNEXPECTED); const bool buffer = desc->Dimension == D3D12_RESOURCE_DIMENSION_BUFFER; - if (buffer && !heap->use_as_placed_resource(true)) { + if (heap->host_address() && !buffer) { + log_once("a placed texture in an existing heap (OpenExistingHeapFromAddress) is not supported yet; " + "dimension", + int(desc->Dimension)); + return d3d12_trace::result(method, E_NOTIMPL); + } + if (buffer && !heap->host_address() && !heap->use_as_placed_resource(true)) { log_once("placed buffer refused: heap uses a separate allocation for sparse tiles", 1); return d3d12_trace::result(method, E_NOTIMPL); } // Only buffers are addressable, as in D3D12: a placed texture keeps a null VA and its own Vulkan image, which // create_texture makes for 1D, 2D and 3D alike (arrays and mips included), as for a committed texture. - const VkDeviceSize placed_va = desc->Dimension == D3D12_RESOURCE_DIMENSION_BUFFER ? heap->offset() + heap_offset : 0; + const VkDeviceSize placed_va = + (buffer && !heap->host_address()) ? heap->offset() + heap_offset : 0; auto* resource = new Resource(state_, *desc, heap->properties(), heap->flags(), placed_va); resource->attach_device(identity()); HRESULT hr = E_NOTIMPL; if (buffer) { - hr = resource->create_placed_buffer(heap->arena_range()); + hr = heap->host_address() + ? resource->create_existing_heap_buffer(heap->arena_range(), heap->host_address(), heap_offset) + : resource->create_placed_buffer(heap->arena_range()); } else { hr = S_OK; const Format format = state_.texture_format(*desc); diff --git a/runtime/test/d3d12_existing_heap_placed_test.cpp b/runtime/test/d3d12_existing_heap_placed_test.cpp new file mode 100644 index 0000000000..6f1e52800f --- /dev/null +++ b/runtime/test/d3d12_existing_heap_placed_test.cpp @@ -0,0 +1,731 @@ +// Placed buffers in ID3D12Device3::OpenExistingHeapFromAddress existing heaps (RT-EXISTING-HEAP-PLACED): +// 1. CreatePlacedResource / CreatePlacedResource1 / CreatePlacedResource2 validation (including the +// SHARED_CROSS_ADAPTER -> ALLOW_CROSS_ADAPTER requirement and castable-list/layout checks) compared +// case-by-case with the live host D3D12 runtime and WARP; plus E_NOTIMPL for placed textures. +// 2. Non-zeroing preservation of pre-filled VirtualAlloc pages, Map() returning base + offset, Map() error checks, +// GetDesc().Flags preservation, GetHeapProperties parity (CUSTOM / WRITE_BACK and WRITE_COMBINE / L0, node masks +// 1, flags 0x421), and GetGPUVirtualAddress offset stride. +// 3. Bidirectional zero-copy CPU<->GPU coherence (CPU write -> GPU readback, GPU upload -> direct host RAM read, +// placed-to-placed copy inside the same heap) with buffer_device_address both disabled and enabled (GPU arena). +// 4. Overlapping placed buffer aliasing, releasing ID3D12Heap before GPU work on placed buffers, and 64-iteration +// alloc/open/place/copy/release/VirtualFree stress (specifically catching Intel WDDM asynchronous unpin bugs). +// 5. Forwarding through the Xbox-ABI device proxy (rt::d3d12_xs::create_device_proxy). +// Skips (77) when no usable Vulkan GPU or VK_EXT_external_memory_host is available. No shaders or game data. +#include "host_adapter.h" +#include "host_wine.h" +#include "vk_test_device.h" +#include "../shims/d3d12_com.h" +#include "../shims/d3d12_xs_device.h" + +#include + +#include +#include +#include +#include +#include +#include + +#define EXPECT(condition) \ + do { \ + if (!(condition)) { \ + std::fprintf(stderr, "%s line %d: %s\n", who, __LINE__, #condition); \ + return 1; \ + } \ + } while (0) + +#define EXPECT_HR(expr, want) \ + do { \ + const HRESULT got_ = (expr); \ + if (got_ != (want)) { \ + std::fprintf(stderr, "%s line %d: %s = 0x%08lX, expected 0x%08lX\n", who, __LINE__, \ + #expr, static_cast(got_), static_cast(want)); \ + return 1; \ + } \ + } while (0) + +namespace { + +template +struct Ref { + T* p = nullptr; + ~Ref() { reset(); } + void reset() { + if (p) p->Release(); + p = nullptr; + } + T* operator->() const { return p; } +}; + +struct VirtualRange { + void* ptr = nullptr; + SIZE_T size = 0; + + bool alloc(SIZE_T bytes, DWORD protect = PAGE_READWRITE) { + reset(); + ptr = VirtualAlloc(nullptr, bytes, MEM_RESERVE | MEM_COMMIT, protect); + size = ptr ? bytes : 0; + return ptr != nullptr; + } + ~VirtualRange() { reset(); } + void reset() { + if (ptr) VirtualFree(ptr, 0, MEM_RELEASE); + ptr = nullptr; + size = 0; + } + std::uint8_t* bytes() const { return static_cast(ptr); } +}; + +constexpr SIZE_T k64KiB = 0x10000; +constexpr SIZE_T k256KiB = 4 * k64KiB; + +D3D12_RESOURCE_DESC buffer_desc(UINT64 bytes, D3D12_RESOURCE_FLAGS flags = D3D12_RESOURCE_FLAG_NONE) { + D3D12_RESOURCE_DESC d{}; + d.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + d.Width = bytes; + d.Height = 1; + d.DepthOrArraySize = 1; + d.MipLevels = 1; + d.SampleDesc.Count = 1; + d.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + d.Flags = flags; + return d; +} + +D3D12_RESOURCE_DESC existing_buffer_desc(UINT64 bytes, D3D12_RESOURCE_FLAGS extra = D3D12_RESOURCE_FLAG_NONE) { + return buffer_desc(bytes, D3D12_RESOURCE_FLAG_ALLOW_CROSS_ADAPTER | extra); +} + +D3D12_RESOURCE_DESC1 buffer_desc1(UINT64 bytes, D3D12_RESOURCE_FLAGS flags = D3D12_RESOURCE_FLAG_NONE) { + D3D12_RESOURCE_DESC1 d{}; + d.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + d.Width = bytes; + d.Height = 1; + d.DepthOrArraySize = 1; + d.MipLevels = 1; + d.SampleDesc.Count = 1; + d.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + d.Flags = flags; + return d; +} + +D3D12_RESOURCE_DESC1 existing_buffer_desc1(UINT64 bytes, D3D12_RESOURCE_FLAGS extra = D3D12_RESOURCE_FLAG_NONE) { + return buffer_desc1(bytes, D3D12_RESOURCE_FLAG_ALLOW_CROSS_ADAPTER | extra); +} + +D3D12_RESOURCE_DESC texture_desc(UINT width, UINT height, D3D12_RESOURCE_FLAGS flags = D3D12_RESOURCE_FLAG_NONE) { + D3D12_RESOURCE_DESC d{}; + d.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + d.Width = width; + d.Height = height; + d.DepthOrArraySize = 1; + d.MipLevels = 1; + d.Format = DXGI_FORMAT_R8G8B8A8_UNORM; + d.SampleDesc.Count = 1; + d.Flags = flags; + return d; +} + +void fill_pattern(void* dst, std::size_t size, std::uint8_t seed) { + auto* out = static_cast(dst); + for (std::size_t i = 0; i < size; ++i) { + std::uint8_t v = static_cast((i * 131u + seed * 37u + 19u) & 0xFFu); + if (v == 0) v = 0xA5u; // strictly non-zero so uninitialized zero-fill is always caught + out[i] = v; + } +} + +bool pattern_matches(const void* ptr, std::size_t size, std::uint8_t seed, std::size_t* mismatch_at = nullptr) { + const auto* in = static_cast(ptr); + for (std::size_t i = 0; i < size; ++i) { + std::uint8_t want = static_cast((i * 131u + seed * 37u + 19u) & 0xFFu); + if (want == 0) want = 0xA5u; + if (in[i] != want) { + if (mismatch_at) *mismatch_at = i; + return false; + } + } + return true; +} + +// Reusable direct-queue copy helper for verifying CPU<->GPU coherence without repeating boilerplate. +struct CopyRunner { + ID3D12Device* device = nullptr; + Ref queue; + Ref allocator; + Ref list; + Ref fence; + HANDLE event = nullptr; + UINT64 fence_value = 0; + + ~CopyRunner() { + if (event) CloseHandle(event); + } + + int init(ID3D12Device* dev, const char* who) { + device = dev; + D3D12_COMMAND_QUEUE_DESC qd{D3D12_COMMAND_LIST_TYPE_DIRECT}; + EXPECT_HR(device->CreateCommandQueue(&qd, IID_PPV_ARGS(&queue.p)), S_OK); + EXPECT_HR(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator.p)), S_OK); + EXPECT_HR(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.p, nullptr, + IID_PPV_ARGS(&list.p)), + S_OK); + EXPECT_HR(list->Close(), S_OK); + EXPECT_HR(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence.p)), S_OK); + event = CreateEventW(nullptr, FALSE, FALSE, nullptr); + EXPECT(event != nullptr); + return 0; + } + + int copy_region(ID3D12Resource* dst, UINT64 dst_off, ID3D12Resource* src, UINT64 src_off, UINT64 bytes, + const char* who) { + EXPECT_HR(allocator->Reset(), S_OK); + EXPECT_HR(list->Reset(allocator.p, nullptr), S_OK); + list->CopyBufferRegion(dst, dst_off, src, src_off, bytes); + EXPECT_HR(list->Close(), S_OK); + ID3D12CommandList* lists[] = {list.p}; + queue->ExecuteCommandLists(1, lists); + const UINT64 target = ++fence_value; + EXPECT_HR(queue->Signal(fence.p, target), S_OK); + EXPECT_HR(fence->SetEventOnCompletion(target, event), S_OK); + EXPECT(WaitForSingleObject(event, 10000) == WAIT_OBJECT_0); + return 0; + } +}; + +struct ValidationCase { + const char* name; + HRESULT hr = S_OK; + bool has_heap_props = false; + D3D12_HEAP_PROPERTIES heap_props{}; + D3D12_HEAP_FLAGS heap_flags = D3D12_HEAP_FLAG_NONE; +}; + +struct ValidationSuite { + bool has_device8 = false; + bool has_device10 = false; + std::vector cases; +}; + +ValidationSuite run_validation_suite(ID3D12Device* device, const char* who) { + ValidationSuite suite; + Ref dev3; + if (FAILED(device->QueryInterface(IID_PPV_ARGS(&dev3.p))) || !dev3.p) return suite; + Ref dev8; + suite.has_device8 = SUCCEEDED(device->QueryInterface(IID_PPV_ARGS(&dev8.p))) && dev8.p != nullptr; + Ref dev10; + suite.has_device10 = SUCCEEDED(device->QueryInterface(IID_PPV_ARGS(&dev10.p))) && dev10.p != nullptr; + + VirtualRange range; + if (!range.alloc(k256KiB, PAGE_READWRITE)) return suite; + Ref heap; + if (FAILED(dev3->OpenExistingHeapFromAddress(range.ptr, IID_PPV_ARGS(&heap.p))) || !heap.p) return suite; + + const auto record = [&](const char* name, HRESULT hr, ID3D12Resource* res) { + ValidationCase c{name, hr}; + if (SUCCEEDED(hr) && res) { + if (SUCCEEDED(res->GetHeapProperties(&c.heap_props, &c.heap_flags))) c.has_heap_props = true; + res->Release(); + } + suite.cases.push_back(c); + }; + const auto place0 = [&](const char* name, UINT64 offset, const D3D12_RESOURCE_DESC& desc, + D3D12_RESOURCE_STATES state, const D3D12_CLEAR_VALUE* clear, bool provide_out = true) { + ID3D12Resource* res = nullptr; + const HRESULT hr = device->CreatePlacedResource( + heap.p, offset, &desc, state, clear, __uuidof(ID3D12Resource), + provide_out ? reinterpret_cast(&res) : nullptr); + record(name, hr, res); + }; + + place0("v0: buffer offset 0 COMMON", 0, existing_buffer_desc(k64KiB), D3D12_RESOURCE_STATE_COMMON, nullptr); + place0("v0: UAV buffer offset 64 KiB COPY_SOURCE", k64KiB, + existing_buffer_desc(k64KiB, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS), D3D12_RESOURCE_STATE_COPY_SOURCE, + nullptr); + place0("v0: buffer without ALLOW_CROSS_ADAPTER", 0, buffer_desc(k64KiB), D3D12_RESOURCE_STATE_COMMON, nullptr); + place0("v0: unaligned offset 4096", 4096, existing_buffer_desc(k64KiB), D3D12_RESOURCE_STATE_COMMON, nullptr); + place0("v0: out-of-bounds offset+width", 3 * k64KiB, existing_buffer_desc(2 * k64KiB), D3D12_RESOURCE_STATE_COMMON, + nullptr); + place0("v0: oversized width > heap", 0, existing_buffer_desc(2 * k256KiB), D3D12_RESOURCE_STATE_COMMON, nullptr); + place0("v0: zero-width buffer", 0, existing_buffer_desc(0), D3D12_RESOURCE_STATE_COMMON, nullptr); + + D3D12_CLEAR_VALUE cv{}; + cv.Format = DXGI_FORMAT_R8G8B8A8_UNORM; + place0("v0: non-null clear value on buffer", 0, existing_buffer_desc(k64KiB), D3D12_RESOURCE_STATE_COMMON, &cv); + place0("v0: valid args with null ppvResource", 0, existing_buffer_desc(k64KiB), D3D12_RESOURCE_STATE_COMMON, nullptr, + false); + + if (suite.has_device8) { + { + const D3D12_RESOURCE_DESC1 d1 = existing_buffer_desc1(k64KiB); + ID3D12Resource* res = nullptr; + const HRESULT hr = dev8->CreatePlacedResource1(heap.p, k64KiB, &d1, D3D12_RESOURCE_STATE_COMMON, nullptr, + IID_PPV_ARGS(&res)); + record("v1: buffer offset 64 KiB COMMON", hr, res); + } + { + const D3D12_RESOURCE_DESC1 d1_no = buffer_desc1(k64KiB); + ID3D12Resource* res = nullptr; + const HRESULT hr = dev8->CreatePlacedResource1(heap.p, k64KiB, &d1_no, D3D12_RESOURCE_STATE_COMMON, nullptr, + IID_PPV_ARGS(&res)); + record("v1: buffer without ALLOW_CROSS_ADAPTER", hr, res); + } + } + if (suite.has_device10) { + const D3D12_RESOURCE_DESC1 d1 = existing_buffer_desc1(k64KiB); + { + ID3D12Resource* res = nullptr; + const HRESULT hr = dev10->CreatePlacedResource2( + heap.p, 2 * k64KiB, &d1, D3D12_BARRIER_LAYOUT_UNDEFINED, nullptr, 0, nullptr, IID_PPV_ARGS(&res)); + record("v2: buffer offset 128 KiB UNDEFINED", hr, res); + } + { + const D3D12_RESOURCE_DESC1 d1_no = buffer_desc1(k64KiB); + ID3D12Resource* res = nullptr; + const HRESULT hr = dev10->CreatePlacedResource2( + heap.p, 2 * k64KiB, &d1_no, D3D12_BARRIER_LAYOUT_UNDEFINED, nullptr, 0, nullptr, IID_PPV_ARGS(&res)); + record("v2: buffer without ALLOW_CROSS_ADAPTER", hr, res); + } + { + ID3D12Resource* res = nullptr; + const HRESULT hr = dev10->CreatePlacedResource2( + heap.p, 2 * k64KiB, &d1, D3D12_BARRIER_LAYOUT_COMMON, nullptr, 0, nullptr, IID_PPV_ARGS(&res)); + record("v2: buffer with BARRIER_LAYOUT_COMMON", hr, res); + } + { + const DXGI_FORMAT cast[] = {DXGI_FORMAT_R8G8B8A8_UNORM}; + ID3D12Resource* res = nullptr; + const HRESULT hr = dev10->CreatePlacedResource2( + heap.p, 0, &d1, D3D12_BARRIER_LAYOUT_UNDEFINED, nullptr, 1, cast, IID_PPV_ARGS(&res)); + record("v2: buffer with castable format list", hr, res); + } + } + std::printf("%s: recorded %zu existing-heap CreatePlacedResource cases\n", who, suite.cases.size()); + return suite; +} + +int compare_validation_suites(const ValidationSuite& ours, const ValidationSuite& host, const char* host_name) { + const char* who = "parity"; + EXPECT(!ours.cases.empty()); + size_t compared = 0; + for (const auto& oc : ours.cases) { + const auto it = std::find_if(host.cases.begin(), host.cases.end(), + [&](const ValidationCase& hc) { return std::strcmp(hc.name, oc.name) == 0; }); + if (it == host.cases.end()) continue; + if (oc.hr != it->hr) { + std::fprintf(stderr, "vulkan vs %s: \"%s\" hr 0x%08lX != 0x%08lX\n", host_name, oc.name, + static_cast(oc.hr), static_cast(it->hr)); + return 1; + } + if (SUCCEEDED(oc.hr) && oc.has_heap_props && it->has_heap_props) { + const bool props_match = + oc.heap_props.Type == it->heap_props.Type && + oc.heap_props.CPUPageProperty == it->heap_props.CPUPageProperty && + oc.heap_props.MemoryPoolPreference == it->heap_props.MemoryPoolPreference && + oc.heap_props.CreationNodeMask == it->heap_props.CreationNodeMask && + oc.heap_props.VisibleNodeMask == it->heap_props.VisibleNodeMask && + oc.heap_flags == it->heap_flags; + if (!props_match) { + std::fprintf(stderr, + "vulkan vs %s: \"%s\" GetHeapProperties differs " + "(type=%d cpu=%d pool=%d flags=0x%x vs type=%d cpu=%d pool=%d flags=0x%x)\n", + host_name, oc.name, int(oc.heap_props.Type), int(oc.heap_props.CPUPageProperty), + int(oc.heap_props.MemoryPoolPreference), unsigned(oc.heap_flags), + int(it->heap_props.Type), int(it->heap_props.CPUPageProperty), + int(it->heap_props.MemoryPoolPreference), unsigned(it->heap_flags)); + return 1; + } + } + ++compared; + } + if (ours.has_device8 && host.has_device8 && ours.has_device10 && host.has_device10) { + EXPECT(compared == 15); + } else { + EXPECT(compared >= 9); + } + std::printf("vulkan vs %s: %zu existing-heap CreatePlacedResource & GetHeapProperties cases match\n", host_name, + compared); + return 0; +} + +int check_metadata_map_and_wc(ID3D12Device* device, const char* who) { + Ref dev3; + EXPECT_HR(device->QueryInterface(IID_PPV_ARGS(&dev3.p)), S_OK); + Ref dev8; + EXPECT_HR(device->QueryInterface(IID_PPV_ARGS(&dev8.p)), S_OK); + Ref dev10; + EXPECT_HR(device->QueryInterface(IID_PPV_ARGS(&dev10.p)), S_OK); + + { + VirtualRange range; + EXPECT(range.alloc(k256KiB, PAGE_READWRITE)); + fill_pattern(range.ptr, k256KiB, 0x31); + + Ref heap; + EXPECT_HR(dev3->OpenExistingHeapFromAddress(range.ptr, IID_PPV_ARGS(&heap.p)), S_OK); + + // Placed textures in existing heaps remain explicitly E_NOTIMPL for now. + { + const D3D12_RESOURCE_DESC td = texture_desc(64, 64, D3D12_RESOURCE_FLAG_ALLOW_CROSS_ADAPTER); + Ref tex; + EXPECT_HR(device->CreatePlacedResource(heap.p, 0, &td, D3D12_RESOURCE_STATE_COMMON, nullptr, + IID_PPV_ARGS(&tex.p)), + E_NOTIMPL); + EXPECT(tex.p == nullptr); + } + + Ref bufs[4]; + const D3D12_RESOURCE_DESC d0 = existing_buffer_desc(k64KiB); + const D3D12_RESOURCE_DESC1 d1 = existing_buffer_desc1(k64KiB); + EXPECT_HR(device->CreatePlacedResource(heap.p, 0 * k64KiB, &d0, D3D12_RESOURCE_STATE_COMMON, nullptr, + IID_PPV_ARGS(&bufs[0].p)), + S_OK); + EXPECT_HR(dev8->CreatePlacedResource1(heap.p, 1 * k64KiB, &d1, D3D12_RESOURCE_STATE_COMMON, nullptr, + IID_PPV_ARGS(&bufs[1].p)), + S_OK); + EXPECT_HR(dev10->CreatePlacedResource2(heap.p, 2 * k64KiB, &d1, D3D12_BARRIER_LAYOUT_UNDEFINED, nullptr, 0, + nullptr, IID_PPV_ARGS(&bufs[2].p)), + S_OK); + EXPECT_HR(device->CreatePlacedResource(heap.p, 3 * k64KiB, &d0, D3D12_RESOURCE_STATE_COMMON, nullptr, + IID_PPV_ARGS(&bufs[3].p)), + S_OK); + + D3D12_GPU_VIRTUAL_ADDRESS vas[4]{}; + for (size_t i = 0; i < 4; ++i) { + EXPECT((bufs[i]->GetDesc().Flags & D3D12_RESOURCE_FLAG_ALLOW_CROSS_ADAPTER) != 0); + + void* mapped = nullptr; + EXPECT_HR(bufs[i]->Map(0, nullptr, &mapped), S_OK); + EXPECT(mapped == range.bytes() + i * k64KiB); + EXPECT(std::memcmp(mapped, range.bytes() + i * k64KiB, k64KiB) == 0); + EXPECT(pattern_matches(mapped, k64KiB, 0x31)); + bufs[i]->Unmap(0, nullptr); + + // Map() invalid argument contracts. + EXPECT_HR(bufs[i]->Map(1, nullptr, &mapped), E_INVALIDARG); + const D3D12_RANGE oob{0, k64KiB + 1}; + EXPECT_HR(bufs[i]->Map(0, &oob, &mapped), E_INVALIDARG); + + D3D12_HEAP_PROPERTIES hp{}; + D3D12_HEAP_FLAGS hf = D3D12_HEAP_FLAG_NONE; + EXPECT_HR(bufs[i]->GetHeapProperties(&hp, &hf), S_OK); + EXPECT(hp.Type == D3D12_HEAP_TYPE_CUSTOM); + EXPECT(hp.CPUPageProperty == D3D12_CPU_PAGE_PROPERTY_WRITE_BACK); + EXPECT(hp.MemoryPoolPreference == D3D12_MEMORY_POOL_L0); + EXPECT(hp.CreationNodeMask == 1 && hp.VisibleNodeMask == 1); + EXPECT(hf == (D3D12_HEAP_FLAG_SHARED | D3D12_HEAP_FLAG_SHARED_CROSS_ADAPTER | + D3D12_HEAP_FLAG_ALLOW_SHADER_ATOMICS)); + + vas[i] = bufs[i]->GetGPUVirtualAddress(); + EXPECT(vas[i] != 0); + } + EXPECT(vas[1] - vas[0] == k64KiB); + EXPECT(vas[2] - vas[1] == k64KiB); + EXPECT(vas[3] - vas[2] == k64KiB); + } + + // Write-combine existing heap: metadata, Map() preservation, and clean device teardown. + { + VirtualRange wc_range; + EXPECT(wc_range.alloc(k64KiB, PAGE_READWRITE | PAGE_WRITECOMBINE)); + MEMORY_BASIC_INFORMATION mbi{}; + EXPECT(VirtualQuery(wc_range.ptr, &mbi, sizeof(mbi)) == sizeof(mbi)); + fill_pattern(wc_range.ptr, k64KiB, 0x57); + + Ref heap; + EXPECT_HR(dev3->OpenExistingHeapFromAddress(wc_range.ptr, IID_PPV_ARGS(&heap.p)), S_OK); + const D3D12_RESOURCE_DESC d = existing_buffer_desc(k64KiB); + Ref placed; + EXPECT_HR(device->CreatePlacedResource(heap.p, 0, &d, D3D12_RESOURCE_STATE_COMMON, nullptr, + IID_PPV_ARGS(&placed.p)), + S_OK); + void* mapped = nullptr; + EXPECT_HR(placed->Map(0, nullptr, &mapped), S_OK); + EXPECT(mapped == wc_range.ptr); + EXPECT(pattern_matches(mapped, k64KiB, 0x57)); + placed->Unmap(0, nullptr); + + D3D12_HEAP_PROPERTIES hp{}; + D3D12_HEAP_FLAGS hf = D3D12_HEAP_FLAG_NONE; + EXPECT_HR(placed->GetHeapProperties(&hp, &hf), S_OK); + const D3D12_CPU_PAGE_PROPERTY want_prop = (mbi.Protect & PAGE_WRITECOMBINE) + ? D3D12_CPU_PAGE_PROPERTY_WRITE_COMBINE + : D3D12_CPU_PAGE_PROPERTY_WRITE_BACK; + EXPECT(hp.Type == D3D12_HEAP_TYPE_CUSTOM && hp.CPUPageProperty == want_prop && + hp.MemoryPoolPreference == D3D12_MEMORY_POOL_L0); + } + + std::printf("%s: Map(), non-zeroing, GPU VA stride, GetHeapProperties, E_NOTIMPL texture & WC verified\n", who); + return 0; +} + +int check_coherence_aliasing_and_stress(ID3D12Device* device, const char* who) { + CopyRunner runner; + if (runner.init(device, who)) return 1; + + Ref dev3; + EXPECT_HR(device->QueryInterface(IID_PPV_ARGS(&dev3.p)), S_OK); + + const D3D12_RESOURCE_DESC d64_comm = buffer_desc(k64KiB); + const D3D12_RESOURCE_DESC d64 = existing_buffer_desc(k64KiB); + const D3D12_HEAP_PROPERTIES upload_hp{D3D12_HEAP_TYPE_UPLOAD}; + const D3D12_HEAP_PROPERTIES readback_hp{D3D12_HEAP_TYPE_READBACK}; + Ref upload, readback; + EXPECT_HR(device->CreateCommittedResource(&upload_hp, D3D12_HEAP_FLAG_NONE, &d64_comm, + D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, IID_PPV_ARGS(&upload.p)), + S_OK); + EXPECT_HR(device->CreateCommittedResource(&readback_hp, D3D12_HEAP_FLAG_NONE, &d64_comm, + D3D12_RESOURCE_STATE_COPY_DEST, nullptr, IID_PPV_ARGS(&readback.p)), + S_OK); + + // 3. Bidirectional CPU<->GPU coherence and placed-to-placed GPU copy within the same existing heap. + { + VirtualRange range; + EXPECT(range.alloc(2 * k64KiB, PAGE_READWRITE)); + Ref heap; + EXPECT_HR(dev3->OpenExistingHeapFromAddress(range.ptr, IID_PPV_ARGS(&heap.p)), S_OK); + Ref buf_a, buf_b; + EXPECT_HR(device->CreatePlacedResource(heap.p, 0, &d64, D3D12_RESOURCE_STATE_COMMON, nullptr, + IID_PPV_ARGS(&buf_a.p)), + S_OK); + EXPECT_HR(device->CreatePlacedResource(heap.p, k64KiB, &d64, D3D12_RESOURCE_STATE_COMMON, nullptr, + IID_PPV_ARGS(&buf_b.p)), + S_OK); + + // CPU -> GPU via raw host pointer after creation + fill_pattern(range.bytes(), k64KiB, 0x11); + if (runner.copy_region(readback.p, 0, buf_a.p, 0, k64KiB, who)) return 1; + void* rb_ptr = nullptr; + EXPECT_HR(readback->Map(0, nullptr, &rb_ptr), S_OK); + EXPECT(pattern_matches(rb_ptr, k64KiB, 0x11)); + readback->Unmap(0, nullptr); + + // GPU -> CPU direct read from raw host pages + void* up_ptr = nullptr; + EXPECT_HR(upload->Map(0, nullptr, &up_ptr), S_OK); + fill_pattern(up_ptr, k64KiB, 0x22); + upload->Unmap(0, nullptr); + if (runner.copy_region(buf_a.p, 0, upload.p, 0, k64KiB, who)) return 1; + EXPECT(pattern_matches(range.bytes(), k64KiB, 0x22)); + + // Placed -> placed inside the same existing heap, then read directly from host RAM + fill_pattern(range.bytes(), k64KiB, 0x33); + std::memset(range.bytes() + k64KiB, 0, k64KiB); + if (runner.copy_region(buf_b.p, 0, buf_a.p, 0, k64KiB, who)) return 1; + EXPECT(pattern_matches(range.bytes() + k64KiB, k64KiB, 0x33)); + } + + // 4a. Overlapping aliased placed buffers: [0..128 KiB) and [64 KiB..128 KiB). + { + VirtualRange range; + EXPECT(range.alloc(2 * k64KiB, PAGE_READWRITE)); + Ref heap; + EXPECT_HR(dev3->OpenExistingHeapFromAddress(range.ptr, IID_PPV_ARGS(&heap.p)), S_OK); + const D3D12_RESOURCE_DESC d128 = existing_buffer_desc(2 * k64KiB); + Ref wide, hi; + EXPECT_HR(device->CreatePlacedResource(heap.p, 0, &d128, D3D12_RESOURCE_STATE_COMMON, nullptr, + IID_PPV_ARGS(&wide.p)), + S_OK); + EXPECT_HR(device->CreatePlacedResource(heap.p, k64KiB, &d64, D3D12_RESOURCE_STATE_COMMON, nullptr, + IID_PPV_ARGS(&hi.p)), + S_OK); + + fill_pattern(range.bytes() + k64KiB, k64KiB, 0x44); + if (runner.copy_region(readback.p, 0, wide.p, k64KiB, k64KiB, who)) return 1; + void* rb_ptr = nullptr; + EXPECT_HR(readback->Map(0, nullptr, &rb_ptr), S_OK); + EXPECT(pattern_matches(rb_ptr, k64KiB, 0x44)); + readback->Unmap(0, nullptr); + + void* up_ptr = nullptr; + EXPECT_HR(upload->Map(0, nullptr, &up_ptr), S_OK); + fill_pattern(up_ptr, k64KiB, 0x55); + upload->Unmap(0, nullptr); + if (runner.copy_region(hi.p, 0, upload.p, 0, k64KiB, who)) return 1; + EXPECT(pattern_matches(range.bytes() + k64KiB, k64KiB, 0x55)); + } + + // 4b. Release ID3D12Heap BEFORE GPU copies on 4 placed buffers; placed resources keep imported VkDeviceMemory alive. + { + VirtualRange range; + EXPECT(range.alloc(k256KiB, PAGE_READWRITE)); + Ref bufs[4]; + { + Ref heap; + EXPECT_HR(dev3->OpenExistingHeapFromAddress(range.ptr, IID_PPV_ARGS(&heap.p)), S_OK); + for (size_t i = 0; i < 4; ++i) { + EXPECT_HR(device->CreatePlacedResource(heap.p, i * k64KiB, &d64, D3D12_RESOURCE_STATE_COMMON, nullptr, + IID_PPV_ARGS(&bufs[i].p)), + S_OK); + } + } // heap released here + for (size_t i = 0; i < 4; ++i) { + const std::uint8_t seed = static_cast(0x60 + i); + fill_pattern(range.bytes() + i * k64KiB, k64KiB, seed); + if (runner.copy_region(readback.p, 0, bufs[i].p, 0, k64KiB, who)) return 1; + void* rb_ptr = nullptr; + EXPECT_HR(readback->Map(0, nullptr, &rb_ptr), S_OK); + EXPECT(pattern_matches(rb_ptr, k64KiB, seed)); + readback->Unmap(0, nullptr); + } + void* up_ptr = nullptr; + EXPECT_HR(upload->Map(0, nullptr, &up_ptr), S_OK); + fill_pattern(up_ptr, k64KiB, 0x77); + upload->Unmap(0, nullptr); + if (runner.copy_region(bufs[3].p, 0, upload.p, 0, k64KiB, who)) return 1; + EXPECT(pattern_matches(range.bytes() + 3 * k64KiB, k64KiB, 0x77)); + } // buffers released here -> immediate VirtualFree on scope exit + + // 4c. 64-iteration alloc/open/place/copy/verify/release/VirtualFree stress loop. + for (int iter = 0; iter < 64; ++iter) { + VirtualRange range; + EXPECT(range.alloc(k64KiB, PAGE_READWRITE)); + const std::uint8_t seed = static_cast((iter * 7 + 3) & 0xFF); + fill_pattern(range.ptr, k64KiB, seed); + Ref heap; + EXPECT_HR(dev3->OpenExistingHeapFromAddress(range.ptr, IID_PPV_ARGS(&heap.p)), S_OK); + Ref placed; + EXPECT_HR(device->CreatePlacedResource(heap.p, 0, &d64, D3D12_RESOURCE_STATE_COMMON, nullptr, + IID_PPV_ARGS(&placed.p)), + S_OK); + heap.reset(); + if (runner.copy_region(readback.p, 0, placed.p, 0, k64KiB, who)) return 1; + void* rb_ptr = nullptr; + EXPECT_HR(readback->Map(0, nullptr, &rb_ptr), S_OK); + EXPECT(pattern_matches(rb_ptr, k64KiB, seed)); + readback->Unmap(0, nullptr); + placed.reset(); + range.reset(); // immediately frees pages while queue continues running + } + + std::printf("%s: bidirectional coherence, aliasing, heap lifetime & 64-iter stress passed\n", who); + return 0; +} + +int check_xbox_proxy(const vktest::Device& vk) { + const char* who = "xbox proxy"; + rt::d3d12::VulkanDeviceInfo info{}; + info.get_instance_proc = vk.instance_proc; + info.instance = vk.instance; + info.physical = vk.physical; + info.device = vk.device; + info.queue = vk.queue; + info.queue_family = vk.family; + info.host_pointer_alignment = vk.host_pointer_alignment; + info.buffer_device_address = vk.buffer_device_address; + + Ref real; + EXPECT_HR(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&real.p)), S_OK); + real->AddRef(); // create_device_proxy takes one reference on success + Ref proxy; + if (FAILED(rt::d3d12_xs::create_device_proxy(real.p, __uuidof(ID3D12Device), + reinterpret_cast(&proxy.p)))) { + real->Release(); + return 1; + } + + // Slot 48 on the Xbox proxy is CreateCommandQueueX rather than PC OpenExistingHeapFromAddress; open the heap on + // the underlying real device and exercise CreatePlacedResource (slot 29) + Map + GPU copy through the proxy. + Ref real3; + EXPECT_HR(real->QueryInterface(IID_PPV_ARGS(&real3.p)), S_OK); + VirtualRange range; + EXPECT(range.alloc(2 * k64KiB, PAGE_READWRITE)); + fill_pattern(range.ptr, 2 * k64KiB, 0x89); + + Ref heap; + EXPECT_HR(real3->OpenExistingHeapFromAddress(range.ptr, IID_PPV_ARGS(&heap.p)), S_OK); + const D3D12_RESOURCE_DESC d64 = existing_buffer_desc(k64KiB); + Ref placed; + EXPECT_HR(proxy->CreatePlacedResource(heap.p, k64KiB, &d64, D3D12_RESOURCE_STATE_COMMON, nullptr, + IID_PPV_ARGS(&placed.p)), + S_OK); + void* mapped = nullptr; + EXPECT_HR(placed->Map(0, nullptr, &mapped), S_OK); + EXPECT(mapped == range.bytes() + k64KiB); + EXPECT(pattern_matches(mapped, k64KiB, 0x89)); + placed->Unmap(0, nullptr); + + CopyRunner runner; + if (runner.init(proxy.p, who)) return 1; + const D3D12_RESOURCE_DESC d64_comm = buffer_desc(k64KiB); + const D3D12_HEAP_PROPERTIES readback_hp{D3D12_HEAP_TYPE_READBACK}; + Ref readback; + EXPECT_HR(proxy->CreateCommittedResource(&readback_hp, D3D12_HEAP_FLAG_NONE, &d64_comm, + D3D12_RESOURCE_STATE_COPY_DEST, nullptr, IID_PPV_ARGS(&readback.p)), + S_OK); + fill_pattern(range.bytes() + k64KiB, k64KiB, 0x9B); + if (runner.copy_region(readback.p, 0, placed.p, 0, k64KiB, who)) return 1; + void* rb_ptr = nullptr; + EXPECT_HR(readback->Map(0, nullptr, &rb_ptr), S_OK); + EXPECT(pattern_matches(rb_ptr, k64KiB, 0x9B)); + readback->Unmap(0, nullptr); + + std::printf("%s: CreatePlacedResource (slot 29) on existing heap + Map + GPU readback passed\n", who); + return 0; +} + +int run_vulkan_mode(bool enable_bda) { + const char* mode_name = enable_bda ? "vulkan (bda+arena)" : "vulkan (no-bda)"; + const char* who = mode_name; + vktest::Device vk; + vk.request_buffer_device_address = enable_bda; + const auto status = vk.initialize(); + if (status == vktest::DeviceStatus::unavailable) return 77; + if (status != vktest::DeviceStatus::ready) return 1; + if (!vk.host_pointer_alignment) { + std::printf("%s: skipped, no VK_EXT_external_memory_host\n", mode_name); + return 77; + } + + int failures = 0; + { + rt::d3d12::VulkanDeviceInfo info{}; + info.get_instance_proc = vk.instance_proc; + info.instance = vk.instance; + info.physical = vk.physical; + info.device = vk.device; + info.queue = vk.queue; + info.queue_family = vk.family; + info.host_pointer_alignment = vk.host_pointer_alignment; + info.buffer_device_address = vk.buffer_device_address; + + Ref ours; + EXPECT_HR(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&ours.p)), S_OK); + const ValidationSuite vulkan_suite = run_validation_suite(ours.p, mode_name); + failures += vulkan_suite.cases.empty() ? 1 : 0; + failures += check_metadata_map_and_wc(ours.p, mode_name); + failures += check_coherence_aliasing_and_stress(ours.p, mode_name); + + if (!enable_bda && !hostwine::host_is_wine()) { + Ref factory; + if (SUCCEEDED(CreateDXGIFactory1(IID_PPV_ARGS(&factory.p)))) { + for (const bool warp : {false, true}) { + Ref adapter; + Ref host; + std::string adapter_name; + if (!hostadapter::reference(factory.p, vk, warp, &adapter.p, adapter_name)) continue; + if (FAILED(D3D12CreateDevice(adapter.p, D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(&host.p)))) continue; + const std::string host_who = "host " + adapter_name; + const ValidationSuite host_suite = run_validation_suite(host.p, host_who.c_str()); + failures += compare_validation_suites(vulkan_suite, host_suite, host_who.c_str()); + } + } + } + if (enable_bda) failures += check_xbox_proxy(vk); + } + if (vk.validation_errors()) { + std::fprintf(stderr, "%s: %u validation errors\n", mode_name, vk.validation_errors()); + return 1; + } + return failures ? 1 : 0; +} + +} // namespace + +int main() { + for (const bool enable_bda : {false, true}) { + const int rc = run_vulkan_mode(enable_bda); + if (rc != 0) return rc; + } + return 0; +} diff --git a/runtime/test/d3d12_existing_heap_test.cpp b/runtime/test/d3d12_existing_heap_test.cpp index fd827f9a1a..a56631b30a 100644 --- a/runtime/test/d3d12_existing_heap_test.cpp +++ b/runtime/test/d3d12_existing_heap_test.cpp @@ -148,9 +148,9 @@ int check_import(ID3D12Device* device, bool supported) { EXPECT_HR(hr, S_OK); EXPECT(heap.p != nullptr); EXPECT(heap->GetDesc().SizeInBytes == size); - // The CPU still owns the pages: a write through them is what the GPU will read. + // The CPU still owns the pages: a write through them is preserved (not zeroed) and visible via Map(). + static_cast(memory)[0xFFFF] = 0x5a; static_cast(memory)[size - 1] = 0x5a; - // A placed resource in it is refused until the placed path addresses existing heaps. D3D12_RESOURCE_DESC buffer{}; buffer.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; buffer.Width = 0x10000; @@ -158,9 +158,21 @@ int check_import(ID3D12Device* device, bool supported) { buffer.SampleDesc.Count = 1; buffer.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; Ref placed; + // Existing heaps carry SHARED_CROSS_ADAPTER, so placed resources without ALLOW_CROSS_ADAPTER are refused. EXPECT_HR(device->CreatePlacedResource(heap.p, 0, &buffer, D3D12_RESOURCE_STATE_COMMON, nullptr, IID_PPV_ARGS(&placed.p)), - E_NOTIMPL); + E_INVALIDARG); + EXPECT(placed.p == nullptr); + buffer.Flags = D3D12_RESOURCE_FLAG_ALLOW_CROSS_ADAPTER; + EXPECT_HR(device->CreatePlacedResource(heap.p, 0, &buffer, D3D12_RESOURCE_STATE_COMMON, nullptr, + IID_PPV_ARGS(&placed.p)), + S_OK); + EXPECT(placed.p != nullptr); + void* mapped = nullptr; + EXPECT_HR(placed->Map(0, nullptr, &mapped), S_OK); + EXPECT(mapped == memory); + EXPECT(static_cast(mapped)[0xFFFF] == 0x5a); + placed->Unmap(0, nullptr); } } EXPECT(VirtualFree(memory, 0, MEM_RELEASE));