From 2702cd33cbbe3d9eb655bb30f1436dbfb7fbe0e5 Mon Sep 17 00:00:00 2001 From: MalexAson <360820579+MalexAson@users.noreply.github.com> Date: Tue, 24 Nov 2026 21:55:02 +0100 Subject: [PATCH] d3d12: on Intel the GPU reads a fresh host import before it is handed out (RT-INTEL-IMPORT-SETTLE) Intel's Windows Vulkan driver (32.0.101.7092, Iris Xe) goes on working with a host import's pages after vkAllocateMemory has returned, and loses the device at the next vkQueueSubmit when the pages are freed before it is done, also when vkFreeMemory came first. d3d12_existing_heap opens existing heaps, releases them and frees their pages at once, so the device was already lost when the title-placed buffer's copy was submitted: "ExecuteCommandLists failed: unsupported", then a failed Signal, three times. On an Intel GPU, OpenExistingHeapFromAddress and a title-placed buffer (device slot 133) now copy four bytes out of the new import on the device's queue and wait for that (DeviceState::settle_host_import) before the object is handed out. Other vendors take the same path as before. d3d12_existing_heap gains check_pages_freed_at_once: three existing heaps and three placed buffers released with their pages freed at once, then a copy. On the Iris Xe it fails 10 of 10 times without the layer change and passes with it; an RTX 4060 passes either way. Co-Authored-By: Claude Fable 5.2 --- docs/d3d12_vulkan.md | 2 +- runtime/shims/d3d12_vulkan_device.cpp | 77 +++++++++++++++++++++- runtime/test/d3d12_existing_heap_test.cpp | 78 +++++++++++++++++++++++ 3 files changed, 154 insertions(+), 3 deletions(-) diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index 90828d409c..29e45fd7c2 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -1480,7 +1480,7 @@ The layer therefore owns the console VAs. It returns them from `ID3D12Resource:: | Address space | Two ranges. A **BDA arena** holds buffers, descriptor heaps and shader code; its device address is `heap_base`. A separate **image key range** supplies unique console VAs for images; those keys are never added to `heap_base`. The arena's `VkBuffer` is created with all buffer usages the game can bind (uniform, storage, vertex, index, indirect, transfer) plus `SHADER_DEVICE_ADDRESS`, and its memory with `VK_MEMORY_ALLOCATE_DEVICE_ADDRESS_BIT`. | | Buffers | A buffer resource is a range in the arena's single `VkBuffer`: offset = its console VA, size = the resource size. Buffer commands bind the arena buffer with that offset, so its device address is exactly `arena_bda + offset`; no per-resource `VkBuffer` object is needed. | | Images | Each image gets a unique console VA key and lives in its own `VkDeviceMemory` (or a suballocated device-local image heap) with optimal tiling. Shader image access goes through the T#/hash table, so nothing dereferences the key. Keeping images out of the arena avoids forcing optimal-tiled images into the arena's memory type and keeps the arena sized by buffers, not textures. | -| Heaps and placed resources | `CreateHeap` reserves the requested size in the arena, so a buffer placed at a 64 KiB-aligned offset is that offset into the arena and its console VA is the heap's place plus the offset. A placed texture (1D, 2D or 3D) gets its own `VkDeviceMemory`; one the title placed at its own address through the console's `CreatePlacedResourceX` (Xbox device slot 133) reports that title address from `GetGPUVirtualAddress`, as the console does — a title turns it into the CPU pointer it clears the texture through — while its pixels do not alias the title's pages yet. Any other texture answers a null VA, as on D3D12. Tiled (`64KB_UNDEFINED_SWIZZLE` and Xbox `0x101`) 2D/3D placed textures (D3D-191) and multisampled 2D placed textures (D3D-222) share that backing, answer `GetResourceAllocationInfo` and `GetResourceTiling`, and check heap/offset alignments. Reserved buffers can use heap tile mappings (section 4.2). | +| Heaps and placed resources | `CreateHeap` reserves the requested size in the arena, so a buffer placed at a 64 KiB-aligned offset is that offset into the arena and its console VA is the heap's place plus the offset. A placed texture (1D, 2D or 3D) gets its own `VkDeviceMemory`; one the title placed at its own address through the console's `CreatePlacedResourceX` (Xbox device slot 133) reports that title address from `GetGPUVirtualAddress`, as the console does — a title turns it into the CPU pointer it clears the texture through — while its pixels do not alias the title's pages yet. Any other texture answers a null VA, as on D3D12. Tiled (`64KB_UNDEFINED_SWIZZLE` and Xbox `0x101`) 2D/3D placed textures (D3D-191) and multisampled 2D placed textures (D3D-222) share that backing, answer `GetResourceAllocationInfo` and `GetResourceTiling`, and check heap/offset alignments. Reserved buffers can use heap tile mappings (section 4.2). An existing heap (`OpenExistingHeapFromAddress`) and a buffer the title placed on its own pages (slot 133) are those pages imported with `VK_EXT_external_memory_host`, and the import is freed when the object is released, so the title can free the pages right after. On an Intel GPU the GPU also reads a fresh import once before the object is handed out: four bytes copied out of it on the device's queue and waited for (`settle_host_import`, a driver workaround). Intel's Windows driver (32.0.101.7092, Iris Xe) goes on working with the pages after `vkAllocateMemory` has returned and loses the device at the next `vkQueueSubmit` when they are gone by then, also when `vkFreeMemory` came first. Measured with a raw Vulkan program: import, `vkFreeMemory`, `VirtualFree`, then a copy between two ordinary buffers loses the device in 10 of 10 runs for imports of 1, 16 and 64 MiB (5 of 10 for 64 KiB, 2 of 10 for 4 KiB, none from 128 MiB up), and in none of 20 when the pages are kept 1 ms longer or a copy out of the import has completed first. The RTX 4060 of the same machine (621.40) loses none, and the Iris Xe's own D3D12 driver takes `OpenExistingHeapFromAddress`, `Release`, `VirtualFree` and a submission in 10 of 10 runs. That first read costs what the first use of the import costs anyway, on both drivers: 0.1 to 0.5 ms for 64 KiB, 1.3 to 2.5 ms for 64 MiB. No device property reports the behaviour, so the vendor ID decides (`d3d12_existing_heap`, `check_pages_freed_at_once`). | | Descriptor heaps | Shader-visible CBV/SRV/UAV and sampler heaps are allocated in the low 4 GB of the arena. RTV/DSV heaps are host-side only. | | Shader code | Each FSSM blob is uploaded to the arena; its console VA is the code base. | | Upload/readback | `D3D12_HEAP_TYPE_UPLOAD`/`READBACK` resources are separate host-visible buffers outside the arena. Their console VAs are only used by copy APIs; if the game binds one as a vertex/index buffer or reads it in a shader, the layer biases the view/descriptor by `-heap_base` so the shader's addition lands on the host BDA (**ASSUMPTION**; **measured to fail for a V#**, see below). | diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index f8a5f656dc..9772338d54 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -641,6 +641,7 @@ struct DeviceState { PFN_vkTransitionImageLayoutEXT transition_image_layout = nullptr; // VK_EXT_external_memory_host; null unless info.host_pointer_alignment is set and the entry point loaded. PFN_vkGetMemoryHostPointerPropertiesEXT get_host_pointer_properties = nullptr; + bool settle_host_imports = false; // an Intel driver: settle_host_import reads every fresh import once // WriteToSubresource/ReadFromSubresource without host image copy: one staging copy at a time, submitted to // the device's VkQueue and waited for. Created on first use. @@ -1412,6 +1413,74 @@ struct DeviceState { } return VK_NULL_HANDLE; } + + // Intel's Windows driver goes on working with a host import's pages for a moment after vkAllocateMemory has + // returned. When they are gone before it is done, it loses the device at the next vkQueueSubmit, also when the + // import was already freed with vkFreeMemory. A title may do just that: open an existing heap or place a buffer + // on its pages, release it and free the pages, which the same GPU's D3D12 driver takes. So on that driver the + // GPU reads a fresh import once before its owner is handed out: four bytes copied out of it on the device's + // queue and waited for, after which the pages can go as soon as the import is freed. Measured with a raw + // Vulkan program on an Iris Xe (32.0.101.7092): import, vkFreeMemory, VirtualFree and a submission lose the + // device in 10 of 10 runs for 1, 16 and 64 MiB (5 of 10 for 64 KiB), in none with the copy in between; an + // RTX 4060 (621.40) loses none either way. No device property reports it, so the vendor ID decides. + // False, logged once, when the copy could not be made: the import is as usable as before. + bool settle_host_import(VkDeviceMemory imported, std::uint32_t memory_type) { + if (!settle_host_imports) return true; + auto& vk = context->vk; + constexpr VkDeviceSize bytes = 4; + leonida::ResourceBinding source{}, target{}; + source.size = target.size = bytes; + VkDeviceMemory target_memory = VK_NULL_HANDLE; + const auto release = [&](bool settled) { + if (source.buffer) vk.vkDestroyBuffer(info.device, source.buffer, nullptr); + if (target.buffer) vk.vkDestroyBuffer(info.device, target.buffer, nullptr); + if (target_memory) vk.vkFreeMemory(info.device, target_memory, nullptr); + if (!settled) + log_once("a host import could not be read before it was handed out; memory type", int(memory_type)); + return settled; + }; + VkExternalMemoryBufferCreateInfo external{VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_BUFFER_CREATE_INFO}; + external.handleTypes = VK_EXTERNAL_MEMORY_HANDLE_TYPE_HOST_ALLOCATION_BIT_EXT; + VkBufferCreateInfo buffer{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO, &external}; + buffer.size = bytes; + buffer.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT; + share(buffer); + VkMemoryRequirements requirements{}; + if (vk.vkCreateBuffer(info.device, &buffer, nullptr, &source.buffer) != VK_SUCCESS) return release(false); + vk.vkGetBufferMemoryRequirements(info.device, source.buffer, &requirements); + if (!(requirements.memoryTypeBits & (1u << memory_type)) || + vk.vkBindBufferMemory(info.device, source.buffer, imported, 0) != VK_SUCCESS) + return release(false); + buffer.pNext = nullptr; + buffer.usage = VK_BUFFER_USAGE_TRANSFER_DST_BIT; + if (vk.vkCreateBuffer(info.device, &buffer, nullptr, &target.buffer) != VK_SUCCESS) return release(false); + vk.vkGetBufferMemoryRequirements(info.device, target.buffer, &requirements); + target_memory = allocate(requirements, 0, 0); + if (!target_memory || vk.vkBindBufferMemory(info.device, target.buffer, target_memory, 0) != VK_SUCCESS) + return release(false); + // Resources only for the length of this call, as staged_copy's buffer is: the IDs are the bindings' addresses. + const auto source_id = reinterpret_cast(&source); + const auto target_id = reinterpret_cast(&target); + leonida::CommandList list; + if (!list.copy_buffer({target_id, 0, source_id, 0, bytes}) || !list.close()) return release(false); + context->add_resource(source_id, source); + context->add_resource(target_id, target); + leonida::ReplayResult result = leonida::ReplayResult::unsupported; + { + 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}; + result = staging_queue->execute(lists); + if (result == leonida::ReplayResult::success && !staging_queue->idle()) + result = leonida::ReplayResult::unsupported; + } + } + context->remove_resource(source_id); + context->remove_resource(target_id); + return release(result == leonida::ReplayResult::success); + } }; // The Vulkan format for a texture this layer can create, with the D24 fallback; VK_FORMAT_UNDEFINED, after a log @@ -2070,10 +2139,12 @@ class Resource final need_bda ? static_cast(&flags) : &import}; allocate.allocationSize = bytes; allocate.memoryTypeIndex = i; - if (vk.vkAllocateMemory(device_.info.device, &allocate, nullptr, &memory_) == VK_SUCCESS) + if (vk.vkAllocateMemory(device_.info.device, &allocate, nullptr, &memory_) == VK_SUCCESS) { memory_flags_ = device_.memory.memoryTypes[i].propertyFlags; - else + device_.settle_host_import(memory_, i); + } else { memory_ = VK_NULL_HANDLE; + } } if (memory_) break; } @@ -5114,6 +5185,7 @@ class Device final VkPhysicalDeviceProperties props{}; get_props(info.physical, &props); state_.pso_identity.vendor = props.vendorID; + state_.settle_host_imports = props.vendorID == 0x8086; // Intel: DeviceState::settle_host_import state_.pso_identity.device = props.deviceID; state_.pso_identity.driver = props.driverVersion; std::memcpy(state_.pso_identity.cache_uuid, props.pipelineCacheUUID, VK_UUID_SIZE); @@ -7127,6 +7199,7 @@ class Device final log_once("OpenExistingHeapFromAddress: importing the host range failed; size in KiB", int(size / 1024)); return d3d12_trace::result(method, E_OUTOFMEMORY); } + state_.settle_host_import(memory, memory_type); D3D12_HEAP_DESC desc{}; desc.SizeInBytes = size; desc.Properties.Type = D3D12_HEAP_TYPE_CUSTOM; diff --git a/runtime/test/d3d12_existing_heap_test.cpp b/runtime/test/d3d12_existing_heap_test.cpp index fd827f9a1a..77d8ba96f1 100644 --- a/runtime/test/d3d12_existing_heap_test.cpp +++ b/runtime/test/d3d12_existing_heap_test.cpp @@ -126,6 +126,83 @@ int compare_cases(const std::vector& ours, const std::vector& host, return failures; } +// A title may release an existing heap, or a buffer it placed on its own pages, and free the pages at once, with no +// submission in between: the device then takes the next submission, as the same GPU's D3D12 driver does. Intel's +// Vulkan driver lost its device there (Iris Xe, 32.0.101.7092: the pages have to outlast vkAllocateMemory by a +// moment, also when the import is already freed), 5 of 10 times for 64 KiB and 10 of 10 for 1 and 16 MiB, until the +// layer made the GPU read a fresh import before handing it out (DeviceState::settle_host_import). +int check_pages_freed_at_once(ID3D12Device* device) { + const char* who = "vulkan pages freed at once"; + Ref device3; + EXPECT(SUCCEEDED(device->QueryInterface(IID_PPV_ARGS(&device3.p)))); + D3D12_RESOURCE_DESC desc{}; + desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + desc.Height = desc.DepthOrArraySize = desc.MipLevels = 1; + desc.SampleDesc.Count = 1; + desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + for (const SIZE_T size : {SIZE_T(0x10000), SIZE_T(0x100000), SIZE_T(0x1000000)}) { + void* pages = VirtualAlloc(nullptr, size, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); + EXPECT(pages != nullptr); + { + Ref heap; + EXPECT_HR(device3->OpenExistingHeapFromAddress(pages, IID_PPV_ARGS(&heap.p)), S_OK); + } + EXPECT(VirtualFree(pages, 0, MEM_RELEASE)); + pages = VirtualAlloc(nullptr, size, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); + EXPECT(pages != nullptr); + { + desc.Width = size; + Ref buffer; + EXPECT_HR(rt::d3d12::create_buffer_at_host_address(device, pages, desc, 0xFFFFFFFFu, + IID_PPV_ARGS(&buffer.p)), + S_OK); + } + EXPECT(VirtualFree(pages, 0, MEM_RELEASE)); + } + desc.Width = 256; + D3D12_HEAP_PROPERTIES upload_heap{D3D12_HEAP_TYPE_UPLOAD}, readback_heap{D3D12_HEAP_TYPE_READBACK}; + Ref upload, readback; + EXPECT(SUCCEEDED(device->CreateCommittedResource(&upload_heap, D3D12_HEAP_FLAG_NONE, &desc, + D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, + IID_PPV_ARGS(&upload.p)))); + EXPECT(SUCCEEDED(device->CreateCommittedResource(&readback_heap, D3D12_HEAP_FLAG_NONE, &desc, + D3D12_RESOURCE_STATE_COPY_DEST, nullptr, + IID_PPV_ARGS(&readback.p)))); + void* mapped = nullptr; + EXPECT(SUCCEEDED(upload->Map(0, nullptr, &mapped))); + const auto pattern = [](UINT i) { return static_cast(i * 29u + 3u); }; + for (UINT i = 0; i < 256; ++i) static_cast(mapped)[i] = pattern(i); + upload->Unmap(0, nullptr); + D3D12_COMMAND_QUEUE_DESC queue_desc{D3D12_COMMAND_LIST_TYPE_DIRECT}; + Ref queue; + Ref allocator; + Ref list; + Ref fence; + EXPECT(SUCCEEDED(device->CreateCommandQueue(&queue_desc, IID_PPV_ARGS(&queue.p)))); + EXPECT(SUCCEEDED(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator.p)))); + EXPECT(SUCCEEDED(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.p, nullptr, + IID_PPV_ARGS(&list.p)))); + list->CopyBufferRegion(readback.p, 0, upload.p, 0, 256); + EXPECT(SUCCEEDED(list->Close())); + ID3D12CommandList* lists[] = {list.p}; + queue->ExecuteCommandLists(1, lists); + EXPECT(SUCCEEDED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence.p)))); + EXPECT(SUCCEEDED(queue->Signal(fence.p, 1))); + HANDLE done = CreateEventW(nullptr, FALSE, FALSE, nullptr); + EXPECT(SUCCEEDED(fence->SetEventOnCompletion(1, done))); + EXPECT(WaitForSingleObject(done, 10000) == WAIT_OBJECT_0); + CloseHandle(done); + EXPECT_HR(device->GetDeviceRemovedReason(), S_OK); + EXPECT(SUCCEEDED(readback->Map(0, nullptr, &mapped))); + bool same = true; + for (UINT i = 0; i < 256; ++i) same &= static_cast(mapped)[i] == pattern(i); + readback->Unmap(0, nullptr); + EXPECT(same); + std::printf("%s: the device took a copy after 3 heaps and 3 placed buffers were released and their pages freed\n", + who); + return 0; +} + // The heap is the caller's memory: CheckFeatureSupport says so, and the heap stays valid while it is held. // Without the extension the feature is unsupported and an accepted range is E_NOTIMPL. int check_import(ID3D12Device* device, bool supported) { @@ -368,6 +445,7 @@ int main() { if (vk.host_pointer_alignment) failures += compare_cases(vulkan_cases, host_cases, who.c_str()); } } + if (vk.host_pointer_alignment) failures += check_pages_freed_at_once(ours.p); } if (vk.validation_errors()) { std::fprintf(stderr, "%u validation errors\n", vk.validation_errors());