diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index 8548a5ac6c..e52cc50d80 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -1672,7 +1672,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 has device-local memory with optimal tiling: a range of a 64 MiB block that other textures share (`runtime/src/image_memory.h`, `VK-IMAGE-MEMORY-POOL`), or its own `VkDeviceMemory` when it is a render target, a depth buffer, a CPU-visible texture or larger than an eighth of a block, or when device-local memory has no room for another block. A range goes back to its block when the last submission that could use the image has completed. One reused from an earlier texture is zeroed before the next submission that runs shaders, as a committed resource reads as zero. Blocks hold only optimal-tiled images, so `bufferImageGranularity` does not apply. 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 memory (a range of a shared block or its own `VkDeviceMemory`, above); 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 memory (a range of a shared block or its own `VkDeviceMemory`, above); 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 9eca923131..5e4929e6a2 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -3965,6 +3965,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 // Slot-133 imports whose memory is allocated (create_host_buffer), for title_host_imports. std::atomic host_imports{0}; @@ -13883,6 +13884,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); + } + // A range of a device-local block for a texture, or null: the texture is too large to share one, or device-local // memory has no room for another block, and the caller makes its own allocation as it would without the blocks. std::unique_ptr allocate_image(const VkMemoryRequirements& requirements, @@ -14855,6 +14924,7 @@ class Resource final // and the geometry watch never make them read-only meanwhile (leonida::kernel_writes::hold). Taken first, // so no guard lands between the writability check above and the import. host_pin_ = leonida::kernel_writes::hold(base_address, std::size_t(bytes)); + std::uint32_t imported_type = 0; // Host-visible and coherent first, as the caller's pages are; then any type both the import and the // buffer take. for (const VkMemoryPropertyFlags want : @@ -14870,6 +14940,7 @@ class Resource final if (vk.vkAllocateMemory(device_.info.device, &allocate, nullptr, &memory_) == VK_SUCCESS) { memory_flags_ = device_.memory.memoryTypes[i].propertyFlags; device_.host_imports.fetch_add(1, std::memory_order_relaxed); + imported_type = i; } else { memory_ = VK_NULL_HANDLE; } @@ -14877,6 +14948,9 @@ class Resource final if (memory_) break; } if (!memory_) return decline(E_OUTOFMEMORY); + // After memory_mutex is released: settle_host_import allocates its scratch buffer through allocate(), + // which takes it. + device_.settle_host_import(memory_, imported_type); if (vk.vkBindBufferMemory(device_.info.device, buffer_, memory_, 0) != VK_SUCCESS) return decline(E_OUTOFMEMORY); if (need_bda && vk.vkGetBufferDeviceAddress) { VkBufferDeviceAddressInfo bda{VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO}; @@ -21792,6 +21866,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); @@ -28194,6 +28269,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 01011b3ef6..fce84df5c0 100644 --- a/runtime/test/d3d12_existing_heap_test.cpp +++ b/runtime/test/d3d12_existing_heap_test.cpp @@ -177,6 +177,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) { @@ -3949,6 +4026,7 @@ int main(int argc, char** argv) { 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());