Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/d3d12_vulkan.md
Original file line number Diff line number Diff line change
Expand Up @@ -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). |
Expand Down
77 changes: 75 additions & 2 deletions runtime/shims/d3d12_vulkan_device.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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<leonida::ResourceId>(&source);
const auto target_id = reinterpret_cast<leonida::ResourceId>(&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<leonida::VulkanQueue>(*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
Expand Down Expand Up @@ -2070,10 +2139,12 @@ class Resource final
need_bda ? static_cast<const void*>(&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;
}
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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;
Expand Down
78 changes: 78 additions & 0 deletions runtime/test/d3d12_existing_heap_test.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,83 @@ int compare_cases(const std::vector<Case>& ours, const std::vector<Case>& 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<ID3D12Device3> 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<ID3D12Heap> 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<ID3D12Resource> 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<ID3D12Resource> 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<std::uint8_t>(i * 29u + 3u); };
for (UINT i = 0; i < 256; ++i) static_cast<std::uint8_t*>(mapped)[i] = pattern(i);
upload->Unmap(0, nullptr);
D3D12_COMMAND_QUEUE_DESC queue_desc{D3D12_COMMAND_LIST_TYPE_DIRECT};
Ref<ID3D12CommandQueue> queue;
Ref<ID3D12CommandAllocator> allocator;
Ref<ID3D12GraphicsCommandList> list;
Ref<ID3D12Fence> 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<std::uint8_t*>(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) {
Expand Down Expand Up @@ -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());
Expand Down