From 4b76715cf6cb70d569917299040418e1c24ce7ff Mon Sep 17 00:00:00 2001 From: Alex Collini Date: Mon, 23 Nov 2026 16:30:44 +0100 Subject: [PATCH 01/23] d3d12_xs: extend the device proxy table to 192 slots so slots past the PC vtable refuse with E_NOTIMPL The retail title calls device slot 133, past the 128-entry table; the call read an empty entry and jumped to 0. Every slot beyond the PC device's vtable now reaches the generic thunk. Mock test covers slot 133. Co-Authored-By: Claude Opus 5.5 --- runtime/shims/d3d12_xs_device.cpp | 5 ++++- runtime/test/xs_proxy_mock_test.cpp | 3 +++ 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/runtime/shims/d3d12_xs_device.cpp b/runtime/shims/d3d12_xs_device.cpp index 590f86bd73..22c09b331d 100644 --- a/runtime/shims/d3d12_xs_device.cpp +++ b/runtime/shims/d3d12_xs_device.cpp @@ -35,7 +35,10 @@ namespace rt::d3d12_xs { namespace { -constexpr unsigned kMaxSlots = 128; +// The retail title calls device slots well past ID3D12Device14 (slot 133 at least); every slot past the PC device's +// vtable goes through the generic thunk and is refused with E_NOTIMPL, so the table must outlast the highest one. +constexpr unsigned kMaxSlots = 192; +static_assert(kMaxSlots > 133, "the proxy table must cover the slots the retail title calls (up to 133)"); static_assert(kMaxSlots > 83, "the proxy table must cover ID3D12Device14 (83 slots)"); static_assert(sizeof(void*) == 8, "the Xbox-ABI proxy is x64-only"); static_assert(sizeof(D3D12_CPU_DESCRIPTOR_HANDLE) == 8, diff --git a/runtime/test/xs_proxy_mock_test.cpp b/runtime/test/xs_proxy_mock_test.cpp index f115b6655e..13f52fa511 100644 --- a/runtime/test/xs_proxy_mock_test.cpp +++ b/runtime/test/xs_proxy_mock_test.cpp @@ -342,6 +342,9 @@ int check_levels() { EXPECT(r75 == E_NOTIMPL && !queue1 && mock->calls[75] == 0); } + // 133: past every PC device vtable; the retail title calls it. Refused, not a jump through a missing entry. + EXPECT(hr_of(raw(device, 133)) == E_NOTIMPL && mock->calls[127] == 0); + Mock* const queue_mock = reinterpret_cast(real_queue); Mock* const fence_mock = reinterpret_cast(real_fence); EXPECT(release(queue) == 0 && release(fence) == 0); From 4eeb61b301595efecce43454b94a00f4290e2d11 Mon Sep 17 00:00:00 2001 From: thibaut Date: Mon, 23 Nov 2026 16:33:40 +0100 Subject: [PATCH 02/23] d3d12: OpenExistingHeapFromAddress backs a heap with the caller's memory (VK_EXT_external_memory_host) The retail executable opens the 64 KiB graphics region it has just committed with XMemVirtualAlloc through device slot 48 right after its first queue and fence; the layer answered E_NOTIMPL and the title asserted. The call now answers as the host runtime does on an RTX 4090 and WARP (six cases measured in d3d12_existing_heap_test): the base of a VirtualAlloc allocation committed read-write over its whole size opens a heap of that size, 64 KiB aligned, CUSTOM / WRITE_BACK / L0, SHARED | SHARED_CROSS_ADAPTER | ALLOW_SHADER_ATOMICS; an inner address, a partial or reserve-only commit and a read-only range are E_INVALIDARG. The backing is the range itself, imported with VK_EXT_external_memory_host, which the device and the test device enable when present. CheckFeatureSupport(EXISTING_HEAPS) follows the extension. Placed resources in such a heap are refused (E_NOTIMPL, logged) until the placed path addresses memory outside the arena. Co-Authored-By: Claude Opus 5.5 --- runtime/shims/d3d12_com.h | 4 + runtime/shims/d3d12_vulkan_device.cpp | 142 ++++++++++++++++++++-- runtime/test/d3d12_existing_heap_test.cpp | 123 ++++++++++++++++++- runtime/test/vk_test_device.h | 13 ++ 4 files changed, 273 insertions(+), 9 deletions(-) diff --git a/runtime/shims/d3d12_com.h b/runtime/shims/d3d12_com.h index f379754a98..422970acb1 100644 --- a/runtime/shims/d3d12_com.h +++ b/runtime/shims/d3d12_com.h @@ -183,6 +183,10 @@ struct VulkanDeviceInfo { // colours fall back to transparent black. bool custom_border_color = false; bool custom_border_color_without_format = false; + // VK_EXT_external_memory_host is enabled on `device` when this is non-zero (its + // minImportedHostPointerAlignment): OpenExistingHeapFromAddress backs a heap with the caller's own committed + // memory. Zero: existing heaps stay unsupported. + VkDeviceSize host_pointer_alignment = 0; }; // A Vulkan-backed ID3D12Device (PC ABI, up to ID3D12Device11) on caller-owned Vulkan objects, which must outlive diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index 5bde4b9568..59136671d5 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -633,6 +633,8 @@ struct DeviceState { PFN_vkCopyMemoryToImageEXT copy_memory_to_image = nullptr; PFN_vkCopyImageToMemoryEXT copy_image_to_memory = nullptr; 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; // 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. @@ -2575,6 +2577,20 @@ class Heap final } } + // An existing heap (OpenExistingHeapFromAddress): `memory` is the caller's committed range imported with + // VK_EXT_external_memory_host, and the heap owns that VkDeviceMemory, not the range. Not in the arena. + Heap(DeviceState& device, const D3D12_HEAP_DESC& desc, VkDeviceMemory memory, std::uint32_t memory_type, + const void* address) + : 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); + delete allocation; + }); + } + // As the host reports it (measured against the PC runtime, d3d12_vulkan_device_test compare_heap_descs): the // alignment the heap was placed with (64 KiB for an Alignment of 0) and the one node for a node mask of 0, as the // layer's resources, descriptor heaps and queues already answer. @@ -2587,6 +2603,8 @@ class Heap final } bool reserved() const { return bool(allocation_); } + // An existing heap: the caller's memory, not an arena range, so offset() is not a place in the arena. + const void* host_address() const { return host_address_; } VkDeviceSize offset() const { return allocation_->offset; } UINT64 bytes() const { return desc_.SizeInBytes; } UINT64 alignment() const { return desc_.Alignment ? desc_.Alignment : D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT; } @@ -2596,7 +2614,7 @@ class Heap final std::uint32_t memory_types) { const auto denied = image ? D3D12_HEAP_FLAG_DENY_NON_RT_DS_TEXTURES : D3D12_HEAP_FLAG_DENY_BUFFERS; if (device_.context.get() != &context || desc_.Properties.Type != D3D12_HEAP_TYPE_DEFAULT || - (desc_.Flags & denied)) return {}; + (desc_.Flags & denied) || host_address_) return {}; std::lock_guard lock(backing_mutex_); if (!image && device_.tiles_share_arena()) { if (tile_allocation_) return {}; @@ -2638,6 +2656,7 @@ class Heap final private: DeviceState& device_; D3D12_HEAP_DESC desc_; + const void* host_address_ = nullptr; std::shared_ptr allocation_; std::mutex backing_mutex_; std::shared_ptr tile_allocation_; @@ -4609,6 +4628,9 @@ class Device final } } if (info.host_image_copy) load_host_image_copy(get_device); + if (info.host_pointer_alignment) + state_.get_host_pointer_properties = reinterpret_cast( + get_device(info.device, "vkGetMemoryHostPointerPropertiesEXT")); // Depth <-> colour copies are staged through scratch buffers (vulkan_scratch.h), on every GPU. state_.context->enable_copy_scratch(get_device, [this](const VkMemoryRequirements& requirements) { return state_.allocate(requirements, 0, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT); @@ -6393,16 +6415,99 @@ class Device final // Heaps and placed resources (section 3.3). A heap reserves its size in the arena, so a buffer placed at a // 64 KiB-aligned offset is simply that offset into the arena, and its console VA is the heap's place plus it. - // Existing-memory heaps and lifetime trackers. CheckFeatureSupport reports EXISTING_HEAPS unsupported, so a call - // the host accepts stays E_NOTIMPL; the host refuses a null address, a file mapping that is not a handle and a - // null lifetime owner with E_INVALIDARG on WARP, NVIDIA and Intel (d3d12_existing_heap_test). Docs: + // Existing-memory heaps and lifetime trackers. The host refuses a null address, a file mapping that is not a + // handle and a null lifetime owner with E_INVALIDARG on WARP, NVIDIA and Intel (d3d12_existing_heap_test). Docs: // https://learn.microsoft.com/en-us/windows/win32/api/d3d12/nf-d3d12-id3d12device3-openexistingheapfromaddress - HRESULT STDMETHODCALLTYPE OpenExistingHeapFromAddress(const void* address, REFIID, void** out) override { + // + // OpenExistingHeapFromAddress answers as the host runtime does on an RTX 4090 and WARP (d3d12_existing_heap_test + // open_cases): the address must be the base of a VirtualAlloc allocation that is committed read-write over its + // whole size; an address inside it, a partly committed or reserved-only allocation and a read-only one are + // E_INVALIDARG. The heap is the allocation's size, 64 KiB aligned, CUSTOM / WRITE_BACK / L0, flags SHARED | + // SHARED_CROSS_ADAPTER | ALLOW_SHADER_ATOMICS. Its backing is that memory itself, imported with + // VK_EXT_external_memory_host, so the GPU sees the caller's writes. Without the extension, or when the range is + // not aligned to minImportedHostPointerAlignment or no memory type takes it, the call stays E_NOTIMPL, and + // CheckFeatureSupport(EXISTING_HEAPS) reports the extension's absence. The console title opens the 64 KiB + // graphics region it has just committed with XMemVirtualAlloc this way, right after its first queue and fence. + HRESULT STDMETHODCALLTYPE OpenExistingHeapFromAddress(const void* address, REFIID riid, void** out) override { constexpr auto method = "ID3D12Device3::OpenExistingHeapFromAddress"; if (out) *out = nullptr; if (!address || !out) return d3d12_trace::result(method, E_INVALIDARG); - log_once("OpenExistingHeapFromAddress (existing heaps are not supported)", 0); - return d3d12_trace::result(method, E_NOTIMPL); + SIZE_T size = 0; + if (!existing_allocation_size(address, size)) return d3d12_trace::result(method, E_INVALIDARG); + if (!state_.get_host_pointer_properties) { + log_once("OpenExistingHeapFromAddress (no VK_EXT_external_memory_host; existing heaps are not supported)", 0); + return d3d12_trace::result(method, E_NOTIMPL); + } + const VkDeviceSize alignment = state_.info.host_pointer_alignment; + if ((reinterpret_cast(address) | size) & (alignment - 1)) { + log_once("OpenExistingHeapFromAddress: range not aligned to minImportedHostPointerAlignment; alignment", + int(alignment)); + return d3d12_trace::result(method, E_NOTIMPL); + } + 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, + &host) != VK_SUCCESS || + !host.memoryTypeBits) { + log_once("OpenExistingHeapFromAddress: no memory type imports this host range", 0); + return d3d12_trace::result(method, E_NOTIMPL); + } + 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); + VkMemoryAllocateFlagsInfo flags{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_FLAGS_INFO, &import}; + flags.flags = VK_MEMORY_ALLOCATE_DEVICE_ADDRESS_BIT; + VkDeviceMemory memory = VK_NULL_HANDLE; + std::uint32_t memory_type = 0; + // Host-visible and coherent first, as the caller's pages are; then any type the driver offers. + for (const VkMemoryPropertyFlags want : + {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)) || + (state_.memory.memoryTypes[i].propertyFlags & want) != want) + continue; + VkMemoryAllocateInfo allocate{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO, &flags}; + allocate.allocationSize = size; + allocate.memoryTypeIndex = i; + if (state_.context->vk.vkAllocateMemory(state_.info.device, &allocate, nullptr, &memory) == + VK_SUCCESS) + memory_type = i; + else + memory = VK_NULL_HANDLE; + } + if (memory) break; + } + if (!memory) { + log_once("OpenExistingHeapFromAddress: importing the host range failed; size in KiB", int(size / 1024)); + return d3d12_trace::result(method, E_OUTOFMEMORY); + } + D3D12_HEAP_DESC desc{}; + desc.SizeInBytes = size; + desc.Properties.Type = D3D12_HEAP_TYPE_CUSTOM; + desc.Properties.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_WRITE_BACK; + desc.Properties.MemoryPoolPreference = D3D12_MEMORY_POOL_L0; + desc.Alignment = D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT; + desc.Flags = D3D12_HEAP_FLAG_SHARED | D3D12_HEAP_FLAG_SHARED_CROSS_ADAPTER | + D3D12_HEAP_FLAG_ALLOW_SHADER_ATOMICS; + auto* heap = new Heap(state_, desc, memory, memory_type, address); + heap->attach_device(identity()); + return d3d12_trace::result(method, hand_out(heap, riid, out)); + } + + // The size of the VirtualAlloc allocation `address` starts, when the whole of it is committed read-write: what + // the host runtime accepts. False for an address inside an allocation, a reserved or free page, or another + // protection anywhere in it. + static bool existing_allocation_size(const void* address, SIZE_T& size) { + MEMORY_BASIC_INFORMATION region{}; + if (!VirtualQuery(address, ®ion, sizeof(region)) || region.AllocationBase != address) return false; + size = 0; + const char* at = static_cast(address); + while (VirtualQuery(at + size, ®ion, sizeof(region)) && region.AllocationBase == address) { + if (region.State != MEM_COMMIT || region.Protect != PAGE_READWRITE) return false; + size += region.RegionSize; + } + return size != 0; } HRESULT STDMETHODCALLTYPE OpenExistingHeapFromFileMapping(HANDLE file_mapping, REFIID, void** out) override { @@ -6504,6 +6609,13 @@ 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); @@ -7385,7 +7497,8 @@ class Device final return d3d12_trace::result(method, S_OK); } case D3D12_FEATURE_EXISTING_HEAPS: - return write_supported_feature(method, data, size, FALSE); + return write_supported_feature( + method, data, size, state_.get_host_pointer_properties ? TRUE : FALSE); case D3D12_FEATURE_SERIALIZATION: { if (size != sizeof(D3D12_FEATURE_DATA_SERIALIZATION)) return d3d12_trace::result(method, E_INVALIDARG); auto* ser = static_cast(data); @@ -8977,6 +9090,18 @@ HRESULT create_vulkan_device_standalone(REFIID riid, void** out, QueueTestSettin "[rt] d3d12: no VK_EXT_custom_border_color; custom sampler border colours fall back to transparent black\n"); } + // Optional: VK_EXT_external_memory_host lets OpenExistingHeapFromAddress import the caller's committed memory as + // the heap's backing, so the GPU reads what the CPU writes there without a copy. + if (std::any_of(extensions.begin(), extensions.end(), [](const auto& e) { + return std::strcmp(e.extensionName, VK_EXT_EXTERNAL_MEMORY_HOST_EXTENSION_NAME) == 0; + })) { + VkPhysicalDeviceExternalMemoryHostPropertiesEXT host_memory{ + VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTERNAL_MEMORY_HOST_PROPERTIES_EXT}; + VkPhysicalDeviceProperties2 properties{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2, &host_memory}; + vkGetPhysicalDeviceProperties2(info.physical, &properties); + info.host_pointer_alignment = host_memory.minImportedHostPointerAlignment; + } + VkDeviceCreateInfo device_info{VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO, &enable12}; device_info.queueCreateInfoCount = std::uint32_t(queue_infos.size()); device_info.pQueueCreateInfos = queue_infos.data(); @@ -9011,6 +9136,7 @@ HRESULT create_vulkan_device_standalone(REFIID riid, void** out, QueueTestSettin info.presentation = has_swapchain && instance_has_surface; info.swapchain_colorspace = info.presentation && swapchain_colorspace_enabled; if (info.custom_border_color) device_extensions.push_back(custom_border_name); + if (info.host_pointer_alignment) device_extensions.push_back(VK_EXT_EXTERNAL_MEMORY_HOST_EXTENSION_NAME); device_info.enabledExtensionCount = std::uint32_t(device_extensions.size()); device_info.ppEnabledExtensionNames = device_extensions.empty() ? nullptr : device_extensions.data(); if (vkCreateDevice(info.physical, &device_info, nullptr, &owned.device) != VK_SUCCESS) diff --git a/runtime/test/d3d12_existing_heap_test.cpp b/runtime/test/d3d12_existing_heap_test.cpp index 6c036f277b..f6bcad02b3 100644 --- a/runtime/test/d3d12_existing_heap_test.cpp +++ b/runtime/test/d3d12_existing_heap_test.cpp @@ -1,7 +1,9 @@ // ID3D12Device3::OpenExistingHeapFromAddress, OpenExistingHeapFromFileMapping and ID3D12Device5::CreateLifetimeTracker // on arguments the host D3D12 runtime refuses (null address, a file mapping that is not a handle, a null owner), all // E_INVALIDARG on the RTX 4080 SUPER, Intel UHD 770 and WARP. Checked on the Vulkan-backed device and, when present, -// on the host devices too; a call the host accepts is not compared (this device reports EXISTING_HEAPS unsupported). +// on the host devices too. With VK_EXT_external_memory_host, OpenExistingHeapFromAddress on real host memory is +// compared case by case with the host devices (open_cases: RTX 4090 and WARP agree), and a heap is opened on a +// committed range; without it, the device reports EXISTING_HEAPS unsupported and answers an accepted range E_NOTIMPL. // No shaders or game data. // https://learn.microsoft.com/en-us/windows/win32/api/d3d12/nf-d3d12-id3d12device3-openexistingheapfromaddress #include "vk_test_device.h" @@ -9,6 +11,8 @@ #include "host_wine.h" #include "../shims/d3d12_com.h" #include +#include +#include #define EXPECT(condition) do { \ if (!(condition)) { std::fprintf(stderr, "%s line %d: %s\n", who, __LINE__, #condition); return 1; } \ @@ -49,6 +53,115 @@ int check(ID3D12Device* device, const char* who) { std::printf("%s: existing-heap and lifetime-tracker refusals match the host runtime\n", who); return 0; } + +// The calls the host accepts or refuses on real host memory, one result per case, for the comparison in main(). +struct Case { + const char* name; + HRESULT hr = S_OK; + D3D12_HEAP_DESC desc{}; +}; + +std::vector open_cases(ID3D12Device* device) { + std::vector out; + Ref device3; + if (FAILED(device->QueryInterface(IID_PPV_ARGS(&device3.p)))) return out; + auto run = [&](const char* name, const void* address) { + Case c{name}; + Ref heap; + c.hr = device3->OpenExistingHeapFromAddress(address, IID_PPV_ARGS(&heap.p)); + if (SUCCEEDED(c.hr) && heap.p) c.desc = heap->GetDesc(); + out.push_back(c); + }; + constexpr SIZE_T k64 = 0x10000; + // A whole 64 KiB committed read-write allocation, as the title's XMemVirtualAlloc gives it. + void* whole = VirtualAlloc(nullptr, k64, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); + run("64 KiB committed, at its base", whole); + run("64 KiB committed, 4 KiB in", static_cast(whole) + 0x1000); + // Two committed 64 KiB in one 192 KiB allocation whose last 64 KiB is only reserved. + char* partial = static_cast(VirtualAlloc(nullptr, 3 * k64, MEM_RESERVE, PAGE_READWRITE)); + VirtualAlloc(partial, 2 * k64, MEM_COMMIT, PAGE_READWRITE); + run("192 KiB reserved, first 128 KiB committed", partial); + void* reserved = VirtualAlloc(nullptr, k64, MEM_RESERVE, PAGE_READWRITE); + run("64 KiB reserved only", reserved); + void* readonly = VirtualAlloc(nullptr, k64, MEM_RESERVE | MEM_COMMIT, PAGE_READONLY); + run("64 KiB committed read-only", readonly); + void* big = VirtualAlloc(nullptr, 32 * k64, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); + run("2 MiB committed", big); + // The heap keeps no hold on the memory the test frees here; every heap above is already released. + for (void* p : {whole, static_cast(partial), reserved, readonly, big}) VirtualFree(p, 0, MEM_RELEASE); + return out; +} + +// Each case answers as the host does: the same HRESULT, and for an opened heap the same description. +int compare_cases(const std::vector& ours, const std::vector& host, const char* who) { + int failures = 0; + for (size_t i = 0; i < ours.size() && i < host.size(); ++i) { + const D3D12_HEAP_DESC& a = ours[i].desc; + const D3D12_HEAP_DESC& b = host[i].desc; + const bool same = ours[i].hr == host[i].hr && a.SizeInBytes == b.SizeInBytes && a.Alignment == b.Alignment && + a.Properties.Type == b.Properties.Type && + a.Properties.CPUPageProperty == b.Properties.CPUPageProperty && + a.Properties.MemoryPoolPreference == b.Properties.MemoryPoolPreference && a.Flags == b.Flags; + if (!same) { + std::fprintf(stderr, "vulkan vs %s: \"%s\" differs (hr 0x%08lX vs 0x%08lX)\n", who, ours[i].name, + static_cast(ours[i].hr), static_cast(host[i].hr)); + ++failures; + } + } + if (!failures) std::printf("vulkan vs %s: %zu OpenExistingHeapFromAddress cases match\n", who, ours.size()); + return failures; +} + +// 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) { + const char* who = "vulkan import"; + D3D12_FEATURE_DATA_EXISTING_HEAPS feature{}; + EXPECT(SUCCEEDED(device->CheckFeatureSupport(D3D12_FEATURE_EXISTING_HEAPS, &feature, sizeof(feature)))); + EXPECT(bool(feature.Supported) == supported); + Ref device3; + EXPECT(SUCCEEDED(device->QueryInterface(IID_PPV_ARGS(&device3.p)))); + constexpr SIZE_T size = 4 * 0x10000; + void* memory = VirtualAlloc(nullptr, size, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); + EXPECT(memory != nullptr); + { + Ref heap; + const HRESULT hr = device3->OpenExistingHeapFromAddress(memory, IID_PPV_ARGS(&heap.p)); + if (!supported) { + EXPECT_HR(hr, E_NOTIMPL); + EXPECT(heap.p == nullptr); + } else { + 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. + 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; + buffer.Height = buffer.DepthOrArraySize = buffer.MipLevels = 1; + buffer.SampleDesc.Count = 1; + buffer.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + Ref placed; + EXPECT_HR(device->CreatePlacedResource(heap.p, 0, &buffer, D3D12_RESOURCE_STATE_COMMON, nullptr, + IID_PPV_ARGS(&placed.p)), + E_NOTIMPL); + } + } + EXPECT(VirtualFree(memory, 0, MEM_RELEASE)); + std::printf("%s: existing heap %s\n", who, supported ? "opened on the caller's memory" : "unsupported, as reported"); + return 0; +} + +void print_cases(const std::vector& cases, const char* who) { + for (const Case& c : cases) + std::printf("%s: %-44s hr=0x%08lX size=%llu align=%llu type=%d cpu=%d pool=%d flags=0x%x\n", who, c.name, + static_cast(c.hr), static_cast(c.desc.SizeInBytes), + static_cast(c.desc.Alignment), int(c.desc.Properties.Type), + int(c.desc.Properties.CPUPageProperty), int(c.desc.Properties.MemoryPoolPreference), + unsigned(c.desc.Flags)); +} } // namespace int main() { @@ -66,8 +179,12 @@ int main() { info.device = vk.device; info.queue = vk.queue; info.queue_family = vk.family; + info.host_pointer_alignment = vk.host_pointer_alignment; if (FAILED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&ours.p)))) return 1; failures += check(ours.p, "vulkan"); + const std::vector vulkan_cases = open_cases(ours.p); + print_cases(vulkan_cases, "vulkan"); + failures += check_import(ours.p, vk.host_pointer_alignment != 0); Ref factory; if (!hostwine::host_is_wine() && SUCCEEDED(CreateDXGIFactory1(IID_PPV_ARGS(&factory.p)))) { for (const bool warp : {false, true}) { @@ -77,6 +194,10 @@ int main() { 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; failures += check(host.p, ("host " + adapter_name).c_str()); + const std::string who = "host " + adapter_name; + const std::vector host_cases = open_cases(host.p); + print_cases(host_cases, who.c_str()); + if (vk.host_pointer_alignment) failures += compare_cases(vulkan_cases, host_cases, who.c_str()); } } } diff --git a/runtime/test/vk_test_device.h b/runtime/test/vk_test_device.h index 114ca187f1..78cdfa25e1 100644 --- a/runtime/test/vk_test_device.h +++ b/runtime/test/vk_test_device.h @@ -121,6 +121,8 @@ class Device { leonida::SubgroupSizeCaps subgroup; bool custom_border_color = false; // VK_EXT_custom_border_color and customBorderColors enabled bool custom_border_color_without_format = false; + // VK_EXT_external_memory_host is enabled when non-zero: its minImportedHostPointerAlignment. + VkDeviceSize host_pointer_alignment = 0; Device() = default; Device(const Device&) = delete; @@ -532,6 +534,16 @@ class Device { *v13_.next() = &custom_border; } + // VK_EXT_external_memory_host where the device has it (OpenExistingHeapFromAddress). + for (const auto& extension : extensions) { + if (std::strcmp(extension.extensionName, VK_EXT_EXTERNAL_MEMORY_HOST_EXTENSION_NAME) != 0) continue; + VkPhysicalDeviceExternalMemoryHostPropertiesEXT host_memory{ + VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTERNAL_MEMORY_HOST_PROPERTIES_EXT}; + VkPhysicalDeviceProperties2 properties{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2, &host_memory}; + instance_fn("vkGetPhysicalDeviceProperties2")(physical, &properties); + host_pointer_alignment = host_memory.minImportedHostPointerAlignment; + } + VkDeviceCreateInfo device_info{VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO, &enable12}; device_info.queueCreateInfoCount = std::uint32_t(queue_infos.size()); device_info.pQueueCreateInfos = queue_infos.data(); @@ -547,6 +559,7 @@ class Device { if (vertex_attribute_divisor) device_extensions.push_back(divisor_extension); if (conditional_rendering) device_extensions.push_back(conditional_extension); if (host_image_copy) device_extensions.push_back(host_image_copy_name); + if (host_pointer_alignment) device_extensions.push_back(VK_EXT_EXTERNAL_MEMORY_HOST_EXTENSION_NAME); const char* swapchain = "VK_KHR_swapchain"; if (presentation) device_extensions.push_back(swapchain); #if defined(VK_KHR_swapchain_maintenance1) From 4d3d1e444831d654d3771442e12640b8dad9ed0b Mon Sep 17 00:00:00 2001 From: thibaut Date: Mon, 23 Nov 2026 16:36:33 +0100 Subject: [PATCH 03/23] d3d12: a write-combined range opens as a WRITE_COMBINE existing heap, an uncached one is refused Measured on the RTX 4090 and WARP: PAGE_READWRITE | PAGE_WRITECOMBINE is accepted with CPUPageProperty WRITE_COMBINE, PAGE_READWRITE | PAGE_NOCACHE is E_INVALIDARG. Two new cases in d3d12_existing_heap_test; 8 of 8 match both host devices. Co-Authored-By: Claude Opus 5.5 --- runtime/shims/d3d12_vulkan_device.cpp | 24 ++++++++++++++--------- runtime/test/d3d12_existing_heap_test.cpp | 8 +++++++- 2 files changed, 22 insertions(+), 10 deletions(-) diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index 59136671d5..5d392bf95f 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -6421,8 +6421,9 @@ class Device final // // OpenExistingHeapFromAddress answers as the host runtime does on an RTX 4090 and WARP (d3d12_existing_heap_test // open_cases): the address must be the base of a VirtualAlloc allocation that is committed read-write over its - // whole size; an address inside it, a partly committed or reserved-only allocation and a read-only one are - // E_INVALIDARG. The heap is the allocation's size, 64 KiB aligned, CUSTOM / WRITE_BACK / L0, flags SHARED | + // whole size; an address inside it, a partly committed or reserved-only allocation, a read-only one and an + // uncached one are E_INVALIDARG. The heap is the allocation's size, 64 KiB aligned, CUSTOM / L0 with WRITE_BACK + // (WRITE_COMBINE for a PAGE_WRITECOMBINE range), flags SHARED | // SHARED_CROSS_ADAPTER | ALLOW_SHADER_ATOMICS. Its backing is that memory itself, imported with // VK_EXT_external_memory_host, so the GPU sees the caller's writes. Without the extension, or when the range is // not aligned to minImportedHostPointerAlignment or no memory type takes it, the call stays E_NOTIMPL, and @@ -6433,7 +6434,8 @@ class Device final if (out) *out = nullptr; if (!address || !out) return d3d12_trace::result(method, E_INVALIDARG); SIZE_T size = 0; - if (!existing_allocation_size(address, size)) return d3d12_trace::result(method, E_INVALIDARG); + DWORD protect = 0; + if (!existing_allocation_size(address, size, protect)) return d3d12_trace::result(method, E_INVALIDARG); if (!state_.get_host_pointer_properties) { log_once("OpenExistingHeapFromAddress (no VK_EXT_external_memory_host; existing heaps are not supported)", 0); return d3d12_trace::result(method, E_NOTIMPL); @@ -6485,7 +6487,8 @@ class Device final D3D12_HEAP_DESC desc{}; desc.SizeInBytes = size; desc.Properties.Type = D3D12_HEAP_TYPE_CUSTOM; - desc.Properties.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_WRITE_BACK; + desc.Properties.CPUPageProperty = (protect & PAGE_WRITECOMBINE) ? D3D12_CPU_PAGE_PROPERTY_WRITE_COMBINE + : D3D12_CPU_PAGE_PROPERTY_WRITE_BACK; desc.Properties.MemoryPoolPreference = D3D12_MEMORY_POOL_L0; desc.Alignment = D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT; desc.Flags = D3D12_HEAP_FLAG_SHARED | D3D12_HEAP_FLAG_SHARED_CROSS_ADAPTER | @@ -6495,16 +6498,19 @@ class Device final return d3d12_trace::result(method, hand_out(heap, riid, out)); } - // The size of the VirtualAlloc allocation `address` starts, when the whole of it is committed read-write: what - // the host runtime accepts. False for an address inside an allocation, a reserved or free page, or another - // protection anywhere in it. - static bool existing_allocation_size(const void* address, SIZE_T& size) { + // The size of the VirtualAlloc allocation `address` starts, and its protection, when the whole of it is committed + // PAGE_READWRITE, or PAGE_READWRITE | PAGE_WRITECOMBINE: what the host runtime accepts (a write-combined range + // opens as a WRITE_COMBINE heap). False for an address inside an allocation, a reserved or free page, another + // protection (read-only, PAGE_NOCACHE), or two protections in one allocation. + static bool existing_allocation_size(const void* address, SIZE_T& size, DWORD& protect) { MEMORY_BASIC_INFORMATION region{}; if (!VirtualQuery(address, ®ion, sizeof(region)) || region.AllocationBase != address) return false; + protect = region.Protect; + if (protect != PAGE_READWRITE && protect != (PAGE_READWRITE | PAGE_WRITECOMBINE)) return false; size = 0; const char* at = static_cast(address); while (VirtualQuery(at + size, ®ion, sizeof(region)) && region.AllocationBase == address) { - if (region.State != MEM_COMMIT || region.Protect != PAGE_READWRITE) return false; + if (region.State != MEM_COMMIT || region.Protect != protect) return false; size += region.RegionSize; } return size != 0; diff --git a/runtime/test/d3d12_existing_heap_test.cpp b/runtime/test/d3d12_existing_heap_test.cpp index f6bcad02b3..f8ca1c6fe4 100644 --- a/runtime/test/d3d12_existing_heap_test.cpp +++ b/runtime/test/d3d12_existing_heap_test.cpp @@ -85,10 +85,16 @@ std::vector open_cases(ID3D12Device* device) { run("64 KiB reserved only", reserved); void* readonly = VirtualAlloc(nullptr, k64, MEM_RESERVE | MEM_COMMIT, PAGE_READONLY); run("64 KiB committed read-only", readonly); + // The console title's graphics regions keep PAGE_WRITECOMBINE (or PAGE_NOCACHE) once XMemVirtualAlloc drops + // the PAGE_GRAPHICS_* bits. + void* combined = VirtualAlloc(nullptr, k64, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE | PAGE_WRITECOMBINE); + run("64 KiB committed read-write write-combined", combined); + void* uncached = VirtualAlloc(nullptr, k64, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE | PAGE_NOCACHE); + run("64 KiB committed read-write uncached", uncached); void* big = VirtualAlloc(nullptr, 32 * k64, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); run("2 MiB committed", big); // The heap keeps no hold on the memory the test frees here; every heap above is already released. - for (void* p : {whole, static_cast(partial), reserved, readonly, big}) VirtualFree(p, 0, MEM_RELEASE); + for (void* p : {whole, static_cast(partial), reserved, readonly, combined, uncached, big}) VirtualFree(p, 0, MEM_RELEASE); return out; } From 9545ba80f89924fd730fdbec3e3870da8cb81ea2 Mon Sep 17 00:00:00 2001 From: thibaut Date: Mon, 23 Nov 2026 17:08:20 +0100 Subject: [PATCH 04/23] d3d12_xs: device slot 133 (CreatePlacedResourceX) makes a buffer on the title's own pages Xbox device slot 133 is (va, desc, state, clear, riid, out): the title places a buffer at the VA of a physical-page range it has just mapped (docs/retail_boot_chain.md 3.4, #6915). The proxy now hands it to a handler the Vulkan layer registers (set_placed_at_va_handler), which imports [va, va + width) with VK_EXT_external_memory_host and binds a VkBuffer to it: the CPU's writes there are the GPU's reads with no copy, and the resource's console VA is the title's VA, so views and immediate writes the title names by that VA resolve to it through the buffer VA index. The Xbox flag bits above the PC ones are dropped and the layout made ROW_MAJOR, as slot 76 does; textures are E_NOTIMPL, a misaligned VA E_INVALIDARG, and with no handler (a PC device) the slot refuses with E_NOTIMPL as #6953's table does. Not decided here: a shader that adds heap_base to the title's VA (its own V#s) does not reach these pages; that needs the single address space of docs/d3d12_vulkan.md 3.3. d3d12_existing_heap_test: on a VirtualAlloc range and on a view of a pagefile-backed section (the form xmem's physical pages take), the buffer's GPU VA is the address and a GPU copy to a READBACK buffer reads a pattern the CPU wrote after creation; Vulkan validation clean on an RTX 4090. Co-Authored-By: Claude Opus 5.5 --- runtime/shims/d3d12_com.h | 7 ++ runtime/shims/d3d12_vulkan_device.cpp | 114 ++++++++++++++++++++++ runtime/shims/d3d12_xs_device.cpp | 43 ++++++++ runtime/shims/d3d12_xs_device.h | 8 ++ runtime/test/d3d12_existing_heap_test.cpp | 82 ++++++++++++++++ 5 files changed, 254 insertions(+) diff --git a/runtime/shims/d3d12_com.h b/runtime/shims/d3d12_com.h index 422970acb1..cccc171110 100644 --- a/runtime/shims/d3d12_com.h +++ b/runtime/shims/d3d12_com.h @@ -218,6 +218,13 @@ VkBuffer vulkan_buffer(ID3D12Resource* resource); const VulkanDeviceInfo* vulkan_device_info(ID3D12Device* device); // True when `device` has VK_KHR_acceleration_structure + VK_KHR_ray_query enabled. bool device_supports_ray_tracing(ID3D12Device* device); + +// Xbox device slot 133 (the console's CreatePlacedResourceX): a buffer on the caller's own pages at `address`, which +// becomes its console VA. The pages are imported with VK_EXT_external_memory_host, so what the CPU writes there is +// what the GPU reads. A buffer description only; E_NOTIMPL on a device that is not the Vulkan layer, without the +// extension, or for a texture. +HRESULT create_buffer_at_host_address(ID3D12Device* device, void* address, const D3D12_RESOURCE_DESC& desc, + REFIID riid, void** out); // The VkAccelerationStructureKHR registered for `va` on `device`, or VK_NULL_HANDLE. For tests. VkAccelerationStructureKHR vulkan_acceleration_structure(ID3D12Device* device, D3D12_GPU_VIRTUAL_ADDRESS va); diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index 5d392bf95f..1b4dcda40c 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -1865,6 +1865,86 @@ class Resource final return S_OK; } + // A buffer on the caller's own pages (Xbox device slot 133, create_buffer_at_host_address): `address` is imported + // with VK_EXT_external_memory_host and the buffer bound to it at offset 0, so the CPU's writes there are the GPU's + // reads with no copy. Its console VA is `address` itself, the VA the title chose, so vertex, index and immediate + // writes the title names by that VA find this buffer (VulkanContext::buffer_at). A shader that adds heap_base to + // that VA does not reach it: the title's own V#s into these pages need the single address space of + // docs/d3d12_vulkan.md section 3.3, which this does not decide. The pages stay the caller's: nothing is zeroed. + HRESULT create_host_buffer(void* address) { + auto& vk = device_.context->vk; + const VkDeviceSize alignment = device_.info.host_pointer_alignment; + if (!device_.get_host_pointer_properties || !alignment) return E_NOTIMPL; + const auto start = reinterpret_cast(address); + if (!address || !desc_.Width || (start & (alignment - 1)) || desc_.Width > UINT64_MAX - alignment) + return E_INVALIDARG; + const VkDeviceSize bytes = (desc_.Width + alignment - 1) & ~(alignment - 1); + const bool need_bda = device_.info.buffer_device_address || device_.arena.buffer != VK_NULL_HANDLE; + 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); + if (vk.vkCreateBuffer(device_.info.device, &info, nullptr, &buffer_) != VK_SUCCESS) return E_OUTOFMEMORY; + VkMemoryRequirements requirements{}; + vk.vkGetBufferMemoryRequirements(device_.info.device, buffer_, &requirements); + VkMemoryHostPointerPropertiesEXT host{VK_STRUCTURE_TYPE_MEMORY_HOST_POINTER_PROPERTIES_EXT}; + if (device_.get_host_pointer_properties(device_.info.device, + VK_EXTERNAL_MEMORY_HANDLE_TYPE_HOST_ALLOCATION_BIT_EXT, address, + &host) != VK_SUCCESS) + return E_INVALIDARG; + const std::uint32_t types = host.memoryTypeBits & requirements.memoryTypeBits; + if (!types || bytes < requirements.size) return E_NOTIMPL; + VkImportMemoryHostPointerInfoEXT import{VK_STRUCTURE_TYPE_IMPORT_MEMORY_HOST_POINTER_INFO_EXT}; + import.handleType = VK_EXTERNAL_MEMORY_HANDLE_TYPE_HOST_ALLOCATION_BIT_EXT; + import.pHostPointer = address; + VkMemoryAllocateFlagsInfo flags{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_FLAGS_INFO, &import}; + flags.flags = VK_MEMORY_ALLOCATE_DEVICE_ADDRESS_BIT; + // 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 : + {VkMemoryPropertyFlags(VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT), + VkMemoryPropertyFlags(0)}) { + for (std::uint32_t i = 0; i < device_.memory.memoryTypeCount && !memory_; ++i) { + if (!(types & (1u << i)) || (device_.memory.memoryTypes[i].propertyFlags & want) != want) continue; + VkMemoryAllocateInfo allocate{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO, + need_bda ? static_cast(&flags) : &import}; + allocate.allocationSize = bytes; + allocate.memoryTypeIndex = i; + if (vk.vkAllocateMemory(device_.info.device, &allocate, nullptr, &memory_) == VK_SUCCESS) + memory_flags_ = device_.memory.memoryTypes[i].propertyFlags; + else + memory_ = VK_NULL_HANDLE; + } + if (memory_) break; + } + if (!memory_) return E_OUTOFMEMORY; + if (vk.vkBindBufferMemory(device_.info.device, buffer_, memory_, 0) != VK_SUCCESS) return E_OUTOFMEMORY; + mapped_ = address; + va_ = start; + 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_; + } + device_.log_va("title-placed buffer", va_, desc_.Width); + leonida::ResourceBinding binding{}; + binding.buffer = buffer_; + binding.size = desc_.Width; + binding.host = static_cast(address); + binding.host_readable = true; + binding.va = va_; + device_.context->add_resource(id(), binding); + return S_OK; + } + HRESULT create_sparse_buffer() { constexpr std::uint64_t tile_bytes = leonida::tile_size_in_bytes; if (!desc_.Width || desc_.Width > UINT64_MAX - tile_bytes || @@ -6516,6 +6596,29 @@ class Device final return size != 0; } + // create_buffer_at_host_address (Xbox device slot 133). The heap the resource reports is CUSTOM / WRITE_BACK / L0, + // what OpenExistingHeapFromAddress gives the same pages, since the CPU keeps writing them. + HRESULT create_at_host_address(void* address, const D3D12_RESOURCE_DESC& desc, REFIID riid, void** out) { + constexpr auto method = "Xbox CreatePlacedResourceX (device slot 133)"; + if (desc.Dimension != D3D12_RESOURCE_DIMENSION_BUFFER) { + log_once("a title-placed texture (device slot 133) is not supported yet; dimension", int(desc.Dimension)); + return d3d12_trace::result(method, E_NOTIMPL); + } + D3D12_HEAP_PROPERTIES heap{}; + heap.Type = D3D12_HEAP_TYPE_CUSTOM; + heap.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_WRITE_BACK; + heap.MemoryPoolPreference = D3D12_MEMORY_POOL_L0; + auto* resource = new Resource(state_, desc, heap, D3D12_HEAP_FLAG_NONE); + resource->attach_device(identity()); + const HRESULT hr = resource->create_host_buffer(address); + if (FAILED(hr)) { + log_once("a title-placed buffer (device slot 133) could not import its pages; HRESULT", int(hr)); + resource->Release(); + return d3d12_trace::result(method, hr); + } + return d3d12_trace::result(method, hand_out(resource, riid, out)); + } + HRESULT STDMETHODCALLTYPE OpenExistingHeapFromFileMapping(HANDLE file_mapping, REFIID, void** out) override { constexpr auto method = "ID3D12Device3::OpenExistingHeapFromFileMapping"; if (out) *out = nullptr; @@ -8070,6 +8173,7 @@ class Device final HRESULT create_vulkan_device(const VulkanDeviceInfo& info, REFIID riid, void** out) { if (!out) return E_POINTER; *out = nullptr; + rt::d3d12_xs::set_placed_at_va_handler(&create_buffer_at_host_address); auto* device = new Device(info); if (!device->ok()) { device->Release(); @@ -8156,6 +8260,16 @@ const VulkanDeviceInfo* vulkan_device_info(ID3D12Device* device) { return nullptr; } +HRESULT create_buffer_at_host_address(ID3D12Device* device, void* address, const D3D12_RESOURCE_DESC& desc, + REFIID riid, void** out) { + if (out) *out = nullptr; + if (!device || !out) return E_POINTER; + ID3D12Device* real = rt::d3d12_xs::device_proxy_real_device(device); + auto* d = Device::from(real ? real : device); + if (!d) return E_NOTIMPL; + return d->create_at_host_address(address, desc, riid, out); +} + bool device_supports_ray_tracing(ID3D12Device* device) { if (!device) return false; ID3D12Device* real = rt::d3d12_xs::device_proxy_real_device(device); diff --git a/runtime/shims/d3d12_xs_device.cpp b/runtime/shims/d3d12_xs_device.cpp index 22c09b331d..7a815e0533 100644 --- a/runtime/shims/d3d12_xs_device.cpp +++ b/runtime/shims/d3d12_xs_device.cpp @@ -129,6 +129,7 @@ const char* slot_name(unsigned slot) { case 67: return "Xbox DeserializeComputePipelineStateX"; case 75: return "CreateCommandQueue1 -> queue proxy"; case 76: return "Xbox resource creation"; + case 133: return "Xbox CreatePlacedResourceX (a buffer on the title's pages)"; default: return "forwarded"; } } @@ -1321,6 +1322,39 @@ HRESULT proxy_create_resource(DeviceProxy* self, const D3D12_HEAP_PROPERTIES* he *riid, out); } +// Device slot 133 is the console's CreatePlacedResourceX: (va, desc, state, clear, riid, out), measured on the retail +// executable (docs/retail_boot_chain.md, section 3.4). `va` is the start of a physical-page range the title has just +// mapped, `desc` a 56-byte description with Xbox bits above the PC resource flags and an Xbox layout word, and +// `state` is 0xFFFFFFFF, which is no PC state. The resource is a buffer on those pages, made by the handler the +// device behind the proxy registered (set_placed_at_va_handler), with the PC flags kept and the layout made +// ROW_MAJOR, as slot 76 does. +std::atomic g_placed_at_va{nullptr}; + +HRESULT proxy_create_placed_resource_x(DeviceProxy* self, void* va, const D3D12_RESOURCE_DESC* xbox_desc, + std::uint32_t state, const IID* riid, void** out) { + note_slot(133); + if (out) *out = nullptr; + // Without a handler (a PC device behind the proxy, or none registered) the slot refuses like any slot past the + // PC vtable, whatever its arguments. + const PlacedAtVaHandler handler = g_placed_at_va.load(std::memory_order_acquire); + if (!handler) return E_NOTIMPL; + if (!out || !xbox_desc || !riid) return E_POINTER; + constexpr auto kPcResourceFlags = static_cast(0x7ff); + D3D12_RESOURCE_DESC pc_desc = *xbox_desc; + const auto xbox_flags = static_cast(pc_desc.Flags); + pc_desc.Flags = static_cast(xbox_flags & kPcResourceFlags); + if (pc_desc.Dimension == D3D12_RESOURCE_DIMENSION_BUFFER) pc_desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + static std::atomic logged{false}; + if (!logged.exchange(true, std::memory_order_relaxed)) { + std::fprintf(stderr, + "[rt] d3d12_xs: slot 133 CreatePlacedResourceX: va=%p dimension=%d width=%llu xbox flags=0x%x " + "state=0x%x -> a buffer on the title's pages\n", + va, static_cast(pc_desc.Dimension), static_cast(pc_desc.Width), + xbox_flags, state); + } + return handler(self->real, va, pc_desc, *riid, out); +} + template std::uint64_t WINAPI proxy_slot(DeviceProxy* self, std::uint64_t a1, std::uint64_t a2, std::uint64_t a3, std::uint64_t a4, std::uint64_t a5, std::uint64_t a6, std::uint64_t a7, @@ -1362,6 +1396,11 @@ std::uint64_t WINAPI proxy_slot(DeviceProxy* self, std::uint64_t a1, std::uint64 return hr_to_u64(proxy_create_compute_pipeline_from_native_code( self, reinterpret_cast(a1), reinterpret_cast(a2), reinterpret_cast(a3))); + } else if constexpr (Slot == 133) { + return hr_to_u64(proxy_create_placed_resource_x(self, reinterpret_cast(a1), + reinterpret_cast(a2), + static_cast(a3), reinterpret_cast(a5), + reinterpret_cast(a6))); } else if constexpr (Slot == 76) { return hr_to_u64(proxy_create_resource( self, reinterpret_cast(a1), @@ -1512,6 +1551,10 @@ unsigned device_proxy_slot_count(const void* device) { return static_cast(device)->slot_count; } +void set_placed_at_va_handler(PlacedAtVaHandler handler) { + g_placed_at_va.store(handler, std::memory_order_release); +} + ID3D12Device* device_proxy_real_device(const void* device) { if (!is_device_proxy(device)) return nullptr; return static_cast(device)->real; diff --git a/runtime/shims/d3d12_xs_device.h b/runtime/shims/d3d12_xs_device.h index 8ff508e6fd..b15f69dc83 100644 --- a/runtime/shims/d3d12_xs_device.h +++ b/runtime/shims/d3d12_xs_device.h @@ -77,6 +77,14 @@ unsigned device_proxy_slot_count(const void* device); // The PC device behind a proxy. Null when `device` is not a proxy. ID3D12Device* device_proxy_real_device(const void* device); +// Device slot 133 (the console's CreatePlacedResourceX) makes a buffer on the title's pages at `va`. The proxy does +// not create it itself: the device behind it does, through this handler, which the Vulkan layer registers +// (rt::d3d12::create_buffer_at_host_address). With none registered, or a PC device behind the proxy, the slot +// answers E_NOTIMPL. +using PlacedAtVaHandler = HRESULT (*)(ID3D12Device* real, void* va, const D3D12_RESOURCE_DESC& desc, REFIID riid, + void** out); +void set_placed_at_va_handler(PlacedAtVaHandler handler); + // True for slots the proxy handles itself rather than forwarding verbatim: IUnknown (0-2), 8 and 75 (queue // proxies), 9 (allocator proxies), 14, 31/34/35/45/46/50 (proxies unwrapped), 32 and 36 (fence proxies), 62, 67 // and 76. Slot 10 is intentionally false: the measured 9/10 handle conversion is on the heap proxy, and device diff --git a/runtime/test/d3d12_existing_heap_test.cpp b/runtime/test/d3d12_existing_heap_test.cpp index f8ca1c6fe4..73f2f13566 100644 --- a/runtime/test/d3d12_existing_heap_test.cpp +++ b/runtime/test/d3d12_existing_heap_test.cpp @@ -11,6 +11,7 @@ #include "host_wine.h" #include "../shims/d3d12_com.h" #include +#include #include #include @@ -160,6 +161,86 @@ int check_import(ID3D12Device* device, bool supported) { return 0; } +// Xbox device slot 133's backend (rt::d3d12::create_buffer_at_host_address): a buffer on the caller's own pages. +// Its GPU VA is the address itself, and what the CPU writes there is what a GPU copy reads, with no upload: the +// pattern is written after the buffer exists and read back through a READBACK buffer. Checked on a VirtualAlloc range +// and on a view of a pagefile-backed section, the form xmem's physical pages are mapped in. A texture is E_NOTIMPL +// and an address off the import alignment E_INVALIDARG. +int check_title_placed(ID3D12Device* device, const char* kind, void* pages, UINT64 size) { + const char* who = "vulkan slot-133 buffer"; + D3D12_RESOURCE_DESC desc{}; + desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + desc.Width = size; + desc.Height = desc.DepthOrArraySize = desc.MipLevels = 1; + desc.SampleDesc.Count = 1; + desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + Ref buffer; + EXPECT_HR(rt::d3d12::create_buffer_at_host_address(device, pages, desc, IID_PPV_ARGS(&buffer.p)), S_OK); + EXPECT(buffer->GetGPUVirtualAddress() == reinterpret_cast(pages)); + auto* bytes = static_cast(pages); + for (UINT64 i = 0; i < size; ++i) bytes[i] = static_cast(i * 131u + 7u); + + D3D12_HEAP_PROPERTIES readback_heap{D3D12_HEAP_TYPE_READBACK}; + Ref readback; + EXPECT(SUCCEEDED(device->CreateCommittedResource(&readback_heap, D3D12_HEAP_FLAG_NONE, &desc, + D3D12_RESOURCE_STATE_COPY_DEST, nullptr, + IID_PPV_ARGS(&readback.p)))); + 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, buffer.p, 0, size); + 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); + void* mapped = nullptr; + EXPECT(SUCCEEDED(readback->Map(0, nullptr, &mapped))); + const bool same = std::memcmp(mapped, pages, static_cast(size)) == 0; + readback->Unmap(0, nullptr); + EXPECT(same); + + D3D12_RESOURCE_DESC texture = desc; + texture.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + texture.Width = texture.Height = 64; + texture.Format = DXGI_FORMAT_R8G8B8A8_UNORM; + texture.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN; + Ref refused; + EXPECT_HR(rt::d3d12::create_buffer_at_host_address(device, pages, texture, IID_PPV_ARGS(&refused.p)), E_NOTIMPL); + EXPECT_HR(rt::d3d12::create_buffer_at_host_address(device, bytes + 1, desc, IID_PPV_ARGS(&refused.p)), + E_INVALIDARG); + EXPECT(refused.p == nullptr); + std::printf("%s: %s, %llu bytes: GPU VA is the address, a GPU copy reads the CPU's writes\n", who, kind, + static_cast(size)); + return 0; +} + +int check_title_placed_all(ID3D12Device* device) { + constexpr SIZE_T size = 4 * 0x10000; + int failures = 0; + void* pages = VirtualAlloc(nullptr, size, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); + if (!pages) return 1; + failures += check_title_placed(device, "VirtualAlloc range", pages, size); + VirtualFree(pages, 0, MEM_RELEASE); + HANDLE section = CreateFileMappingW(INVALID_HANDLE_VALUE, nullptr, PAGE_READWRITE, 0, DWORD(size), nullptr); + void* view = section ? MapViewOfFile(section, FILE_MAP_ALL_ACCESS, 0, 0, size) : nullptr; + if (!view) return failures + 1; + failures += check_title_placed(device, "section view", view, size); + UnmapViewOfFile(view); + CloseHandle(section); + return failures; +} + void print_cases(const std::vector& cases, const char* who) { for (const Case& c : cases) std::printf("%s: %-44s hr=0x%08lX size=%llu align=%llu type=%d cpu=%d pool=%d flags=0x%x\n", who, c.name, @@ -191,6 +272,7 @@ int main() { const std::vector vulkan_cases = open_cases(ours.p); print_cases(vulkan_cases, "vulkan"); failures += check_import(ours.p, vk.host_pointer_alignment != 0); + if (vk.host_pointer_alignment) failures += check_title_placed_all(ours.p); Ref factory; if (!hostwine::host_is_wine() && SUCCEEDED(CreateDXGIFactory1(IID_PPV_ARGS(&factory.p)))) { for (const bool warp : {false, true}) { From a32330f561ea6088900a4abb61af9b5dd216d5ef Mon Sep 17 00:00:00 2001 From: thibaut Date: Mon, 23 Nov 2026 17:23:12 +0100 Subject: [PATCH 05/23] d3d12_xs: slot 133 review fixes: integer flag mask for clang-cl, handler registered by every Vulkan device The PC flag mask was a D3D12_RESOURCE_FLAGS constant past the SDK's last enumerator, which clang-cl with SDK 10.0.26100 refuses as a constant expression; it is an integer now, cast after the AND. The slot-133 handler was registered in create_vulkan_device only, so the standalone device gta6rt --run creates never served the slot; the Device constructor registers it now. Co-Authored-By: Claude Opus 5.5 --- runtime/shims/d3d12_vulkan_device.cpp | 5 ++++- runtime/shims/d3d12_xs_device.cpp | 4 +++- third_party/rpf9-explorer | 2 +- 3 files changed, 8 insertions(+), 3 deletions(-) diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index 1b4dcda40c..83f08cc2de 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -4580,6 +4580,10 @@ class Device final static constexpr GUID kTag{0xc58e1d27, 0x3a96, 0x4b4f, {0x9e, 0x72, 0x6d, 0x0a, 0x8b, 0x5f, 0x3c, 0x61}}; explicit Device(const VulkanDeviceInfo& info) { + // Every Vulkan device serves Xbox device slot 133, whichever entry made it: create_vulkan_device and the + // standalone device gta6rt --run uses both come through here (found in review: registering only in + // create_vulkan_device left the retail path without it). + rt::d3d12_xs::set_placed_at_va_handler(&create_buffer_at_host_address); state_.info = info; queue_users_.resize(info.command_queues.size(), 0); compute_users_.resize(info.compute_queues.size(), 0); @@ -8173,7 +8177,6 @@ class Device final HRESULT create_vulkan_device(const VulkanDeviceInfo& info, REFIID riid, void** out) { if (!out) return E_POINTER; *out = nullptr; - rt::d3d12_xs::set_placed_at_va_handler(&create_buffer_at_host_address); auto* device = new Device(info); if (!device->ok()) { device->Release(); diff --git a/runtime/shims/d3d12_xs_device.cpp b/runtime/shims/d3d12_xs_device.cpp index 7a815e0533..a1a5d86ef3 100644 --- a/runtime/shims/d3d12_xs_device.cpp +++ b/runtime/shims/d3d12_xs_device.cpp @@ -1339,7 +1339,9 @@ HRESULT proxy_create_placed_resource_x(DeviceProxy* self, void* va, const D3D12_ const PlacedAtVaHandler handler = g_placed_at_va.load(std::memory_order_acquire); if (!handler) return E_NOTIMPL; if (!out || !xbox_desc || !riid) return E_POINTER; - constexpr auto kPcResourceFlags = static_cast(0x7ff); + // An integer mask: a D3D12_RESOURCE_FLAGS constant past the SDK's last enumerator is not a constant expression + // for clang-cl with SDK 10.0.26100 (found in review). The cast is applied to the masked value at run time. + constexpr std::uint32_t kPcResourceFlags = 0x7ff; D3D12_RESOURCE_DESC pc_desc = *xbox_desc; const auto xbox_flags = static_cast(pc_desc.Flags); pc_desc.Flags = static_cast(xbox_flags & kPcResourceFlags); diff --git a/third_party/rpf9-explorer b/third_party/rpf9-explorer index e2939175c3..917e9b9c75 160000 --- a/third_party/rpf9-explorer +++ b/third_party/rpf9-explorer @@ -1 +1 @@ -Subproject commit e2939175c36a02d6ed25fa2c217b9d6ddcb8b516 +Subproject commit 917e9b9c75d7a200d143565740abab6026173bce From 2b584ec2b5babcbe2961cea82f184a5893f080a2 Mon Sep 17 00:00:00 2001 From: thibaut Date: Mon, 23 Nov 2026 17:27:45 +0100 Subject: [PATCH 06/23] Reset third_party/rpf9-explorer to main's commit (stray gitlink bump, found in review) Co-Authored-By: Claude Opus 5.5 --- third_party/rpf9-explorer | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/third_party/rpf9-explorer b/third_party/rpf9-explorer index 917e9b9c75..e2939175c3 160000 --- a/third_party/rpf9-explorer +++ b/third_party/rpf9-explorer @@ -1 +1 @@ -Subproject commit 917e9b9c75d7a200d143565740abab6026173bce +Subproject commit e2939175c36a02d6ed25fa2c217b9d6ddcb8b516 From 588ef0b5ebfd77a475c77e46acd4e7e3b039c7ea Mon Sep 17 00:00:00 2001 From: thibaut Date: Mon, 23 Nov 2026 17:33:52 +0100 Subject: [PATCH 07/23] d3d12: slot 133 falls back to an ordinary buffer when the driver will not import the title's pages RADV under Wine refuses to import a view of a pagefile-backed section (E_OUTOFMEMORY on an RX 9070 XT, found in review), which is the form xmem's physical pages take, so the retail boot stopped at the first 174 MiB placement. An import failure other than a misaligned VA now gives an ordinary DEFAULT buffer of the same description, as #6915's stand-in did, logged once: the boot goes on, and the title's writes at that VA don't reach it on such a driver. Co-Authored-By: Claude Opus 5.5 --- runtime/shims/d3d12_vulkan_device.cpp | 17 +++++++++++++++-- third_party/rpf9-explorer | 2 +- 2 files changed, 16 insertions(+), 3 deletions(-) diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index ce89acff0f..ab51e9c27a 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -6917,11 +6917,24 @@ class Device final auto* resource = new Resource(state_, desc, heap, D3D12_HEAP_FLAG_NONE); resource->attach_device(identity()); const HRESULT hr = resource->create_host_buffer(address); - if (FAILED(hr)) { - log_once("a title-placed buffer (device slot 133) could not import its pages; HRESULT", int(hr)); + if (hr == E_INVALIDARG) { resource->Release(); return d3d12_trace::result(method, hr); } + if (FAILED(hr)) { + // The driver would not import these pages: RADV refuses a view of a pagefile-backed section, the form + // xmem's physical pages take (found in review on an RX 9070 XT under Wine), and a device without + // VK_EXT_external_memory_host has no import at all. The boot goes on with an ordinary DEFAULT buffer + // of the same description, as #6915's stand-in did: the title gets a resource, but its writes at + // `address` do not reach it. + resource->Release(); + log_once("a title-placed buffer (device slot 133) could not import its pages, so it is an ordinary buffer " + "the title's writes do not reach; HRESULT", + int(hr)); + const D3D12_HEAP_PROPERTIES fallback{D3D12_HEAP_TYPE_DEFAULT}; + return d3d12_trace::result(method, create_committed(&fallback, D3D12_HEAP_FLAG_NONE, &desc, + D3D12_RESOURCE_STATE_COMMON, 0, nullptr, riid, out)); + } return d3d12_trace::result(method, hand_out(resource, riid, out)); } diff --git a/third_party/rpf9-explorer b/third_party/rpf9-explorer index e2939175c3..917e9b9c75 160000 --- a/third_party/rpf9-explorer +++ b/third_party/rpf9-explorer @@ -1 +1 @@ -Subproject commit e2939175c36a02d6ed25fa2c217b9d6ddcb8b516 +Subproject commit 917e9b9c75d7a200d143565740abab6026173bce From 5e260436f97cb9c49099f7488848fdeb0f7dda04 Mon Sep 17 00:00:00 2001 From: thibaut Date: Mon, 23 Nov 2026 17:43:45 +0100 Subject: [PATCH 08/23] Reset third_party/rpf9-explorer to main's commit again (the fallback commit re-added it, found in review) Co-Authored-By: Claude Opus 5.5 --- third_party/rpf9-explorer | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/third_party/rpf9-explorer b/third_party/rpf9-explorer index 917e9b9c75..e2939175c3 160000 --- a/third_party/rpf9-explorer +++ b/third_party/rpf9-explorer @@ -1 +1 @@ -Subproject commit 917e9b9c75d7a200d143565740abab6026173bce +Subproject commit e2939175c36a02d6ed25fa2c217b9d6ddcb8b516 From 310773a01cae69f733b9fb9c27b634942a32ff79 Mon Sep 17 00:00:00 2001 From: thibaut Date: Mon, 23 Nov 2026 17:49:03 +0100 Subject: [PATCH 09/23] d3d12: slot 133 review fixes: no write-combined import, committed-range check, immediate free, proxy test - A write-combined (or uncached) page in the range is not imported: an RTX 5090 imported such a range and read wrong bytes back (found in review). It takes the ordinary-buffer fallback. - The whole range must be committed, walked with VirtualQuery across allocations (the retail buffer spans three mapped windows); otherwise E_INVALIDARG instead of undefined behaviour in Vulkan. - The imported memory is freed as soon as the submitted work has retired (wait_retire_ticket), not after the next submission: VK_EXT_external_memory_host needs the caller's pages to outlive it, and a title may free them right after releasing the resource. - The PC flag mask is 0x5ff: 0x200, which the host refuses, is dropped. Slot 133 is listed in device_slot_overridden. - xs_proxy_mock_test registers a handler and checks slot 133's argument positions, the flag mask (0x20204 -> 0x4), the ROW_MAJOR rewrite and the iid; d3d12_existing_heap_test checks the write-combined fallback and the partly committed refusal. Co-Authored-By: Claude Opus 5.5 --- runtime/shims/d3d12_vulkan_device.cpp | 29 +++++++++++++++ runtime/shims/d3d12_xs_device.cpp | 6 ++-- runtime/test/d3d12_existing_heap_test.cpp | 30 ++++++++++++++++ runtime/test/xs_proxy_mock_test.cpp | 44 +++++++++++++++++++++-- 4 files changed, 105 insertions(+), 4 deletions(-) diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index ab51e9c27a..f0ed747a07 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -1723,6 +1723,18 @@ class Resource final } if (image_address_) device_.forget_image(image_address_); device_.context->remove_resource(id()); + if (host_import_) { + // 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). + 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); + buffer_ = VK_NULL_HANDLE; + memory_ = VK_NULL_HANDLE; + } if (in_arena_) device_.arena_release(arena_offset_, desc_.Width, DeviceState::arena_buffer); if (image_ && !sparse_image_) device_.context->defer_destroy(leonida::DeferredDeletionQueue::Kind::image, image_); @@ -1897,6 +1909,21 @@ class Resource final if (!address || !desc_.Width || (start & (alignment - 1)) || desc_.Width > UINT64_MAX - alignment) return E_INVALIDARG; const VkDeviceSize bytes = (desc_.Width + alignment - 1) & ~(alignment - 1); + // The whole imported range must be committed, possibly across several allocations (the retail buffer spans + // three mapped windows): anything else is undefined in Vulkan, so it is E_INVALIDARG here (found in review). + // A write-combined page is not imported: on an RTX 5090 such an import succeeded but GPU reads returned + // wrong bytes (found in review), so it takes the ordinary-buffer fallback instead. + bool write_combined = false; + for (VkDeviceSize at = 0; at < bytes;) { + MEMORY_BASIC_INFORMATION region{}; + if (!VirtualQuery(static_cast(address) + at, ®ion, sizeof(region)) || + region.State != MEM_COMMIT) + return E_INVALIDARG; + if (region.Protect & (PAGE_WRITECOMBINE | PAGE_NOCACHE)) write_combined = true; + const auto region_end = reinterpret_cast(region.BaseAddress) + region.RegionSize; + at = region_end - start; + } + if (write_combined) return E_NOTIMPL; const bool need_bda = device_.info.buffer_device_address || device_.arena.buffer != VK_NULL_HANDLE; VkExternalMemoryBufferCreateInfo external{VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_BUFFER_CREATE_INFO}; external.handleTypes = VK_EXTERNAL_MEMORY_HANDLE_TYPE_HOST_ALLOCATION_BIT_EXT; @@ -1945,6 +1972,7 @@ class Resource final if (!memory_) return E_OUTOFMEMORY; if (vk.vkBindBufferMemory(device_.info.device, buffer_, memory_, 0) != VK_SUCCESS) return E_OUTOFMEMORY; mapped_ = address; + host_import_ = true; va_ = start; if (need_bda && vk.vkGetBufferDeviceAddress) { VkBufferDeviceAddressInfo bda{VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO}; @@ -2494,6 +2522,7 @@ class Resource final VkImageAspectFlags aspects_ = 0; std::uint64_t buffer_va_ = 0; std::uint64_t gpu_va_ = 0; + bool host_import_ = false; // memory_ is the caller's pages (create_host_buffer): freed at once, not deferred bool reserved_ = false; bool sparse_image_ = false; bool placed_ = false; diff --git a/runtime/shims/d3d12_xs_device.cpp b/runtime/shims/d3d12_xs_device.cpp index f1afba93ad..b565fdd4d2 100644 --- a/runtime/shims/d3d12_xs_device.cpp +++ b/runtime/shims/d3d12_xs_device.cpp @@ -1503,7 +1503,9 @@ HRESULT proxy_create_placed_resource_x(DeviceProxy* self, void* va, const D3D12_ if (!out || !xbox_desc || !riid) return E_POINTER; // An integer mask: a D3D12_RESOURCE_FLAGS constant past the SDK's last enumerator is not a constant expression // for clang-cl with SDK 10.0.26100 (found in review). The cast is applied to the masked value at run time. - constexpr std::uint32_t kPcResourceFlags = 0x7ff; + // The PC flags up to RAYTRACING_ACCELERATION_STRUCTURE (0x100) and USE_TIGHT_ALIGNMENT (0x400); 0x200 is + // dropped, as committed_resource_refusal says the host refuses it (found in review). + constexpr std::uint32_t kPcResourceFlags = 0x5ff; D3D12_RESOURCE_DESC pc_desc = *xbox_desc; const auto xbox_flags = static_cast(pc_desc.Flags); pc_desc.Flags = static_cast(xbox_flags & kPcResourceFlags); @@ -1754,7 +1756,7 @@ ID3D12Device* device_proxy_real_device(const void* device) { bool device_slot_overridden(unsigned slot) { if (slot <= 2 || slot == 8 || slot == 9 || slot == 14 || slot == 31 || slot == 32 || slot == 34 || slot == 35 || slot == 36 || slot == 45 || slot == 46 || slot == 50 || slot == 62 || slot == 67 || - slot == 75 || slot == 76) + slot == 75 || slot == 76 || slot == 133) return true; const XboxDeviceSlotRoutes& routes = xbox_device_slot_routes(); return slot == routes.frame_interval || slot == routes.schedule_event || slot == routes.wait_event || diff --git a/runtime/test/d3d12_existing_heap_test.cpp b/runtime/test/d3d12_existing_heap_test.cpp index 73f2f13566..9a3034f14e 100644 --- a/runtime/test/d3d12_existing_heap_test.cpp +++ b/runtime/test/d3d12_existing_heap_test.cpp @@ -238,6 +238,36 @@ int check_title_placed_all(ID3D12Device* device) { failures += check_title_placed(device, "section view", view, size); UnmapViewOfFile(view); CloseHandle(section); + + // Not imported: a write-combined range (an RTX 5090 imported it but read wrong bytes back, found in review) + // falls back to an ordinary buffer, so the resource exists but is not at the pages' address; a range only partly + // committed is E_INVALIDARG. + const char* who = "vulkan slot-133 buffer"; + D3D12_RESOURCE_DESC desc{}; + desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + desc.Width = size; + desc.Height = desc.DepthOrArraySize = desc.MipLevels = 1; + desc.SampleDesc.Count = 1; + desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + void* combined = VirtualAlloc(nullptr, size, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE | PAGE_WRITECOMBINE); + EXPECT(combined != nullptr); + { + Ref fallback; + EXPECT_HR(rt::d3d12::create_buffer_at_host_address(device, combined, desc, IID_PPV_ARGS(&fallback.p)), S_OK); + EXPECT(fallback->GetGPUVirtualAddress() != reinterpret_cast(combined)); + } + VirtualFree(combined, 0, MEM_RELEASE); + char* partial = static_cast(VirtualAlloc(nullptr, size, MEM_RESERVE, PAGE_READWRITE)); + EXPECT(partial != nullptr && VirtualAlloc(partial, size / 2, MEM_COMMIT, PAGE_READWRITE) == partial); + { + Ref refused; + EXPECT_HR(rt::d3d12::create_buffer_at_host_address(device, partial, desc, IID_PPV_ARGS(&refused.p)), + E_INVALIDARG); + EXPECT(refused.p == nullptr); + } + VirtualFree(partial, 0, MEM_RELEASE); + std::printf("%s: a write-combined range falls back to an ordinary buffer, a partly committed one is refused\n", + who); return failures; } diff --git a/runtime/test/xs_proxy_mock_test.cpp b/runtime/test/xs_proxy_mock_test.cpp index 9dded9da1b..f7dbd407f0 100644 --- a/runtime/test/xs_proxy_mock_test.cpp +++ b/runtime/test/xs_proxy_mock_test.cpp @@ -269,9 +269,9 @@ using SlotFn = std::uint64_t(WINAPI*)(void*, std::uint64_t, std::uint64_t, std:: std::uint64_t, std::uint64_t, std::uint64_t, std::uint64_t, std::uint64_t); std::uint64_t raw(const void* object, unsigned slot, std::uint64_t a1 = 0, std::uint64_t a2 = 0, - std::uint64_t a3 = 0, std::uint64_t a4 = 0, std::uint64_t a5 = 0) { + std::uint64_t a3 = 0, std::uint64_t a4 = 0, std::uint64_t a5 = 0, std::uint64_t a6 = 0) { void* const* vtable = *reinterpret_cast(object); - return reinterpret_cast(vtable[slot])(const_cast(object), a1, a2, a3, a4, a5, 0, 0, 0, 0, 0, 0, + return reinterpret_cast(vtable[slot])(const_cast(object), a1, a2, a3, a4, a5, a6, 0, 0, 0, 0, 0, 0, 0, 0); } @@ -384,6 +384,46 @@ int check_levels() { // 133: past every PC device vtable; the retail title calls it. Refused, not a jump through a missing entry. EXPECT(hr_of(raw(device, 133)) == E_NOTIMPL && mock->calls[127] == 0); + // 133 with a handler (CreatePlacedResourceX): the arguments in the title's positions (va, desc, state, + // clear, riid, out) reach the handler with the real device, the Xbox flag bits masked to the PC ones the host + // takes (0x20004 -> 0x4, and 0x200 dropped) and the buffer's Xbox layout word made ROW_MAJOR. + { + static void* seen_real = nullptr; + static void* seen_va = nullptr; + static D3D12_RESOURCE_DESC seen_desc{}; + static GUID seen_iid{}; + const xs::PlacedAtVaHandler handler = [](ID3D12Device* real_device, void* va, + const D3D12_RESOURCE_DESC& desc, REFIID iid, + void** out) -> HRESULT { + seen_real = real_device; + seen_va = va; + seen_desc = desc; + seen_iid = iid; + *out = reinterpret_cast(0x1330); + return S_OK; + }; + xs::set_placed_at_va_handler(handler); + D3D12_RESOURCE_DESC xbox_desc{}; + xbox_desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + xbox_desc.Width = 0x10000; + xbox_desc.Height = xbox_desc.DepthOrArraySize = xbox_desc.MipLevels = 1; + xbox_desc.SampleDesc.Count = 1; + xbox_desc.Layout = static_cast(0x1); // the Xbox row-major word + xbox_desc.Flags = static_cast(0x20204); + const GUID resource_iid = __uuidof(ID3D12Resource); + void* placed = nullptr; + void* const va = reinterpret_cast(0x7f0000000000ull); + const HRESULT r133 = hr_of(raw(device, 133, word(va), word(&xbox_desc), 0xFFFFFFFFull, 0, + word(&resource_iid), word(&placed))); + xs::set_placed_at_va_handler(nullptr); + EXPECT(r133 == S_OK && placed == reinterpret_cast(0x1330)); + EXPECT(seen_real == xs::device_proxy_real_device(device) && seen_va == va); + EXPECT(static_cast(seen_desc.Flags) == 0x4); + EXPECT(seen_desc.Layout == D3D12_TEXTURE_LAYOUT_ROW_MAJOR && seen_desc.Width == 0x10000); + EXPECT(std::memcmp(&seen_iid, &resource_iid, sizeof(GUID)) == 0); + EXPECT(xs::device_slot_overridden(133)); + } + Mock* const queue_mock = reinterpret_cast(real_queue); Mock* const fence_mock = reinterpret_cast(real_fence); EXPECT(release(queue) == 0 && release(fence) == 0); From c3fe8252904e5bf7297aae79ba5306ad308bc2fb Mon Sep 17 00:00:00 2001 From: thibaut Date: Mon, 23 Nov 2026 17:55:50 +0100 Subject: [PATCH 10/23] d3d12_existing_heap_test: don't compare the host's heap Alignment, which varies from run to run The host runtime answers 64 KiB on some runs and 4 MiB on others for the same allocation (RX 9070 XT, RTX 5090, WARP; found in review), which made the test fail about 1 run in 40. The layer's Alignment must still be 64 KiB for an opened heap, and the host's either of the two values. Co-Authored-By: Claude Opus 5.5 --- runtime/test/d3d12_existing_heap_test.cpp | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/runtime/test/d3d12_existing_heap_test.cpp b/runtime/test/d3d12_existing_heap_test.cpp index 9a3034f14e..44059575f8 100644 --- a/runtime/test/d3d12_existing_heap_test.cpp +++ b/runtime/test/d3d12_existing_heap_test.cpp @@ -105,7 +105,14 @@ int compare_cases(const std::vector& ours, const std::vector& host, for (size_t i = 0; i < ours.size() && i < host.size(); ++i) { const D3D12_HEAP_DESC& a = ours[i].desc; const D3D12_HEAP_DESC& b = host[i].desc; - const bool same = ours[i].hr == host[i].hr && a.SizeInBytes == b.SizeInBytes && a.Alignment == b.Alignment && + // The host's Alignment varies from run to run for the same allocation (64 KiB on some runs, 4 MiB on others, + // on an RX 9070 XT, an RTX 5090 and WARP; found in review), so it is not compared: the layer's must be 64 KiB + // for an opened heap, and the host's either of the two. + const bool alignment_ok = + !SUCCEEDED(ours[i].hr) || + (a.Alignment == D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT && + (b.Alignment == D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT || b.Alignment == 4ull * 1024 * 1024)); + const bool same = ours[i].hr == host[i].hr && a.SizeInBytes == b.SizeInBytes && alignment_ok && a.Properties.Type == b.Properties.Type && a.Properties.CPUPageProperty == b.Properties.CPUPageProperty && a.Properties.MemoryPoolPreference == b.Properties.MemoryPoolPreference && a.Flags == b.Flags; From a07c8c0e895dd8c2755171bdda9b78ef75b65a38 Mon Sep 17 00:00:00 2001 From: Logan Date: Mon, 23 Nov 2026 12:01:48 -0500 Subject: [PATCH 11/23] xmem: commit physical pages on first touch, not when they are allocated XMemAllocatePhysicalPages backed each call with one SEC_COMMIT section, so the title's ~6.1 GiB page-pool request after boot stop 17 was charged in full at once and fails with ERROR_COMMITMENT_LIMIT on a 16 GB machine. Mapping the pages right away (as the title does) would charge most of it within seconds too, so the commit now follows first access. The section is SEC_RESERVE. A vectored handler commits the faulting 64 KiB page through a reserve-only view of the whole section when the address lies in a live mapping, so every view of that page sees it. Faults on committed pages whose protection forbids the access, and faults outside the mapped pages, go on to the next handler, and a failed commit is not swallowed. rt::xmem::commit_physical_range commits a range up front for shims that hand guest memory to the kernel. Reported by controldebils and rafaelpssz in #7333. --- runtime/shims/xmem.cpp | 144 +++++++++++++++++++++++++++++++++++-- runtime/shims/xmem.h | 9 +++ runtime/test/xmem_test.cpp | 126 ++++++++++++++++++++++++++++++++ 3 files changed, 272 insertions(+), 7 deletions(-) create mode 100644 runtime/shims/xmem.h diff --git a/runtime/shims/xmem.cpp b/runtime/shims/xmem.cpp index 37f29459f1..ee499b077f 100644 --- a/runtime/shims/xmem.cpp +++ b/runtime/shims/xmem.cpp @@ -35,6 +35,7 @@ #include "shims.h" #include "startup_trace.h" +#include "xmem.h" namespace { @@ -238,10 +239,14 @@ struct Window { struct Section { HANDLE handle; - explicit Section(HANDLE h) : handle(h) {} + void* scratch; + explicit Section(HANDLE h) : handle(h), scratch(MapViewOfFile(h, FILE_MAP_WRITE, 0, 0, 0)) {} Section(const Section&) = delete; Section& operator=(const Section&) = delete; - ~Section() { CloseHandle(handle); } + ~Section() { + if (scratch) UnmapViewOfFile(scratch); + CloseHandle(handle); + } }; struct PhysicalPage { @@ -261,7 +266,28 @@ std::map g_windows; // base -> window std::unordered_map g_pages; // page number -> backing std::vector g_free_slots; uint64_t g_next_slot = 1; -std::unordered_map g_mapped; // mapped 64 KiB address -> page number +struct MappedPage { + uint64_t page; + std::shared_ptr
section; + uint64_t offset; +}; + +std::unordered_map g_mapped; +SRWLOCK g_fault_lock = SRWLOCK_INIT; + +struct FaultLockExclusive { + FaultLockExclusive() { AcquireSRWLockExclusive(&g_fault_lock); } + ~FaultLockExclusive() { ReleaseSRWLockExclusive(&g_fault_lock); } + FaultLockExclusive(const FaultLockExclusive&) = delete; + FaultLockExclusive& operator=(const FaultLockExclusive&) = delete; +}; + +struct FaultLockShared { + FaultLockShared() { AcquireSRWLockShared(&g_fault_lock); } + ~FaultLockShared() { ReleaseSRWLockShared(&g_fault_lock); } + FaultLockShared(const FaultLockShared&) = delete; + FaultLockShared& operator=(const FaultLockShared&) = delete; +}; // With g_phys_mutex held. A window replaces every window it overlaps: the title released those regions (with // kernel32!VirtualFree, which the shim does not see) before the host could hand the addresses out again. @@ -429,11 +455,17 @@ void* WINAPI XMemVirtualAlloc(void* address, SIZE_T size, DWORD allocation_type, bool unmap_page(uintptr_t address) { const auto it = g_mapped.find(address); if (it == g_mapped.end()) return true; + MappedPage mapped = std::move(it->second); + { + const FaultLockExclusive lock; + g_mapped.erase(it); + } if (!placeholder_api().unmap_view2(GetCurrentProcess(), reinterpret_cast(address), MEM_PRESERVE_PLACEHOLDER)) { + const FaultLockExclusive lock; + g_mapped.emplace(address, std::move(mapped)); return false; } - g_mapped.erase(it); return true; } @@ -453,10 +485,77 @@ bool map_page(uintptr_t address, uint64_t page, DWORD protect) { it->second.offset, kPhysicalPageSize, MEM_REPLACE_PLACEHOLDER, protect, nullptr, 0); if (!view) return false; - g_mapped[address] = page; + const FaultLockExclusive lock; + g_mapped[address] = MappedPage{page, it->second.section, it->second.offset}; return true; } +enum class PageCommit { not_ours, committed_before, committed_now, failed }; + +PageCommit commit_mapped_page(uintptr_t address, DWORD& protect) { + const auto it = g_mapped.find(address); + if (it == g_mapped.end() || !it->second.section->scratch) return PageCommit::not_ours; + MEMORY_BASIC_INFORMATION info{}; + if (!VirtualQuery(reinterpret_cast(address), &info, sizeof(info)) || info.Type != MEM_MAPPED) { + return PageCommit::not_ours; + } + if (info.State == MEM_COMMIT) { + protect = info.Protect; + return PageCommit::committed_before; + } + void* const backing = static_cast(it->second.section->scratch) + it->second.offset; + return VirtualAlloc(backing, kPhysicalPageSize, MEM_COMMIT, PAGE_READWRITE) ? PageCommit::committed_now + : PageCommit::failed; +} + +bool access_allowed(DWORD protect, ULONG_PTR access) { + if (protect & PAGE_GUARD) return false; + switch (protect & 0xff) { + case PAGE_EXECUTE_READWRITE: + case PAGE_EXECUTE_WRITECOPY: + return true; + case PAGE_READWRITE: + case PAGE_WRITECOPY: + return access != 8; + case PAGE_EXECUTE_READ: + return access != 1; + case PAGE_READONLY: + return access == 0; + case PAGE_EXECUTE: + return access == 8; + default: + return false; + } +} + +LONG CALLBACK physical_page_fault(EXCEPTION_POINTERS* info) { + thread_local bool busy = false; + const EXCEPTION_RECORD* record = info ? info->ExceptionRecord : nullptr; + if (busy || !record || record->ExceptionCode != EXCEPTION_ACCESS_VIOLATION || record->NumberParameters < 2) { + return EXCEPTION_CONTINUE_SEARCH; + } + busy = true; + const uintptr_t address = + static_cast(record->ExceptionInformation[1]) & ~static_cast(kPhysicalPageSize - 1); + DWORD protect = 0; + PageCommit result; + { + const FaultLockShared lock; + result = commit_mapped_page(address, protect); + } + busy = false; + if (result == PageCommit::committed_now) return EXCEPTION_CONTINUE_EXECUTION; + if (result == PageCommit::committed_before && access_allowed(protect, record->ExceptionInformation[0])) { + return EXCEPTION_CONTINUE_EXECUTION; + } + return EXCEPTION_CONTINUE_SEARCH; +} + +bool install_physical_page_fault_handler() { + static const bool installed = AddVectoredExceptionHandler(1, &physical_page_fault) != nullptr; + return installed; +} + // Two of the measured windows are reserved PAGE_NOACCESS for the CPU and the GPU alike; pages mapped there are still // GPU memory, which the D3D12 layer reads on the CPU. DWORD view_protect(const Window& window) { @@ -487,7 +586,7 @@ void note_physical_attributes(uint64_t attributes, uint64_t count, const void* c // a 32-bit BOOL. After success every caller compares the count with the one it asked for and frees the pages if they // differ, so the count is in/out. // -// Each call is backed by one pagefile-backed section of count * 64 KiB: committed (charged) at once, given physical +// Each call is backed by one pagefile-backed section of count * 64 KiB: committed (charged) on touch, given physical // memory as it is touched, zero-filled. Pages keep their contents while unmapped or mapped elsewhere, and one page can // be mapped at several addresses. ASSUMPTION: the attribute word (memory type, perhaps the page size) is not decoded; // every page is 64 KiB, which all four callers' arithmetic agrees with. @@ -506,14 +605,23 @@ BOOL WINAPI XMemAllocatePhysicalPages(uint64_t attributes, uint64_t* page_count, SetLastError(ERROR_NOT_ENOUGH_MEMORY); return FALSE; } + if (!install_physical_page_fault_handler()) { + *page_count = 0; + SetLastError(ERROR_NOT_SUPPORTED); + return FALSE; + } const uint64_t bytes = count * kPhysicalPageSize; // below 2^37: count is below 2^21 - const HANDLE handle = CreateFileMappingW(INVALID_HANDLE_VALUE, nullptr, PAGE_READWRITE | SEC_COMMIT, + const HANDLE handle = CreateFileMappingW(INVALID_HANDLE_VALUE, nullptr, PAGE_READWRITE | SEC_RESERVE, static_cast(bytes >> 32), static_cast(bytes), nullptr); if (!handle) { *page_count = 0; return FALSE; } const auto section = std::make_shared
(handle); + if (!section->scratch) { + *page_count = 0; + return FALSE; + } for (uint64_t i = 0; i < count; ++i) { uint64_t slot; if (!g_free_slots.empty()) { @@ -694,6 +802,28 @@ LPVOID WINAPI TitleVirtualAlloc(LPVOID address, SIZE_T size, DWORD allocation_ty } // namespace +namespace rt::xmem { + +bool commit_physical_range(const void* address, size_t size) { + if (size == 0) return true; + const uintptr_t start = reinterpret_cast(address); + if (start > (std::numeric_limits::max)() - (size - 1)) { + SetLastError(ERROR_INVALID_PARAMETER); + return false; + } + const uintptr_t mask = ~static_cast(kPhysicalPageSize - 1); + const uintptr_t first = start & mask; + const uintptr_t pages = (((start + (size - 1)) & mask) - first) / kPhysicalPageSize + 1; + const FaultLockShared lock; + for (uintptr_t i = 0; i < pages; ++i) { + DWORD protect = 0; + if (commit_mapped_page(first + i * kPhysicalPageSize, protect) == PageCommit::failed) return false; + } + return true; +} + +} + #define TITLE_VIRTUAL_ALLOC(dll) {dll, "VirtualAlloc", reinterpret_cast(&TitleVirtualAlloc)} // The classic libraries and the memory api sets a title's imports name. diff --git a/runtime/shims/xmem.h b/runtime/shims/xmem.h new file mode 100644 index 0000000000..8e0b2d973e --- /dev/null +++ b/runtime/shims/xmem.h @@ -0,0 +1,9 @@ +#pragma once + +#include + +namespace rt::xmem { + +bool commit_physical_range(const void* address, std::size_t size); + +} diff --git a/runtime/test/xmem_test.cpp b/runtime/test/xmem_test.cpp index eed030c129..bd24de018f 100644 --- a/runtime/test/xmem_test.cpp +++ b/runtime/test/xmem_test.cpp @@ -18,9 +18,11 @@ #include #include #include +#include #include "shims.h" #include "startup_trace.h" +#include "xmem.h" namespace { @@ -440,6 +442,129 @@ void test_physical_pages(const PhysicalApi& api) { // The windows were split into one placeholder per page; the process exit releases them. } +bool access_faults(volatile uint32_t* address, bool write) { + __try { + if (write) { + *address = 1; + } else { + const uint32_t value = *address; + (void)value; + } + } __except (GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION ? EXCEPTION_EXECUTE_HANDLER + : EXCEPTION_CONTINUE_SEARCH) { + return true; + } + return false; +} + +int64_t commit_growth(const PERFORMANCE_INFORMATION& from, const PERFORMANCE_INFORMATION& to) { + return (static_cast(to.CommitTotal) - static_cast(from.CommitTotal)) * + static_cast(to.PageSize); +} + +void test_physical_pages_commit_on_touch(const PhysicalApi& api) { + PERFORMANCE_INFORMATION before{}; + if (!GetPerformanceInfo(&before, sizeof(before))) { + check(false, "GetPerformanceInfo reads the system commit charge"); + return; + } + const uint64_t free_commit = static_cast(before.CommitLimit - before.CommitTotal) * before.PageSize; + const uint64_t count = (free_commit + (uint64_t{1} << 30)) / kPage64k; + if (count >= (uint64_t{1} << 20)) { + std::printf("SKIP physical pages past the free commit: %llu MiB of commit is free\n", + static_cast(free_commit >> 20)); + return; + } + std::vector pages(static_cast(count)); + uint64_t got = count; + check(api.allocate(0x380, &got, pages.data()) == TRUE && got == count, + "XMemAllocatePhysicalPages gives 1 GiB more pages than the system has commit free"); + if (got != count) return; + PERFORMANCE_INFORMATION allocated{}; + GetPerformanceInfo(&allocated, sizeof(allocated)); + check(commit_growth(before, allocated) < static_cast(count * kPage64k / 8), + "allocating those pages does not charge them"); + + constexpr uint64_t kMapped = 1024; + constexpr uint64_t kTouched = 512; + auto* const window = static_cast( + api.virtual_alloc(nullptr, kMapped * kPage64k, MEM_RESERVE | kXmem64kPages, 0x21, PAGE_READWRITE)); + auto* const second = static_cast( + api.virtual_alloc(nullptr, 2 * kPage64k, MEM_RESERVE | kXmem64kPages, 0x21, PAGE_READWRITE)); + check(window != nullptr && second != nullptr, "XMemVirtualAlloc reserves windows for them"); + if (!window || !second) { + api.free_pages(count, pages.data()); + return; + } + check(api.map(window, kMapped, pages.data()) == window, "1,024 of them map into one window"); + PERFORMANCE_INFORMATION mapped{}; + GetPerformanceInfo(&mapped, sizeof(mapped)); + check(commit_growth(allocated, mapped) < static_cast(kMapped * kPage64k / 2), + "mapping them does not charge them"); + + for (uint64_t i = 0; i < kTouched; ++i) { + static_cast(static_cast(window + i * kPage64k))[0] = + 0xc0de0000u | static_cast(i); + } + PERFORMANCE_INFORMATION touched{}; + GetPerformanceInfo(&touched, sizeof(touched)); + const int64_t touched_growth = commit_growth(mapped, touched); + check(touched_growth >= static_cast(kTouched * kPage64k / 2) && + touched_growth < static_cast(kMapped * kPage64k), + "writing to 512 of them charges about those 512 pages"); + bool written = true; + for (uint64_t i = 0; i < kTouched; ++i) written &= read_u32(window + i * kPage64k, 0) == (0xc0de0000u | i); + check(written, "each touched page keeps what was written to it"); + check(read_u32(window + kTouched * kPage64k, 0) == 0, "an untouched page reads as zero"); + + check(api.map(second, 2, pages.data()) == second, "two of the pages map into a second window"); + check(read_u32(second, 0) == 0xc0de0000u && read_u32(second + kPage64k, 0) == 0xc0de0001u, + "the second window sees what was written through the first"); + static_cast(static_cast(second))[1] = 0x5ca1ab1e; + check(read_u32(window, 4) == 0x5ca1ab1e, "and the first window sees what is written through the second"); + + DWORD old = 0; + check(VirtualProtect(window, kPage64k, PAGE_READONLY, &old) != FALSE && + access_faults(static_cast(static_cast(window)), true), + "a write to a committed read-only page still faults to the next handler"); + VirtualProtect(window, kPage64k, PAGE_READWRITE, &old); + void* const elsewhere = VirtualAlloc(nullptr, kPage64k, MEM_RESERVE, PAGE_READWRITE); + check(elsewhere != nullptr && access_faults(static_cast(elsewhere), false), + "a fault outside the mapped pages still reaches the next handler"); + if (elsewhere) VirtualFree(elsewhere, 0, MEM_RELEASE); + + uint8_t* const target = window + (kTouched + 1) * kPage64k; + check(rt::xmem::commit_physical_range(target, kPage64k), "commit_physical_range commits an untouched page"); + uint32_t local = 0; + check(rt::xmem::commit_physical_range(&local, sizeof(local)), "commit_physical_range skips memory it does not own"); + wchar_t directory[MAX_PATH]{}; + wchar_t path[MAX_PATH]{}; + bool read_ok = false; + if (GetTempPathW(MAX_PATH, directory) && GetTempFileNameW(directory, L"xpg", 0, path)) { + std::vector pattern(kPage64k / sizeof(uint32_t)); + for (size_t i = 0; i < pattern.size(); ++i) pattern[i] = 0x7e570000u + static_cast(i); + const HANDLE out = + CreateFileW(path, GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_TEMPORARY, nullptr); + DWORD bytes = 0; + const bool wrote = out != INVALID_HANDLE_VALUE && + WriteFile(out, pattern.data(), static_cast(kPage64k), &bytes, nullptr) && + bytes == kPage64k; + if (out != INVALID_HANDLE_VALUE) CloseHandle(out); + const HANDLE in = wrote ? CreateFileW(path, GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, 0, nullptr) + : INVALID_HANDLE_VALUE; + if (in != INVALID_HANDLE_VALUE) { + read_ok = ReadFile(in, target, static_cast(kPage64k), &bytes, nullptr) && bytes == kPage64k && + std::memcmp(target, pattern.data(), kPage64k) == 0; + CloseHandle(in); + } + DeleteFileW(path); + } + check(read_ok, "ReadFile fills a page that commit_physical_range committed"); + + check(api.map(second, 2, nullptr) == second && api.map(window, kMapped, nullptr) == window, "they unmap"); + check(api.free_pages(count, pages.data()) == TRUE, "XMemFreePhysicalPages frees them"); +} + // The placeholder flags pass through: reserve a placeholder, carve windows and committed memory out of it. void test_placeholders(const PhysicalApi& api) { auto* const base = static_cast( @@ -718,6 +843,7 @@ int main() { if (tools_mem) check(tools_mem() == FALSE, "XMemIsToolsMemAvailable returns FALSE (no devkit tools memory)"); if (virtual_alloc && physical.allocate && physical.free_pages && physical.map && physical.scatter) { test_physical_pages(physical); + test_physical_pages_commit_on_touch(physical); test_placeholders(physical); } From abd85df49f26245dbd8be81d750b6425c9f6e379 Mon Sep 17 00:00:00 2001 From: Logan Date: Mon, 23 Nov 2026 12:26:16 -0500 Subject: [PATCH 12/23] xmem: rt::xmem::commit_physical_pages commits pages by page number A writer that copies into physical pages through its own view of their section (a DirectStorage destination given as page numbers, #7652) sees reserve-only memory for pages the title has not touched yet, and no fault handler can resolve that address. commit_physical_pages commits the given pages through each section's own view, one VirtualAlloc per contiguous run, so such a writer can commit before it copies. Raised by nurtrino in #7599. --- runtime/shims/xmem.cpp | 30 ++++++++++++++++++++++++++++++ runtime/shims/xmem.h | 2 ++ runtime/test/xmem_test.cpp | 31 +++++++++++++++++++++++++++++++ 3 files changed, 63 insertions(+) diff --git a/runtime/shims/xmem.cpp b/runtime/shims/xmem.cpp index ee499b077f..e97f60f1e3 100644 --- a/runtime/shims/xmem.cpp +++ b/runtime/shims/xmem.cpp @@ -822,6 +822,36 @@ bool commit_physical_range(const void* address, size_t size) { return true; } +bool commit_physical_pages(const uint64_t* page_array, size_t count) { + if (count == 0) return true; + if (!page_array) { + SetLastError(ERROR_INVALID_PARAMETER); + return false; + } + const std::lock_guard lock(g_phys_mutex); + size_t first = 0; + while (first < count) { + const auto it = g_pages.find(page_array[first]); + if (it == g_pages.end() || !it->second.section->scratch) { + SetLastError(ERROR_INVALID_PARAMETER); + return false; + } + size_t last = first + 1; + while (last < count) { + const auto next = g_pages.find(page_array[last]); + if (next == g_pages.end() || next->second.section != it->second.section || + next->second.offset != it->second.offset + (last - first) * kPhysicalPageSize) { + break; + } + ++last; + } + void* const backing = static_cast(it->second.section->scratch) + it->second.offset; + if (!VirtualAlloc(backing, (last - first) * kPhysicalPageSize, MEM_COMMIT, PAGE_READWRITE)) return false; + first = last; + } + return true; +} + } #define TITLE_VIRTUAL_ALLOC(dll) {dll, "VirtualAlloc", reinterpret_cast(&TitleVirtualAlloc)} diff --git a/runtime/shims/xmem.h b/runtime/shims/xmem.h index 8e0b2d973e..beef935e65 100644 --- a/runtime/shims/xmem.h +++ b/runtime/shims/xmem.h @@ -1,9 +1,11 @@ #pragma once #include +#include namespace rt::xmem { bool commit_physical_range(const void* address, std::size_t size); +bool commit_physical_pages(const std::uint64_t* page_array, std::size_t count); } diff --git a/runtime/test/xmem_test.cpp b/runtime/test/xmem_test.cpp index bd24de018f..a47e43bfd1 100644 --- a/runtime/test/xmem_test.cpp +++ b/runtime/test/xmem_test.cpp @@ -565,6 +565,36 @@ void test_physical_pages_commit_on_touch(const PhysicalApi& api) { check(api.free_pages(count, pages.data()) == TRUE, "XMemFreePhysicalPages frees them"); } +void test_commit_physical_pages(const PhysicalApi& api) { + constexpr uint64_t kPages = 3; + uint64_t pages[kPages]{}; + uint64_t count = kPages; + check(api.allocate(0x280, &count, pages) == TRUE && count == kPages, "three physical pages for commit by number"); + if (count != kPages) return; + check(rt::xmem::commit_physical_pages(pages, 0), "committing no pages succeeds"); + check(!rt::xmem::commit_physical_pages(nullptr, 1), "committing from a null page array fails"); + const uint64_t unknown = 0x1fffff0; + check(!rt::xmem::commit_physical_pages(&unknown, 1), "committing a page number that was never allocated fails"); + check(rt::xmem::commit_physical_pages(pages, 2), "commit_physical_pages commits two pages that were never mapped"); + + auto* const window = static_cast( + api.virtual_alloc(nullptr, kPages * kPage64k, MEM_RESERVE | kXmem64kPages, 0x21, PAGE_READWRITE)); + check(window != nullptr, "XMemVirtualAlloc reserves a window for them"); + if (window) { + check(api.map(window, kPages, pages) == window, "the three pages map"); + MEMORY_BASIC_INFORMATION info[kPages]{}; + bool queried = true; + for (uint64_t i = 0; i < kPages; ++i) + queried &= VirtualQuery(window + i * kPage64k, &info[i], sizeof(info[i])) == sizeof(info[i]); + check(queried && info[0].State == MEM_COMMIT && info[1].State == MEM_COMMIT && info[2].State == MEM_RESERVE, + "the two committed by number are committed in the window and the third is not yet"); + check(read_u32(window, 0) == 0 && read_u32(window + kPage64k, 0) == 0, + "pages committed by number read as zero"); + api.map(window, kPages, nullptr); + } + check(api.free_pages(kPages, pages) == TRUE, "XMemFreePhysicalPages frees them"); +} + // The placeholder flags pass through: reserve a placeholder, carve windows and committed memory out of it. void test_placeholders(const PhysicalApi& api) { auto* const base = static_cast( @@ -844,6 +874,7 @@ int main() { if (virtual_alloc && physical.allocate && physical.free_pages && physical.map && physical.scatter) { test_physical_pages(physical); test_physical_pages_commit_on_touch(physical); + test_commit_physical_pages(physical); test_placeholders(physical); } From 228cb9ec6ce51e178d6d656958db013eeec8cf5c Mon Sep 17 00:00:00 2001 From: thibaut Date: Mon, 23 Nov 2026 18:33:50 +0100 Subject: [PATCH 13/23] d3d12: slot 133 imports from the page that holds the address and binds at the offset; uncommitted pages fall back The title places small buffers inside a page too: a 16-byte UAV at a 64-byte-aligned address on an RTX 5090 (found in review), which the import refused with E_INVALIDARG, halting the boot. The import now starts at the page holding the address and the buffer is bound at the offset; an offset off the buffer's alignment takes the ordinary-buffer fallback. A range not fully committed (xmem commits on first touch) also falls back instead of failing. Only a null address or a zero width are E_INVALIDARG. d3d12_existing_heap_test: a buffer 64 bytes into a page reads back the CPU's writes at its own VA; a 1-byte offset and a partly committed range fall back. Co-Authored-By: Claude Opus 5.5 --- runtime/shims/d3d12_vulkan_device.cpp | 43 +++++++++++++---------- runtime/test/d3d12_existing_heap_test.cpp | 24 +++++++------ 2 files changed, 39 insertions(+), 28 deletions(-) diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index f0ed747a07..5224524fda 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -1906,24 +1906,30 @@ class Resource final const VkDeviceSize alignment = device_.info.host_pointer_alignment; if (!device_.get_host_pointer_properties || !alignment) return E_NOTIMPL; const auto start = reinterpret_cast(address); - if (!address || !desc_.Width || (start & (alignment - 1)) || desc_.Width > UINT64_MAX - alignment) - return E_INVALIDARG; - const VkDeviceSize bytes = (desc_.Width + alignment - 1) & ~(alignment - 1); + if (!address || !desc_.Width || desc_.Width > UINT64_MAX - 2 * alignment) return E_INVALIDARG; + // The import starts at the page that holds `address`, and the buffer is bound at the offset inside it: the + // title places small buffers inside a page too (a 16-byte UAV at a 64-byte-aligned address on an RTX 5090, + // found in review), which an import of `address` itself would refuse. + const std::uintptr_t base = start & ~static_cast(alignment - 1); + void* const base_address = reinterpret_cast(base); + const VkDeviceSize offset = start - base; + const VkDeviceSize bytes = (offset + desc_.Width + alignment - 1) & ~(alignment - 1); // The whole imported range must be committed, possibly across several allocations (the retail buffer spans - // three mapped windows): anything else is undefined in Vulkan, so it is E_INVALIDARG here (found in review). - // A write-combined page is not imported: on an RTX 5090 such an import succeeded but GPU reads returned - // wrong bytes (found in review), so it takes the ordinary-buffer fallback instead. - bool write_combined = false; + // three mapped windows); a page not committed yet (xmem commits on first touch) or a write-combined one (on + // an RTX 5090 such an import succeeded but GPU reads returned wrong bytes, found in review) is not imported, + // and the ordinary-buffer fallback answers instead. + bool importable = true; for (VkDeviceSize at = 0; at < bytes;) { MEMORY_BASIC_INFORMATION region{}; - if (!VirtualQuery(static_cast(address) + at, ®ion, sizeof(region)) || - region.State != MEM_COMMIT) - return E_INVALIDARG; - if (region.Protect & (PAGE_WRITECOMBINE | PAGE_NOCACHE)) write_combined = true; + if (!VirtualQuery(static_cast(base_address) + at, ®ion, sizeof(region)) || + region.State != MEM_COMMIT || (region.Protect & (PAGE_WRITECOMBINE | PAGE_NOCACHE))) { + importable = false; + break; + } const auto region_end = reinterpret_cast(region.BaseAddress) + region.RegionSize; - at = region_end - start; + at = region_end - base; } - if (write_combined) return E_NOTIMPL; + if (!importable) return E_NOTIMPL; const bool need_bda = device_.info.buffer_device_address || device_.arena.buffer != VK_NULL_HANDLE; VkExternalMemoryBufferCreateInfo external{VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_BUFFER_CREATE_INFO}; external.handleTypes = VK_EXTERNAL_MEMORY_HANDLE_TYPE_HOST_ALLOCATION_BIT_EXT; @@ -1941,14 +1947,15 @@ class Resource final vk.vkGetBufferMemoryRequirements(device_.info.device, buffer_, &requirements); VkMemoryHostPointerPropertiesEXT host{VK_STRUCTURE_TYPE_MEMORY_HOST_POINTER_PROPERTIES_EXT}; if (device_.get_host_pointer_properties(device_.info.device, - VK_EXTERNAL_MEMORY_HANDLE_TYPE_HOST_ALLOCATION_BIT_EXT, address, + VK_EXTERNAL_MEMORY_HANDLE_TYPE_HOST_ALLOCATION_BIT_EXT, base_address, &host) != VK_SUCCESS) - return E_INVALIDARG; + return E_NOTIMPL; const std::uint32_t types = host.memoryTypeBits & requirements.memoryTypeBits; - if (!types || bytes < requirements.size) return E_NOTIMPL; + // An offset off the buffer's own alignment cannot be bound: the fallback answers. + if (!types || (offset % requirements.alignment) || bytes < offset + requirements.size) return E_NOTIMPL; VkImportMemoryHostPointerInfoEXT import{VK_STRUCTURE_TYPE_IMPORT_MEMORY_HOST_POINTER_INFO_EXT}; import.handleType = VK_EXTERNAL_MEMORY_HANDLE_TYPE_HOST_ALLOCATION_BIT_EXT; - import.pHostPointer = address; + import.pHostPointer = base_address; VkMemoryAllocateFlagsInfo flags{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_FLAGS_INFO, &import}; flags.flags = VK_MEMORY_ALLOCATE_DEVICE_ADDRESS_BIT; // Host-visible and coherent first, as the caller's pages are; then any type both the import and the @@ -1970,7 +1977,7 @@ class Resource final if (memory_) break; } if (!memory_) return E_OUTOFMEMORY; - if (vk.vkBindBufferMemory(device_.info.device, buffer_, memory_, 0) != VK_SUCCESS) return E_OUTOFMEMORY; + if (vk.vkBindBufferMemory(device_.info.device, buffer_, memory_, offset) != VK_SUCCESS) return E_OUTOFMEMORY; mapped_ = address; host_import_ = true; va_ = start; diff --git a/runtime/test/d3d12_existing_heap_test.cpp b/runtime/test/d3d12_existing_heap_test.cpp index 44059575f8..378aa78197 100644 --- a/runtime/test/d3d12_existing_heap_test.cpp +++ b/runtime/test/d3d12_existing_heap_test.cpp @@ -224,9 +224,11 @@ int check_title_placed(ID3D12Device* device, const char* kind, void* pages, UINT texture.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN; Ref refused; EXPECT_HR(rt::d3d12::create_buffer_at_host_address(device, pages, texture, IID_PPV_ARGS(&refused.p)), E_NOTIMPL); - EXPECT_HR(rt::d3d12::create_buffer_at_host_address(device, bytes + 1, desc, IID_PPV_ARGS(&refused.p)), - E_INVALIDARG); EXPECT(refused.p == nullptr); + // An address off the buffer alignment can't be bound inside the import: the ordinary-buffer fallback answers. + Ref fallback; + EXPECT_HR(rt::d3d12::create_buffer_at_host_address(device, bytes + 1, desc, IID_PPV_ARGS(&fallback.p)), S_OK); + EXPECT(fallback->GetGPUVirtualAddress() != reinterpret_cast(bytes + 1)); std::printf("%s: %s, %llu bytes: GPU VA is the address, a GPU copy reads the CPU's writes\n", who, kind, static_cast(size)); return 0; @@ -238,6 +240,9 @@ int check_title_placed_all(ID3D12Device* device) { void* pages = VirtualAlloc(nullptr, size, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); if (!pages) return 1; failures += check_title_placed(device, "VirtualAlloc range", pages, size); + // Inside a page, as the title places small UAV buffers (64-byte aligned, found in review on an RTX 5090): the + // import starts at the page and the buffer is bound at the offset. + failures += check_title_placed(device, "64 bytes into a page", static_cast(pages) + 64, 0x1000 - 64); VirtualFree(pages, 0, MEM_RELEASE); HANDLE section = CreateFileMappingW(INVALID_HANDLE_VALUE, nullptr, PAGE_READWRITE, 0, DWORD(size), nullptr); void* view = section ? MapViewOfFile(section, FILE_MAP_ALL_ACCESS, 0, 0, size) : nullptr; @@ -247,8 +252,8 @@ int check_title_placed_all(ID3D12Device* device) { CloseHandle(section); // Not imported: a write-combined range (an RTX 5090 imported it but read wrong bytes back, found in review) - // falls back to an ordinary buffer, so the resource exists but is not at the pages' address; a range only partly - // committed is E_INVALIDARG. + // falls back to an ordinary buffer, so the resource exists but is not at the pages' address; so does a range only + // partly committed. const char* who = "vulkan slot-133 buffer"; D3D12_RESOURCE_DESC desc{}; desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; @@ -267,14 +272,13 @@ int check_title_placed_all(ID3D12Device* device) { char* partial = static_cast(VirtualAlloc(nullptr, size, MEM_RESERVE, PAGE_READWRITE)); EXPECT(partial != nullptr && VirtualAlloc(partial, size / 2, MEM_COMMIT, PAGE_READWRITE) == partial); { - Ref refused; - EXPECT_HR(rt::d3d12::create_buffer_at_host_address(device, partial, desc, IID_PPV_ARGS(&refused.p)), - E_INVALIDARG); - EXPECT(refused.p == nullptr); + // Pages not committed yet (xmem commits on first touch) are not imported either: the fallback answers. + Ref fallback; + EXPECT_HR(rt::d3d12::create_buffer_at_host_address(device, partial, desc, IID_PPV_ARGS(&fallback.p)), S_OK); + EXPECT(fallback->GetGPUVirtualAddress() != reinterpret_cast(partial)); } VirtualFree(partial, 0, MEM_RELEASE); - std::printf("%s: a write-combined range falls back to an ordinary buffer, a partly committed one is refused\n", - who); + std::printf("%s: a write-combined range and a partly committed one fall back to an ordinary buffer\n", who); return failures; } From 75c2b87a751ca1825caee3fae323cce43c1eb78a Mon Sep 17 00:00:00 2001 From: Logan Date: Mon, 23 Nov 2026 12:37:42 -0500 Subject: [PATCH 14/23] xmem: take the fault lock before reading or changing a mapped page's record unmap_page moved the record out of g_mapped before taking the exclusive lock, so a first-touch fault on that page could read a moved-from section, and map_page made the view live before recording it, so a fault in between was not recognised. unmap_page now holds the exclusive lock from the lookup to the erase, and map_page holds it across mapping the view and recording it. xmem_test adds four threads writing into a window while 256 slices of pages are mapped and unmapped under them. Reported by tupacfan04 in the review of #7556. --- runtime/shims/xmem.cpp | 11 ++----- runtime/test/xmem_test.cpp | 60 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 63 insertions(+), 8 deletions(-) diff --git a/runtime/shims/xmem.cpp b/runtime/shims/xmem.cpp index e97f60f1e3..9665a87664 100644 --- a/runtime/shims/xmem.cpp +++ b/runtime/shims/xmem.cpp @@ -453,19 +453,14 @@ void* WINAPI XMemVirtualAlloc(void* address, SIZE_T size, DWORD allocation_type, // With g_phys_mutex held. Unmaps the page at `address` if one is mapped there; the address becomes a placeholder again. bool unmap_page(uintptr_t address) { + const FaultLockExclusive lock; const auto it = g_mapped.find(address); if (it == g_mapped.end()) return true; - MappedPage mapped = std::move(it->second); - { - const FaultLockExclusive lock; - g_mapped.erase(it); - } if (!placeholder_api().unmap_view2(GetCurrentProcess(), reinterpret_cast(address), MEM_PRESERVE_PLACEHOLDER)) { - const FaultLockExclusive lock; - g_mapped.emplace(address, std::move(mapped)); return false; } + g_mapped.erase(it); return true; } @@ -481,11 +476,11 @@ bool map_page(uintptr_t address, uint64_t page, DWORD protect) { } void* const target = reinterpret_cast(address); if (!isolate_placeholder(target, kPhysicalPageSize)) return false; + const FaultLockExclusive lock; void* const view = placeholder_api().map_view3(it->second.section->handle, GetCurrentProcess(), target, it->second.offset, kPhysicalPageSize, MEM_REPLACE_PLACEHOLDER, protect, nullptr, 0); if (!view) return false; - const FaultLockExclusive lock; g_mapped[address] = MappedPage{page, it->second.section, it->second.offset}; return true; } diff --git a/runtime/test/xmem_test.cpp b/runtime/test/xmem_test.cpp index a47e43bfd1..4ea7770077 100644 --- a/runtime/test/xmem_test.cpp +++ b/runtime/test/xmem_test.cpp @@ -11,6 +11,7 @@ #include #include +#include #include #include #include @@ -18,6 +19,7 @@ #include #include #include +#include #include #include "shims.h" @@ -595,6 +597,63 @@ void test_commit_physical_pages(const PhysicalApi& api) { check(api.free_pages(kPages, pages) == TRUE, "XMemFreePhysicalPages frees them"); } +void test_first_touch_during_remap(const PhysicalApi& api) { + constexpr uint64_t kSlice = 16; + constexpr uint64_t kSlices = 256; + std::vector pages(kSlice * kSlices); + uint64_t count = pages.size(); + check(api.allocate(0x280, &count, pages.data()) == TRUE && count == pages.size(), + "4,096 physical pages for the remap race"); + if (count != pages.size()) return; + auto* const window = static_cast( + api.virtual_alloc(nullptr, kSlice * kPage64k, MEM_RESERVE | kXmem64kPages, 0x21, PAGE_READWRITE)); + check(window != nullptr, "XMemVirtualAlloc reserves a window for the remap race"); + if (!window) { + api.free_pages(count, pages.data()); + return; + } + std::atomic stop{false}; + std::atomic touches{0}; + std::atomic unmapped_faults{0}; + std::vector writers; + for (int t = 0; t < 4; ++t) { + writers.emplace_back([&, t] { + uint64_t i = static_cast(t); + while (!stop.load(std::memory_order_relaxed)) { + auto* const word = + static_cast(static_cast(window + (i % kSlice) * kPage64k)) + t; + if (access_faults(word, true)) { + unmapped_faults.fetch_add(1, std::memory_order_relaxed); + } else { + touches.fetch_add(1, std::memory_order_relaxed); + } + ++i; + } + }); + } + const ULONGLONG started = GetTickCount64(); + bool remapped = true; + for (uint64_t s = 0; s < kSlices; ++s) { + remapped &= api.map(window, kSlice, pages.data() + s * kSlice) == window; + Sleep(0); + remapped &= api.map(window, kSlice, nullptr) == window; + } + remapped &= api.map(window, kSlice, pages.data() + (kSlices - 1) * kSlice) == window; + stop.store(true); + for (auto& writer : writers) writer.join(); + const ULONGLONG elapsed = GetTickCount64() - started; + check(remapped, "256 slices map and unmap while 4 threads write into the window"); + check(elapsed < 30000, "first-touch faults during map and unmap finish without hanging"); + check(touches.load() > 0, "writes land while the pages are mapped"); + std::printf("remap race: %llu writes landed, %llu hit an unmapped page, %llu ms\n", + static_cast(touches.load()), + static_cast(unmapped_faults.load()), static_cast(elapsed)); + static_cast(static_cast(window))[8] = 0x600dcafe; + check(read_u32(window, 32) == 0x600dcafe, "the last slice is still mapped and writable"); + api.map(window, kSlice, nullptr); + check(api.free_pages(count, pages.data()) == TRUE, "XMemFreePhysicalPages frees the remap race pages"); +} + // The placeholder flags pass through: reserve a placeholder, carve windows and committed memory out of it. void test_placeholders(const PhysicalApi& api) { auto* const base = static_cast( @@ -875,6 +934,7 @@ int main() { test_physical_pages(physical); test_physical_pages_commit_on_touch(physical); test_commit_physical_pages(physical); + test_first_touch_during_remap(physical); test_placeholders(physical); } From 4fb24d2faaa86e7287fa7da2670f54ea89e80fce Mon Sep 17 00:00:00 2001 From: thibaut Date: Mon, 23 Nov 2026 18:37:44 +0100 Subject: [PATCH 15/23] d3d12: a texture at slot 133 gets an ordinary committed texture instead of E_NOTIMPL The retail title places textures at slot 133 too, and asserted on the E_NOTIMPL (found in review). A texture now gets an ordinary committed DEFAULT texture of the same description, as slot 76 gives one, logged once; it is not on the title's pages. The proxy rewrites a texture's Xbox layout word to UNKNOWN (a buffer's to ROW_MAJOR), as slot 76 does. Co-Authored-By: Claude Opus 5.5 --- runtime/shims/d3d12_vulkan_device.cpp | 11 +++++++++-- runtime/shims/d3d12_xs_device.cpp | 5 ++++- runtime/test/d3d12_existing_heap_test.cpp | 7 ++++--- 3 files changed, 17 insertions(+), 6 deletions(-) diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index 5224524fda..415844882d 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -6943,8 +6943,15 @@ class Device final HRESULT create_at_host_address(void* address, const D3D12_RESOURCE_DESC& desc, REFIID riid, void** out) { constexpr auto method = "Xbox CreatePlacedResourceX (device slot 133)"; if (desc.Dimension != D3D12_RESOURCE_DIMENSION_BUFFER) { - log_once("a title-placed texture (device slot 133) is not supported yet; dimension", int(desc.Dimension)); - return d3d12_trace::result(method, E_NOTIMPL); + // A texture is not placed on the title's pages yet: it gets an ordinary committed DEFAULT texture of the + // same description, as slot 76 gives one, so the title has its resource instead of asserting (found in + // review). What the title writes at `address` does not reach it. + log_once("a title-placed texture (device slot 133) is an ordinary committed texture, not the title's pages; " + "dimension", + int(desc.Dimension)); + const D3D12_HEAP_PROPERTIES fallback{D3D12_HEAP_TYPE_DEFAULT}; + return d3d12_trace::result(method, create_committed(&fallback, D3D12_HEAP_FLAG_NONE, &desc, + D3D12_RESOURCE_STATE_COMMON, 0, nullptr, riid, out)); } D3D12_HEAP_PROPERTIES heap{}; heap.Type = D3D12_HEAP_TYPE_CUSTOM; diff --git a/runtime/shims/d3d12_xs_device.cpp b/runtime/shims/d3d12_xs_device.cpp index b565fdd4d2..fe8b3896b4 100644 --- a/runtime/shims/d3d12_xs_device.cpp +++ b/runtime/shims/d3d12_xs_device.cpp @@ -1509,7 +1509,10 @@ HRESULT proxy_create_placed_resource_x(DeviceProxy* self, void* va, const D3D12_ D3D12_RESOURCE_DESC pc_desc = *xbox_desc; const auto xbox_flags = static_cast(pc_desc.Flags); pc_desc.Flags = static_cast(xbox_flags & kPcResourceFlags); - if (pc_desc.Dimension == D3D12_RESOURCE_DIMENSION_BUFFER) pc_desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + // The Xbox layout word (0x101 tiled, 0x1 row-major buffer) is no PC layout: ROW_MAJOR for a buffer and UNKNOWN + // for everything else, as slot 76 does. + pc_desc.Layout = pc_desc.Dimension == D3D12_RESOURCE_DIMENSION_BUFFER ? D3D12_TEXTURE_LAYOUT_ROW_MAJOR + : D3D12_TEXTURE_LAYOUT_UNKNOWN; static std::atomic logged{false}; if (!logged.exchange(true, std::memory_order_relaxed)) { std::fprintf(stderr, diff --git a/runtime/test/d3d12_existing_heap_test.cpp b/runtime/test/d3d12_existing_heap_test.cpp index 378aa78197..7c10803ebf 100644 --- a/runtime/test/d3d12_existing_heap_test.cpp +++ b/runtime/test/d3d12_existing_heap_test.cpp @@ -222,9 +222,10 @@ int check_title_placed(ID3D12Device* device, const char* kind, void* pages, UINT texture.Width = texture.Height = 64; texture.Format = DXGI_FORMAT_R8G8B8A8_UNORM; texture.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN; - Ref refused; - EXPECT_HR(rt::d3d12::create_buffer_at_host_address(device, pages, texture, IID_PPV_ARGS(&refused.p)), E_NOTIMPL); - EXPECT(refused.p == nullptr); + // A texture isn't placed on the pages yet: the title gets an ordinary committed texture instead of a refusal. + Ref placed_texture; + EXPECT_HR(rt::d3d12::create_buffer_at_host_address(device, pages, texture, IID_PPV_ARGS(&placed_texture.p)), S_OK); + EXPECT(placed_texture.p != nullptr && placed_texture->GetDesc().Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE2D); // An address off the buffer alignment can't be bound inside the import: the ordinary-buffer fallback answers. Ref fallback; EXPECT_HR(rt::d3d12::create_buffer_at_host_address(device, bytes + 1, desc, IID_PPV_ARGS(&fallback.p)), S_OK); From af75a43dc9376a3bf5cbd9ab5d7e09936c68cb11 Mon Sep 17 00:00:00 2001 From: Logan Date: Mon, 23 Nov 2026 12:48:20 -0500 Subject: [PATCH 16/23] xmem: judge a fault on a committed page by the protection at the faulting address The handler queried the protection at the start of the 64 KiB page, so a write to a 4 KiB part the title had made read-only looked allowed and was resumed, faulting again forever instead of reaching the title's own handler. It now looks the record up by the page and the protection up by the faulting address. xmem_test writes to a read-only 4 KiB part of a read-write page and expects the fault. --- runtime/shims/xmem.cpp | 13 +++++++------ runtime/test/xmem_test.cpp | 6 ++++++ 2 files changed, 13 insertions(+), 6 deletions(-) diff --git a/runtime/shims/xmem.cpp b/runtime/shims/xmem.cpp index 9665a87664..1e286d7120 100644 --- a/runtime/shims/xmem.cpp +++ b/runtime/shims/xmem.cpp @@ -487,11 +487,11 @@ bool map_page(uintptr_t address, uint64_t page, DWORD protect) { enum class PageCommit { not_ours, committed_before, committed_now, failed }; -PageCommit commit_mapped_page(uintptr_t address, DWORD& protect) { +PageCommit commit_mapped_page(uintptr_t address, uintptr_t accessed, DWORD& protect) { const auto it = g_mapped.find(address); if (it == g_mapped.end() || !it->second.section->scratch) return PageCommit::not_ours; MEMORY_BASIC_INFORMATION info{}; - if (!VirtualQuery(reinterpret_cast(address), &info, sizeof(info)) || info.Type != MEM_MAPPED) { + if (!VirtualQuery(reinterpret_cast(accessed), &info, sizeof(info)) || info.Type != MEM_MAPPED) { return PageCommit::not_ours; } if (info.State == MEM_COMMIT) { @@ -530,13 +530,13 @@ LONG CALLBACK physical_page_fault(EXCEPTION_POINTERS* info) { return EXCEPTION_CONTINUE_SEARCH; } busy = true; - const uintptr_t address = - static_cast(record->ExceptionInformation[1]) & ~static_cast(kPhysicalPageSize - 1); + const uintptr_t accessed = static_cast(record->ExceptionInformation[1]); + const uintptr_t address = accessed & ~static_cast(kPhysicalPageSize - 1); DWORD protect = 0; PageCommit result; { const FaultLockShared lock; - result = commit_mapped_page(address, protect); + result = commit_mapped_page(address, accessed, protect); } busy = false; if (result == PageCommit::committed_now) return EXCEPTION_CONTINUE_EXECUTION; @@ -812,7 +812,8 @@ bool commit_physical_range(const void* address, size_t size) { const FaultLockShared lock; for (uintptr_t i = 0; i < pages; ++i) { DWORD protect = 0; - if (commit_mapped_page(first + i * kPhysicalPageSize, protect) == PageCommit::failed) return false; + const uintptr_t page = first + i * kPhysicalPageSize; + if (commit_mapped_page(page, page, protect) == PageCommit::failed) return false; } return true; } diff --git a/runtime/test/xmem_test.cpp b/runtime/test/xmem_test.cpp index 4ea7770077..3ec621b0b4 100644 --- a/runtime/test/xmem_test.cpp +++ b/runtime/test/xmem_test.cpp @@ -530,6 +530,12 @@ void test_physical_pages_commit_on_touch(const PhysicalApi& api) { access_faults(static_cast(static_cast(window)), true), "a write to a committed read-only page still faults to the next handler"); VirtualProtect(window, kPage64k, PAGE_READWRITE, &old); + check(VirtualProtect(window + 4096, 4096, PAGE_READONLY, &old) != FALSE && + access_faults(static_cast(static_cast(window + 4096)), true), + "a write to a read-only 4 KiB part of a read-write page still faults to the next handler"); + check(!access_faults(static_cast(static_cast(window + 8192)), true), + "the rest of that page stays writable"); + VirtualProtect(window + 4096, 4096, PAGE_READWRITE, &old); void* const elsewhere = VirtualAlloc(nullptr, kPage64k, MEM_RESERVE, PAGE_READWRITE); check(elsewhere != nullptr && access_faults(static_cast(elsewhere), false), "a fault outside the mapped pages still reaches the next handler"); From 6545c9c5305b8839a9fbe596b33b1ae90222fec7 Mon Sep 17 00:00:00 2001 From: Giovanni Lion Date: Tue, 24 Nov 2026 02:01:53 +0800 Subject: [PATCH 17/23] tests: check reported cache protection in existing-heap fixture Wine can report a requested write-combined allocation as ordinary read/write memory. Check the observed protection and retain the fallback expectation when a cache modifier is present; otherwise verify the read/write import. Add PAGE_NOCACHE to keep the unsafe-protection guard covered under Wine. Claim: https://github.com/ItsNotRexed/Leonida/issues/7913#issuecomment-7109390728 Depends on: #7218 AI-assisted: Codex --- runtime/test/d3d12_existing_heap_test.cpp | 35 ++++++++++++++++------- 1 file changed, 24 insertions(+), 11 deletions(-) diff --git a/runtime/test/d3d12_existing_heap_test.cpp b/runtime/test/d3d12_existing_heap_test.cpp index 7c10803ebf..db07be90c3 100644 --- a/runtime/test/d3d12_existing_heap_test.cpp +++ b/runtime/test/d3d12_existing_heap_test.cpp @@ -252,9 +252,9 @@ int check_title_placed_all(ID3D12Device* device) { UnmapViewOfFile(view); CloseHandle(section); - // Not imported: a write-combined range (an RTX 5090 imported it but read wrong bytes back, found in review) - // falls back to an ordinary buffer, so the resource exists but is not at the pages' address; so does a range only - // partly committed. + // Cache-modified ranges are not imported (WC imports read wrong bytes on an RTX 5090 in review). Some Wine + // versions report a requested WC allocation as plain read-write memory; check the protection actually supplied. + // PAGE_NOCACHE also exercises the fallback on those hosts, rather than dropping the cache-protection check. const char* who = "vulkan slot-133 buffer"; D3D12_RESOURCE_DESC desc{}; desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; @@ -262,14 +262,27 @@ int check_title_placed_all(ID3D12Device* device) { desc.Height = desc.DepthOrArraySize = desc.MipLevels = 1; desc.SampleDesc.Count = 1; desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; - void* combined = VirtualAlloc(nullptr, size, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE | PAGE_WRITECOMBINE); - EXPECT(combined != nullptr); - { - Ref fallback; - EXPECT_HR(rt::d3d12::create_buffer_at_host_address(device, combined, desc, IID_PPV_ARGS(&fallback.p)), S_OK); - EXPECT(fallback->GetGPUVirtualAddress() != reinterpret_cast(combined)); + for (DWORD modifier : {DWORD(PAGE_WRITECOMBINE), DWORD(PAGE_NOCACHE)}) { + void* pages = VirtualAlloc(nullptr, size, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE | modifier); + EXPECT(pages != nullptr); + MEMORY_BASIC_INFORMATION region{}; + EXPECT(VirtualQuery(pages, ®ion, sizeof(region)) == sizeof(region)); + const bool cache_modified = (region.Protect & (PAGE_WRITECOMBINE | PAGE_NOCACHE)) != 0; + { + Ref buffer; + EXPECT_HR(rt::d3d12::create_buffer_at_host_address(device, pages, desc, IID_PPV_ARGS(&buffer.p)), S_OK); + if (cache_modified) { + EXPECT(buffer->GetGPUVirtualAddress() != reinterpret_cast(pages)); + } else { + EXPECT(region.Protect == PAGE_READWRITE); + EXPECT(buffer->GetGPUVirtualAddress() == reinterpret_cast(pages)); + } + } + std::printf("%s: cache modifier 0x%lx, reported protection 0x%lx: %s\n", who, modifier, region.Protect, + cache_modified ? "ordinary-buffer fallback verified" + : "modifier not reported; read-write import verified"); + VirtualFree(pages, 0, MEM_RELEASE); } - VirtualFree(combined, 0, MEM_RELEASE); char* partial = static_cast(VirtualAlloc(nullptr, size, MEM_RESERVE, PAGE_READWRITE)); EXPECT(partial != nullptr && VirtualAlloc(partial, size / 2, MEM_COMMIT, PAGE_READWRITE) == partial); { @@ -279,7 +292,7 @@ int check_title_placed_all(ID3D12Device* device) { EXPECT(fallback->GetGPUVirtualAddress() != reinterpret_cast(partial)); } VirtualFree(partial, 0, MEM_RELEASE); - std::printf("%s: a write-combined range and a partly committed one fall back to an ordinary buffer\n", who); + std::printf("%s: a partly committed range falls back to an ordinary buffer\n", who); return failures; } From e85ebec7d438b111b14a1355e2c42c3d193a68d4 Mon Sep 17 00:00:00 2001 From: Logan Date: Mon, 23 Nov 2026 13:04:13 -0500 Subject: [PATCH 18/23] xmem_test: build with /EHa under clang-cl The commit-on-touch checks expect hardware faults from plain loads and stores inside __try. MSVC catches those as it is; clang-cl only with asynchronous exceptions, so without /EHa the expected fault escaped and xmem_test crashed. Same option as tiny_dll. Reported by AirKyzzZ in #7556. --- runtime/CMakeLists.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index 0d9b03f20f..2fd565cb0b 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -208,7 +208,7 @@ if(WIN32 AND LEONIDA_BUILD_WINDOWS_RUNTIME) ) target_include_directories(xmem_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/shims) target_compile_definitions(xmem_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(xmem_test PRIVATE /W4 /permissive- /utf-8) + target_compile_options(xmem_test PRIVATE /W4 /permissive- /utf-8 $<$:/EHa>) target_link_options(xmem_test PRIVATE /OPT:NOREF) target_link_libraries(xmem_test PRIVATE psapi) From a3eae955dcec4fb65864ca6c10b4ca3f2999c2d3 Mon Sep 17 00:00:00 2001 From: thibaut Date: Mon, 23 Nov 2026 19:10:29 +0100 Subject: [PATCH 19/23] d3d12: slot 133's third argument is a barrier layout; a placed texture starts in the matching state The title's third word at slot 133 is a D3D12_BARRIER_LAYOUT, not a resource state (measured by @dracbat on a retail boot: 0x6 SHADER_RESOURCE for its RT/DS textures, 0x3 UNORDERED_ACCESS for its RT+UAV ones, 0xFFFFFFFF UNDEFINED for the 182 MiB buffer), as PC CreatePlacedResource2 takes it. The proxy passes it to the handler, and a texture's ordinary committed fallback starts in the equivalent legacy state (UNDEFINED and unlisted values give COMMON; a state the description refuses retries with COMMON, so the title always gets its resource). Buffers are unchanged. Co-Authored-By: Claude Opus 5.5 --- runtime/shims/d3d12_com.h | 2 +- runtime/shims/d3d12_vulkan_device.cpp | 35 +++++++++++++++++++---- runtime/shims/d3d12_xs_device.cpp | 2 +- runtime/shims/d3d12_xs_device.h | 6 ++-- runtime/test/d3d12_existing_heap_test.cpp | 10 +++---- runtime/test/xs_proxy_mock_test.cpp | 7 +++-- 6 files changed, 46 insertions(+), 16 deletions(-) diff --git a/runtime/shims/d3d12_com.h b/runtime/shims/d3d12_com.h index c131c41d49..14ead7b24f 100644 --- a/runtime/shims/d3d12_com.h +++ b/runtime/shims/d3d12_com.h @@ -228,7 +228,7 @@ bool device_supports_ray_tracing(ID3D12Device* device); // what the GPU reads. A buffer description only; E_NOTIMPL on a device that is not the Vulkan layer, without the // extension, or for a texture. HRESULT create_buffer_at_host_address(ID3D12Device* device, void* address, const D3D12_RESOURCE_DESC& desc, - REFIID riid, void** out); + std::uint32_t layout, REFIID riid, void** out); // The VkAccelerationStructureKHR registered for `va` on `device`, or VK_NULL_HANDLE. For tests. VkAccelerationStructureKHR vulkan_acceleration_structure(ID3D12Device* device, D3D12_GPU_VIRTUAL_ADDRESS va); diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index f40fba78b3..2a463e1f83 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -6944,7 +6944,26 @@ class Device final // create_buffer_at_host_address (Xbox device slot 133). The heap the resource reports is CUSTOM / WRITE_BACK / L0, // what OpenExistingHeapFromAddress gives the same pages, since the CPU keeps writing them. - HRESULT create_at_host_address(void* address, const D3D12_RESOURCE_DESC& desc, REFIID riid, void** out) { + // A D3D12_BARRIER_LAYOUT (what Xbox slot 133 passes, as PC CreatePlacedResource2 does) as the legacy initial state + // of an equivalent committed resource. UNDEFINED (0xFFFFFFFF) and anything unlisted give COMMON. + static D3D12_RESOURCE_STATES state_for_barrier_layout(std::uint32_t layout) { + switch (layout) { + case 1: return D3D12_RESOURCE_STATE_GENERIC_READ; + case 2: return D3D12_RESOURCE_STATE_RENDER_TARGET; + case 3: return D3D12_RESOURCE_STATE_UNORDERED_ACCESS; + case 4: return D3D12_RESOURCE_STATE_DEPTH_WRITE; + case 5: return D3D12_RESOURCE_STATE_DEPTH_READ; + case 6: return D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE | D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE; + case 7: return D3D12_RESOURCE_STATE_COPY_SOURCE; + case 8: return D3D12_RESOURCE_STATE_COPY_DEST; + case 9: return D3D12_RESOURCE_STATE_RESOLVE_SOURCE; + case 10: return D3D12_RESOURCE_STATE_RESOLVE_DEST; + default: return D3D12_RESOURCE_STATE_COMMON; + } + } + + HRESULT create_at_host_address(void* address, const D3D12_RESOURCE_DESC& desc, std::uint32_t layout, REFIID riid, + void** out) { constexpr auto method = "Xbox CreatePlacedResourceX (device slot 133)"; if (desc.Dimension != D3D12_RESOURCE_DIMENSION_BUFFER) { // A texture is not placed on the title's pages yet: it gets an ordinary committed DEFAULT texture of the @@ -6953,9 +6972,15 @@ class Device final log_once("a title-placed texture (device slot 133) is an ordinary committed texture, not the title's pages; " "dimension", int(desc.Dimension)); + // The initial state follows the title's barrier layout (slot 133's third argument, measured by + // @dracbat); a state the description refuses (or UNDEFINED) gives COMMON, so the title still gets it. const D3D12_HEAP_PROPERTIES fallback{D3D12_HEAP_TYPE_DEFAULT}; - return d3d12_trace::result(method, create_committed(&fallback, D3D12_HEAP_FLAG_NONE, &desc, - D3D12_RESOURCE_STATE_COMMON, 0, nullptr, riid, out)); + const D3D12_RESOURCE_STATES initial = state_for_barrier_layout(layout); + HRESULT hr = create_committed(&fallback, D3D12_HEAP_FLAG_NONE, &desc, initial, 0, nullptr, riid, out); + if (FAILED(hr) && initial != D3D12_RESOURCE_STATE_COMMON) + hr = create_committed(&fallback, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COMMON, 0, nullptr, + riid, out); + return d3d12_trace::result(method, hr); } D3D12_HEAP_PROPERTIES heap{}; heap.Type = D3D12_HEAP_TYPE_CUSTOM; @@ -8641,13 +8666,13 @@ const VulkanDeviceInfo* vulkan_device_info(ID3D12Device* device) { } HRESULT create_buffer_at_host_address(ID3D12Device* device, void* address, const D3D12_RESOURCE_DESC& desc, - REFIID riid, void** out) { + std::uint32_t layout, REFIID riid, void** out) { if (out) *out = nullptr; if (!device || !out) return E_POINTER; ID3D12Device* real = rt::d3d12_xs::device_proxy_real_device(device); auto* d = Device::from(real ? real : device); if (!d) return E_NOTIMPL; - return d->create_at_host_address(address, desc, riid, out); + return d->create_at_host_address(address, desc, layout, riid, out); } bool device_supports_ray_tracing(ID3D12Device* device) { diff --git a/runtime/shims/d3d12_xs_device.cpp b/runtime/shims/d3d12_xs_device.cpp index fe8b3896b4..1244ac3515 100644 --- a/runtime/shims/d3d12_xs_device.cpp +++ b/runtime/shims/d3d12_xs_device.cpp @@ -1521,7 +1521,7 @@ HRESULT proxy_create_placed_resource_x(DeviceProxy* self, void* va, const D3D12_ va, static_cast(pc_desc.Dimension), static_cast(pc_desc.Width), xbox_flags, state); } - return handler(self->real, va, pc_desc, *riid, out); + return handler(self->real, va, pc_desc, state, *riid, out); } template diff --git a/runtime/shims/d3d12_xs_device.h b/runtime/shims/d3d12_xs_device.h index f5fb37b163..1fc08dbdea 100644 --- a/runtime/shims/d3d12_xs_device.h +++ b/runtime/shims/d3d12_xs_device.h @@ -93,8 +93,10 @@ ID3D12Device* device_proxy_real_device(const void* device); // not create it itself: the device behind it does, through this handler, which the Vulkan layer registers // (rt::d3d12::create_buffer_at_host_address). With none registered, or a PC device behind the proxy, the slot // answers E_NOTIMPL. -using PlacedAtVaHandler = HRESULT (*)(ID3D12Device* real, void* va, const D3D12_RESOURCE_DESC& desc, REFIID riid, - void** out); +// `layout` is the title's third argument, a D3D12_BARRIER_LAYOUT (0xFFFFFFFF = UNDEFINED), measured on a retail +// boot: 0x6 SHADER_RESOURCE, 0x3 UNORDERED_ACCESS, as PC CreatePlacedResource2 takes it. +using PlacedAtVaHandler = HRESULT (*)(ID3D12Device* real, void* va, const D3D12_RESOURCE_DESC& desc, + std::uint32_t layout, REFIID riid, void** out); void set_placed_at_va_handler(PlacedAtVaHandler handler); // True for slots the proxy handles itself rather than forwarding verbatim: IUnknown (0-2), 8 and 75 (queue diff --git a/runtime/test/d3d12_existing_heap_test.cpp b/runtime/test/d3d12_existing_heap_test.cpp index db07be90c3..04900226a1 100644 --- a/runtime/test/d3d12_existing_heap_test.cpp +++ b/runtime/test/d3d12_existing_heap_test.cpp @@ -182,7 +182,7 @@ int check_title_placed(ID3D12Device* device, const char* kind, void* pages, UINT desc.SampleDesc.Count = 1; desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; Ref buffer; - EXPECT_HR(rt::d3d12::create_buffer_at_host_address(device, pages, desc, IID_PPV_ARGS(&buffer.p)), S_OK); + EXPECT_HR(rt::d3d12::create_buffer_at_host_address(device, pages, desc, 0xFFFFFFFFu, IID_PPV_ARGS(&buffer.p)), S_OK); EXPECT(buffer->GetGPUVirtualAddress() == reinterpret_cast(pages)); auto* bytes = static_cast(pages); for (UINT64 i = 0; i < size; ++i) bytes[i] = static_cast(i * 131u + 7u); @@ -224,11 +224,11 @@ int check_title_placed(ID3D12Device* device, const char* kind, void* pages, UINT texture.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN; // A texture isn't placed on the pages yet: the title gets an ordinary committed texture instead of a refusal. Ref placed_texture; - EXPECT_HR(rt::d3d12::create_buffer_at_host_address(device, pages, texture, IID_PPV_ARGS(&placed_texture.p)), S_OK); + EXPECT_HR(rt::d3d12::create_buffer_at_host_address(device, pages, texture, 0x6u, IID_PPV_ARGS(&placed_texture.p)), S_OK); EXPECT(placed_texture.p != nullptr && placed_texture->GetDesc().Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE2D); // An address off the buffer alignment can't be bound inside the import: the ordinary-buffer fallback answers. Ref fallback; - EXPECT_HR(rt::d3d12::create_buffer_at_host_address(device, bytes + 1, desc, IID_PPV_ARGS(&fallback.p)), S_OK); + EXPECT_HR(rt::d3d12::create_buffer_at_host_address(device, bytes + 1, desc, 0xFFFFFFFFu, IID_PPV_ARGS(&fallback.p)), S_OK); EXPECT(fallback->GetGPUVirtualAddress() != reinterpret_cast(bytes + 1)); std::printf("%s: %s, %llu bytes: GPU VA is the address, a GPU copy reads the CPU's writes\n", who, kind, static_cast(size)); @@ -270,7 +270,7 @@ int check_title_placed_all(ID3D12Device* device) { const bool cache_modified = (region.Protect & (PAGE_WRITECOMBINE | PAGE_NOCACHE)) != 0; { Ref buffer; - EXPECT_HR(rt::d3d12::create_buffer_at_host_address(device, pages, desc, IID_PPV_ARGS(&buffer.p)), S_OK); + EXPECT_HR(rt::d3d12::create_buffer_at_host_address(device, pages, desc, 0xFFFFFFFFu, IID_PPV_ARGS(&buffer.p)), S_OK); if (cache_modified) { EXPECT(buffer->GetGPUVirtualAddress() != reinterpret_cast(pages)); } else { @@ -288,7 +288,7 @@ int check_title_placed_all(ID3D12Device* device) { { // Pages not committed yet (xmem commits on first touch) are not imported either: the fallback answers. Ref fallback; - EXPECT_HR(rt::d3d12::create_buffer_at_host_address(device, partial, desc, IID_PPV_ARGS(&fallback.p)), S_OK); + EXPECT_HR(rt::d3d12::create_buffer_at_host_address(device, partial, desc, 0xFFFFFFFFu, IID_PPV_ARGS(&fallback.p)), S_OK); EXPECT(fallback->GetGPUVirtualAddress() != reinterpret_cast(partial)); } VirtualFree(partial, 0, MEM_RELEASE); diff --git a/runtime/test/xs_proxy_mock_test.cpp b/runtime/test/xs_proxy_mock_test.cpp index f7dbd407f0..b99e14826d 100644 --- a/runtime/test/xs_proxy_mock_test.cpp +++ b/runtime/test/xs_proxy_mock_test.cpp @@ -392,9 +392,11 @@ int check_levels() { static void* seen_va = nullptr; static D3D12_RESOURCE_DESC seen_desc{}; static GUID seen_iid{}; + static std::uint32_t seen_layout = 0; const xs::PlacedAtVaHandler handler = [](ID3D12Device* real_device, void* va, - const D3D12_RESOURCE_DESC& desc, REFIID iid, - void** out) -> HRESULT { + const D3D12_RESOURCE_DESC& desc, std::uint32_t layout, + REFIID iid, void** out) -> HRESULT { + seen_layout = layout; seen_real = real_device; seen_va = va; seen_desc = desc; @@ -421,6 +423,7 @@ int check_levels() { EXPECT(static_cast(seen_desc.Flags) == 0x4); EXPECT(seen_desc.Layout == D3D12_TEXTURE_LAYOUT_ROW_MAJOR && seen_desc.Width == 0x10000); EXPECT(std::memcmp(&seen_iid, &resource_iid, sizeof(GUID)) == 0); + EXPECT(seen_layout == 0xFFFFFFFFu); // the title's third word, passed through as the barrier layout EXPECT(xs::device_slot_overridden(133)); } From df62408b84b4bdb811b3c975c5c9aa5386982131 Mon Sep 17 00:00:00 2001 From: thibaut Date: Mon, 23 Nov 2026 20:48:47 +0100 Subject: [PATCH 20/23] d3d12_existing_heap_test: a driver may refuse the section-view import (RADV userptr is anonymous-only) RADV imports host memory through amdgpu userptr, which libdrm creates anonymous-only, so it refuses a view of a pagefile-backed section with EPERM (RX 9060 XT under Wine, found in review), and the layer answers with its fallback as designed. The section-view case now accepts that outcome and checks the fallback resource exists; NVIDIA and AMD's Windows driver still import it, and the readback is still checked there. Co-Authored-By: Claude Opus 5.5 --- runtime/test/d3d12_existing_heap_test.cpp | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/runtime/test/d3d12_existing_heap_test.cpp b/runtime/test/d3d12_existing_heap_test.cpp index 04900226a1..110bedd851 100644 --- a/runtime/test/d3d12_existing_heap_test.cpp +++ b/runtime/test/d3d12_existing_heap_test.cpp @@ -173,7 +173,11 @@ int check_import(ID3D12Device* device, bool supported) { // pattern is written after the buffer exists and read back through a READBACK buffer. Checked on a VirtualAlloc range // and on a view of a pagefile-backed section, the form xmem's physical pages are mapped in. A texture is E_NOTIMPL // and an address off the import alignment E_INVALIDARG. -int check_title_placed(ID3D12Device* device, const char* kind, void* pages, UINT64 size) { +// `may_refuse`: the driver is allowed to refuse importing these pages, and the layer then answers with its fallback. +// RADV imports host memory through amdgpu userptr, which takes anonymous memory only, so it refuses a view of a +// pagefile-backed section with EPERM (measured on an RX 9060 XT under Wine, found in review), while NVIDIA and +// AMD's Windows driver import it. The fallback is checked to exist; the readback below needs the import. +int check_title_placed(ID3D12Device* device, const char* kind, void* pages, UINT64 size, bool may_refuse = false) { const char* who = "vulkan slot-133 buffer"; D3D12_RESOURCE_DESC desc{}; desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; @@ -183,6 +187,11 @@ int check_title_placed(ID3D12Device* device, const char* kind, void* pages, UINT desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; Ref buffer; EXPECT_HR(rt::d3d12::create_buffer_at_host_address(device, pages, desc, 0xFFFFFFFFu, IID_PPV_ARGS(&buffer.p)), S_OK); + if (may_refuse && buffer->GetGPUVirtualAddress() != reinterpret_cast(pages)) { + std::printf("%s: %s, %llu bytes: this driver refused the import; the fallback resource answered\n", who, kind, + static_cast(size)); + return 0; + } EXPECT(buffer->GetGPUVirtualAddress() == reinterpret_cast(pages)); auto* bytes = static_cast(pages); for (UINT64 i = 0; i < size; ++i) bytes[i] = static_cast(i * 131u + 7u); @@ -248,7 +257,7 @@ int check_title_placed_all(ID3D12Device* device) { HANDLE section = CreateFileMappingW(INVALID_HANDLE_VALUE, nullptr, PAGE_READWRITE, 0, DWORD(size), nullptr); void* view = section ? MapViewOfFile(section, FILE_MAP_ALL_ACCESS, 0, 0, size) : nullptr; if (!view) return failures + 1; - failures += check_title_placed(device, "section view", view, size); + failures += check_title_placed(device, "section view", view, size, /*may_refuse=*/true); UnmapViewOfFile(view); CloseHandle(section); From 1d4d2952e8d0d66152282e272d719e6d56ac6049 Mon Sep 17 00:00:00 2001 From: thibaut Date: Mon, 23 Nov 2026 21:06:13 +0100 Subject: [PATCH 21/23] d3d12_existing_heap_test: the cache-modifier loop's buffer no longer hides the function's pages (C4456) Found in review under MSVC /W4: the loop's local 'pages' shadowed the function's own. Renamed to cached_pages; no behaviour change. Co-Authored-By: Claude Opus 5.5 --- runtime/test/d3d12_existing_heap_test.cpp | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/runtime/test/d3d12_existing_heap_test.cpp b/runtime/test/d3d12_existing_heap_test.cpp index 110bedd851..14b6ae3f41 100644 --- a/runtime/test/d3d12_existing_heap_test.cpp +++ b/runtime/test/d3d12_existing_heap_test.cpp @@ -272,25 +272,25 @@ int check_title_placed_all(ID3D12Device* device) { desc.SampleDesc.Count = 1; desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; for (DWORD modifier : {DWORD(PAGE_WRITECOMBINE), DWORD(PAGE_NOCACHE)}) { - void* pages = VirtualAlloc(nullptr, size, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE | modifier); - EXPECT(pages != nullptr); + void* cached_pages = VirtualAlloc(nullptr, size, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE | modifier); + EXPECT(cached_pages != nullptr); MEMORY_BASIC_INFORMATION region{}; - EXPECT(VirtualQuery(pages, ®ion, sizeof(region)) == sizeof(region)); + EXPECT(VirtualQuery(cached_pages, ®ion, sizeof(region)) == sizeof(region)); const bool cache_modified = (region.Protect & (PAGE_WRITECOMBINE | PAGE_NOCACHE)) != 0; { Ref buffer; - EXPECT_HR(rt::d3d12::create_buffer_at_host_address(device, pages, desc, 0xFFFFFFFFu, IID_PPV_ARGS(&buffer.p)), S_OK); + EXPECT_HR(rt::d3d12::create_buffer_at_host_address(device, cached_pages, desc, 0xFFFFFFFFu, IID_PPV_ARGS(&buffer.p)), S_OK); if (cache_modified) { - EXPECT(buffer->GetGPUVirtualAddress() != reinterpret_cast(pages)); + EXPECT(buffer->GetGPUVirtualAddress() != reinterpret_cast(cached_pages)); } else { EXPECT(region.Protect == PAGE_READWRITE); - EXPECT(buffer->GetGPUVirtualAddress() == reinterpret_cast(pages)); + EXPECT(buffer->GetGPUVirtualAddress() == reinterpret_cast(cached_pages)); } } std::printf("%s: cache modifier 0x%lx, reported protection 0x%lx: %s\n", who, modifier, region.Protect, cache_modified ? "ordinary-buffer fallback verified" : "modifier not reported; read-write import verified"); - VirtualFree(pages, 0, MEM_RELEASE); + VirtualFree(cached_pages, 0, MEM_RELEASE); } char* partial = static_cast(VirtualAlloc(nullptr, size, MEM_RESERVE, PAGE_READWRITE)); EXPECT(partial != nullptr && VirtualAlloc(partial, size / 2, MEM_COMMIT, PAGE_READWRITE) == partial); From 3644c72a57bda2bc06d473285a7708670653b465 Mon Sep 17 00:00:00 2001 From: thibaut Date: Mon, 23 Nov 2026 22:29:53 +0100 Subject: [PATCH 22/23] d3d12: slot-133 texture layouts are validated; an import reaching the arena's VA window takes the fallback From review (@FRaccie): - The texture fallback called create_committed, which takes the state without checking it (textures start undefined and take their first command's layout), so the barrier-layout state and its COMMON retry did nothing. It now goes through create_committed_validated, as CreateCommittedResource does: RENDER_TARGET on a texture without ALLOW_RENDER_TARGET is refused and the COMMON retry answers; a description the checks refuse outright is refused. - An imported buffer's VA is its host address, in the same BufferVaIndex as default-heap buffers, whose VAs are offsets in [0, arena size). A host address inside that window (low addresses, as under Wine) would shadow arena buffers in the nearest-start lookup, so such a range is not imported and the fallback answers. d3d12_existing_heap_test checks the two texture cases. Co-Authored-By: Claude Opus 5.5 --- runtime/shims/d3d12_vulkan_device.cpp | 22 +++++++++++++++++----- runtime/test/d3d12_existing_heap_test.cpp | 12 ++++++++++++ 2 files changed, 29 insertions(+), 5 deletions(-) diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index 2a463e1f83..f079edd4c7 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -1917,6 +1917,15 @@ class Resource final void* const base_address = reinterpret_cast(base); const VkDeviceSize offset = start - base; const VkDeviceSize bytes = (offset + desc_.Width + alignment - 1) & ~(alignment - 1); + // An imported buffer's VA is its host address, and it joins the same BufferVaIndex as default-heap buffers, + // whose VAs are offsets in [0, arena size). A host range that reaches into that window (low host addresses, + // as under Wine) would shadow arena buffers in the index's nearest-start lookup, so it takes the fallback + // (found in review). + if (start < device_.arena.size) { + log_once("a title-placed buffer's host address overlaps the arena's VA window; not imported, size", + int(desc_.Width > INT_MAX ? INT_MAX : desc_.Width)); + return E_NOTIMPL; + } // The whole imported range must be committed, possibly across several allocations (the retail buffer spans // three mapped windows); a page not committed yet (xmem commits on first touch) or a write-combined one (on // an RTX 5090 such an import succeeded but GPU reads returned wrong bytes, found in review) is not imported, @@ -6972,14 +6981,17 @@ class Device final log_once("a title-placed texture (device slot 133) is an ordinary committed texture, not the title's pages; " "dimension", int(desc.Dimension)); - // The initial state follows the title's barrier layout (slot 133's third argument, measured by - // @dracbat); a state the description refuses (or UNDEFINED) gives COMMON, so the title still gets it. + // The title's barrier layout (slot 133's third argument, measured by @dracbat) is checked against the + // description as CreateCommittedResource checks a state; one it refuses (or UNDEFINED) gives COMMON, so + // the title still gets its texture. The image itself starts undefined either way: the first command that + // uses it moves it to that command's layout (vulkan_replay.h, initialize), as for every texture here. const D3D12_HEAP_PROPERTIES fallback{D3D12_HEAP_TYPE_DEFAULT}; const D3D12_RESOURCE_STATES initial = state_for_barrier_layout(layout); - HRESULT hr = create_committed(&fallback, D3D12_HEAP_FLAG_NONE, &desc, initial, 0, nullptr, riid, out); + HRESULT hr = create_committed_validated(nullptr, &fallback, D3D12_HEAP_FLAG_NONE, &desc, initial, nullptr, + 0, nullptr, riid, out); if (FAILED(hr) && initial != D3D12_RESOURCE_STATE_COMMON) - hr = create_committed(&fallback, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COMMON, 0, nullptr, - riid, out); + hr = create_committed_validated(nullptr, &fallback, D3D12_HEAP_FLAG_NONE, &desc, + D3D12_RESOURCE_STATE_COMMON, nullptr, 0, nullptr, riid, out); return d3d12_trace::result(method, hr); } D3D12_HEAP_PROPERTIES heap{}; diff --git a/runtime/test/d3d12_existing_heap_test.cpp b/runtime/test/d3d12_existing_heap_test.cpp index 14b6ae3f41..d2af3a1f45 100644 --- a/runtime/test/d3d12_existing_heap_test.cpp +++ b/runtime/test/d3d12_existing_heap_test.cpp @@ -235,6 +235,18 @@ int check_title_placed(ID3D12Device* device, const char* kind, void* pages, UINT Ref placed_texture; EXPECT_HR(rt::d3d12::create_buffer_at_host_address(device, pages, texture, 0x6u, IID_PPV_ARGS(&placed_texture.p)), S_OK); EXPECT(placed_texture.p != nullptr && placed_texture->GetDesc().Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE2D); + // The layout is validated as a CreateCommittedResource state: RENDER_TARGET (2) on a texture without + // ALLOW_RENDER_TARGET is refused, and the COMMON retry still gives the title its texture. A description the + // checks refuse outright (more mips than the size has) is refused, not created. + Ref target_layout; + EXPECT_HR(rt::d3d12::create_buffer_at_host_address(device, pages, texture, 0x2u, IID_PPV_ARGS(&target_layout.p)), S_OK); + EXPECT(target_layout.p != nullptr); + D3D12_RESOURCE_DESC too_many_mips = texture; + too_many_mips.MipLevels = 12; + Ref refused_texture; + EXPECT(FAILED(rt::d3d12::create_buffer_at_host_address(device, pages, too_many_mips, 0x6u, + IID_PPV_ARGS(&refused_texture.p))) && + refused_texture.p == nullptr); // An address off the buffer alignment can't be bound inside the import: the ordinary-buffer fallback answers. Ref fallback; EXPECT_HR(rt::d3d12::create_buffer_at_host_address(device, bytes + 1, desc, 0xFFFFFFFFu, IID_PPV_ARGS(&fallback.p)), S_OK); From cb29a2b88f9f538f70c70575bdc9183b469fba9b Mon Sep 17 00:00:00 2001 From: Raavve <184497748+Raavve@users.noreply.github.com> Date: Mon, 23 Nov 2026 17:56:23 -0300 Subject: [PATCH 23/23] d3d12_xs: slot 133 commits the buffer's xmem pages before the host-pointer import xmem commits physical pages on first touch (#7556), so a range the title has mapped but not written yet is still MEM_RESERVE when it places a buffer on it through device slot 133, and the Vulkan layer's import (#7218) refuses reserved pages and answers with its fallback buffer, which the title's writes never reach. Slot 133 now calls a registered pages hook (set_placed_at_va_pages_hook, next to set_placed_at_va_handler) with the buffer's range before the handler; gta6rt registers rt::xmem::commit_physical_range. A failed commit is logged once and the handler still runs. Textures don't call it. The Vulkan layer doesn't link xmem. Tests: xs_proxy_mock_test checks the hook order, arguments, failure and texture cases; the new d3d12_xmem_placed_test places a buffer on untouched xmem physical pages and checks the fallback without the hook, and with it the import and a GPU copy reading the CPU's writes. Co-Authored-By: Claude Opus 5.5 --- runtime/CMakeLists.txt | 9 ++ runtime/shims/d3d12_xs_device.cpp | 15 ++ runtime/shims/d3d12_xs_device.h | 9 ++ runtime/src/main.cpp | 4 + runtime/test/d3d12_xmem_placed_test.cpp | 182 ++++++++++++++++++++++++ runtime/test/xs_proxy_mock_test.cpp | 59 ++++++++ 6 files changed, 278 insertions(+) create mode 100644 runtime/test/d3d12_xmem_placed_test.cpp diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index 9f485ea0b1..d4b66203b8 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -1727,6 +1727,15 @@ 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) + # 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) + target_link_libraries(d3d12_xmem_placed_test PRIVATE gta6rt_d3d12_com d3d12 dxgi psapi) + target_compile_definitions(d3d12_xmem_placed_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(d3d12_xmem_placed_test PRIVATE /W4 /permissive- /utf-8) + target_link_options(d3d12_xmem_placed_test PRIVATE /OPT:NOREF) + add_test(NAME d3d12_xmem_placed COMMAND d3d12_xmem_placed_test) + set_tests_properties(d3d12_xmem_placed PROPERTIES SKIP_RETURN_CODE 77) # Fences and timing (D3D-30): multiple-fence waits, clock calibration, adapter LUID, custom heap properties. add_executable(d3d12_fence_timing_test test/d3d12_fence_timing_test.cpp) diff --git a/runtime/shims/d3d12_xs_device.cpp b/runtime/shims/d3d12_xs_device.cpp index 1244ac3515..0f831f4e1a 100644 --- a/runtime/shims/d3d12_xs_device.cpp +++ b/runtime/shims/d3d12_xs_device.cpp @@ -1491,6 +1491,7 @@ HRESULT proxy_create_resource(DeviceProxy* self, const D3D12_HEAP_PROPERTIES* he // device behind the proxy registered (set_placed_at_va_handler), with the PC flags kept and the layout made // ROW_MAJOR, as slot 76 does. std::atomic g_placed_at_va{nullptr}; +std::atomic g_placed_at_va_pages{nullptr}; HRESULT proxy_create_placed_resource_x(DeviceProxy* self, void* va, const D3D12_RESOURCE_DESC* xbox_desc, std::uint32_t state, const IID* riid, void** out) { @@ -1521,6 +1522,16 @@ HRESULT proxy_create_placed_resource_x(DeviceProxy* self, void* va, const D3D12_ va, static_cast(pc_desc.Dimension), static_cast(pc_desc.Width), xbox_flags, state); } + // The buffer's pages are committed before the handler walks them (set_placed_at_va_pages_hook). + const PlacedAtVaPagesHook pages = g_placed_at_va_pages.load(std::memory_order_acquire); + if (pages && pc_desc.Dimension == D3D12_RESOURCE_DIMENSION_BUFFER && pc_desc.Width && + !pages(va, static_cast(pc_desc.Width))) { + static std::atomic refused{false}; + if (!refused.exchange(true, std::memory_order_relaxed)) { + std::fprintf(stderr, "[rt] d3d12_xs: slot 133: committing the pages of va=%p width=%llu failed (error %lu)\n", + va, static_cast(pc_desc.Width), GetLastError()); + } + } return handler(self->real, va, pc_desc, state, *riid, out); } @@ -1751,6 +1762,10 @@ void set_placed_at_va_handler(PlacedAtVaHandler handler) { g_placed_at_va.store(handler, std::memory_order_release); } +void set_placed_at_va_pages_hook(PlacedAtVaPagesHook hook) { + g_placed_at_va_pages.store(hook, std::memory_order_release); +} + ID3D12Device* device_proxy_real_device(const void* device) { if (!is_device_proxy(device)) return nullptr; return static_cast(device)->real; diff --git a/runtime/shims/d3d12_xs_device.h b/runtime/shims/d3d12_xs_device.h index 1fc08dbdea..069706ce6b 100644 --- a/runtime/shims/d3d12_xs_device.h +++ b/runtime/shims/d3d12_xs_device.h @@ -49,6 +49,7 @@ #include +#include #include namespace rt::d3d12_xs { @@ -99,6 +100,14 @@ using PlacedAtVaHandler = HRESULT (*)(ID3D12Device* real, void* va, const D3D12_ std::uint32_t layout, REFIID riid, void** out); void set_placed_at_va_handler(PlacedAtVaHandler handler); +// Called by slot 133 for a buffer, before the handler, with the buffer's range [va, va + width). gta6rt registers +// rt::xmem::commit_physical_range: xmem commits physical pages on first touch, so a range the title has mapped but +// not written yet is still reserved, and the handler's import refuses reserved pages (it would answer with its +// fallback buffer, which the title's writes never reach). A false return is logged once and the handler is still +// called. With none registered nothing is done. +using PlacedAtVaPagesHook = bool (*)(const void* va, std::size_t bytes); +void set_placed_at_va_pages_hook(PlacedAtVaPagesHook hook); + // True for slots the proxy handles itself rather than forwarding verbatim: IUnknown (0-2), 8 and 75 (queue // proxies), 9 (allocator proxies), 14, 31/34/35/45/46/50 (proxies unwrapped), 32 and 36 (fence proxies), 48/73 and // 78/79/80 (the Xbox slots above, at their configured indices), 62, 67 and 76. Slot 10 is intentionally false: the diff --git a/runtime/src/main.cpp b/runtime/src/main.cpp index 71a5b44e12..39b362a016 100644 --- a/runtime/src/main.cpp +++ b/runtime/src/main.cpp @@ -32,10 +32,12 @@ #include "mods.h" #include "pe_loader.h" #include "../shims/d3d12_trace.h" +#include "../shims/d3d12_xs_device.h" #include "../shims/file_system.h" #include "../shims/process_shim.h" #include "../shims/shims.h" #include "../shims/startup_trace.h" +#include "../shims/xmem.h" namespace { @@ -147,6 +149,8 @@ int wmain(int argc, wchar_t** argv) { "this executable (docs/modding.md)\n", leonida::mods::active().size()); } rt::d3d12_trace::set_enabled(trace_d3d12); + // Slot 133 imports the title's pages; xmem commits them on first touch, so they are committed first. + rt::d3d12_xs::set_placed_at_va_pages_hook(&rt::xmem::commit_physical_range); if (int trace_error = 0; !trace_file.empty() && !rt::startup_trace::open(trace_file.c_str(), &trace_error)) { std::fprintf(stderr, trace_error == EEXIST ? "error: the trace file already exists; --trace only creates a new file\n" : "error: cannot create the trace file\n"); diff --git a/runtime/test/d3d12_xmem_placed_test.cpp b/runtime/test/d3d12_xmem_placed_test.cpp new file mode 100644 index 0000000000..368b32510b --- /dev/null +++ b/runtime/test/d3d12_xmem_placed_test.cpp @@ -0,0 +1,182 @@ +// Xbox device slot 133 (CreatePlacedResourceX) on xmem physical pages that were mapped but never touched. xmem +// commits physical pages on first touch, so such a range is still reserved when the title places a buffer on it, and +// the Vulkan layer's import (rt::d3d12::create_buffer_at_host_address) refuses reserved pages and answers with its +// fallback buffer, which the CPU's writes never reach. With rt::xmem::commit_physical_range registered as the slot's +// pages hook (rt::d3d12_xs::set_placed_at_va_pages_hook, as gta6rt does), the pages are committed first: the buffer's +// GPU VA is the window itself and a GPU copy reads what the CPU writes there afterwards. +// Needs VK_EXT_external_memory_host (skipped otherwise). No shaders or game data. +#include "vk_test_device.h" +#include "../shims/d3d12_com.h" +#include "../shims/d3d12_xs_device.h" +#include "../shims/shims.h" +#include "../shims/xmem.h" + +#include + +#define EXPECT(condition) do { \ + if (!(condition)) { std::fprintf(stderr, "%s line %d: %s\n", who, __LINE__, #condition); return 1; } \ +} while (0) + +namespace { + +const char* const who = "xmem slot-133 buffer"; + +template +struct Ref { + T* p = nullptr; + ~Ref() { if (p) p->Release(); } + T* operator->() const { return p; } +}; + +using XMemVirtualAllocFn = void*(WINAPI*)(void*, SIZE_T, DWORD, ULONGLONG, DWORD); +using XMemAllocatePhysicalPagesFn = BOOL(WINAPI*)(std::uint64_t, std::uint64_t*, std::uint64_t*); +using XMemFreePhysicalPagesFn = BOOL(WINAPI*)(std::uint64_t, const std::uint64_t*); +using XMemMapPhysicalPagesFn = void*(WINAPI*)(void*, std::uint64_t, const std::uint64_t*); +using SlotFn = std::uint64_t(WINAPI*)(void*, std::uint64_t, std::uint64_t, std::uint64_t, std::uint64_t, + std::uint64_t, std::uint64_t); +constexpr DWORD kXmem64kPages = 0x20400000; +constexpr SIZE_T kPage64k = 0x10000; +constexpr std::uint64_t kPages = 4; + +bool state_is(const void* address, DWORD state) { + MEMORY_BASIC_INFORMATION info{}; + return VirtualQuery(address, &info, sizeof(info)) && info.State == state; +} + +// Slot 133 as the title calls it: (va, desc, layout, clear, riid, out). +HRESULT place(void* device, void* va, const D3D12_RESOURCE_DESC& desc, ID3D12Resource** out) { + void* const* vtable = *static_cast(device); + const GUID iid = __uuidof(ID3D12Resource); + const std::uint64_t r = reinterpret_cast(vtable[133])( + device, reinterpret_cast(va), reinterpret_cast(&desc), 0xFFFFFFFFull, 0, + reinterpret_cast(&iid), reinterpret_cast(out)); + return static_cast(static_cast(r)); +} + +int gpu_reads_cpu_writes(ID3D12Device* real, ID3D12Resource* buffer, const void* pages, UINT64 size) { + D3D12_RESOURCE_DESC desc = buffer->GetDesc(); + D3D12_HEAP_PROPERTIES readback_heap{D3D12_HEAP_TYPE_READBACK}; + Ref readback; + EXPECT(SUCCEEDED(real->CreateCommittedResource(&readback_heap, D3D12_HEAP_FLAG_NONE, &desc, + D3D12_RESOURCE_STATE_COPY_DEST, nullptr, IID_PPV_ARGS(&readback.p)))); + D3D12_COMMAND_QUEUE_DESC queue_desc{D3D12_COMMAND_LIST_TYPE_DIRECT}; + Ref queue; + Ref allocator; + Ref list; + Ref fence; + EXPECT(SUCCEEDED(real->CreateCommandQueue(&queue_desc, IID_PPV_ARGS(&queue.p)))); + EXPECT(SUCCEEDED(real->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator.p)))); + EXPECT(SUCCEEDED(real->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.p, nullptr, + IID_PPV_ARGS(&list.p)))); + list->CopyBufferRegion(readback.p, 0, buffer, 0, size); + EXPECT(SUCCEEDED(list->Close())); + ID3D12CommandList* lists[] = {list.p}; + queue->ExecuteCommandLists(1, lists); + EXPECT(SUCCEEDED(real->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); + void* mapped = nullptr; + EXPECT(SUCCEEDED(readback->Map(0, nullptr, &mapped))); + const bool same = std::memcmp(mapped, pages, static_cast(size)) == 0; + readback->Unmap(0, nullptr); + EXPECT(same); + return 0; +} + +int run(ID3D12Device* real, void* device) { + const auto virtual_alloc = reinterpret_cast(rt::shims::find("xmem.dll", "XMemVirtualAlloc")); + const auto allocate = + reinterpret_cast(rt::shims::find("xmem.dll", "XMemAllocatePhysicalPages")); + const auto free_pages = + reinterpret_cast(rt::shims::find("xmem.dll", "XMemFreePhysicalPages")); + const auto map = reinterpret_cast(rt::shims::find("xmem.dll", "XMemMapPhysicalPages")); + EXPECT(virtual_alloc && allocate && free_pages && map); + + constexpr UINT64 size = kPages * kPage64k; + auto* const window = + static_cast(virtual_alloc(nullptr, size, MEM_RESERVE | kXmem64kPages, 0x23, PAGE_READWRITE)); + EXPECT(window != nullptr); + std::uint64_t pages[kPages]{}; + std::uint64_t count = kPages; + EXPECT(allocate(0x280, &count, pages) == TRUE && count == kPages); + EXPECT(map(window, kPages, pages) == window); + EXPECT(state_is(window, MEM_RESERVE)); // mapped, never touched: nothing committed yet + + D3D12_RESOURCE_DESC desc{}; + desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + desc.Width = size; + desc.Height = desc.DepthOrArraySize = desc.MipLevels = 1; + desc.SampleDesc.Count = 1; + desc.Layout = static_cast(0x1); // the Xbox row-major word + const auto window_va = reinterpret_cast(window); + + // Without the hook the reserved pages are refused and the fallback answers. + rt::d3d12_xs::set_placed_at_va_pages_hook(nullptr); + { + Ref fallback; + EXPECT(place(device, window, desc, &fallback.p) == S_OK && fallback.p); + EXPECT(fallback->GetGPUVirtualAddress() != window_va); + EXPECT(state_is(window, MEM_RESERVE)); + } + std::printf("%s: untouched physical pages without the hook: still reserved, fallback buffer\n", who); + + // With it the range is committed first and imported. + rt::d3d12_xs::set_placed_at_va_pages_hook(&rt::xmem::commit_physical_range); + { + Ref buffer; + EXPECT(place(device, window, desc, &buffer.p) == S_OK && buffer.p); + EXPECT(state_is(window, MEM_COMMIT) && state_is(window + size - 1, MEM_COMMIT)); + EXPECT(buffer->GetGPUVirtualAddress() == window_va); + for (UINT64 i = 0; i < size; ++i) window[i] = static_cast(i * 131u + 7u); + if (gpu_reads_cpu_writes(real, buffer.p, window, size)) return 1; + } + rt::d3d12_xs::set_placed_at_va_pages_hook(nullptr); + std::printf("%s: with commit_physical_range: %llu bytes committed, GPU VA is the window, a GPU copy reads the " + "CPU's writes\n", who, static_cast(size)); + + EXPECT(map(window, kPages, nullptr) == window); + EXPECT(free_pages(count, pages) == TRUE); + return 0; +} + +} // namespace + +int main() { + vktest::Device vk; + 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", who); + 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; + Ref real; + if (FAILED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&real.p)))) return 1; + real->AddRef(); // the proxy takes one reference + Ref device; + if (FAILED(rt::d3d12_xs::create_device_proxy(real.p, __uuidof(ID3D12Device), + reinterpret_cast(&device.p)))) { + real->Release(); + return 1; + } + failures += run(real.p, device.p); + } + if (vk.validation_errors()) { + std::fprintf(stderr, "%u validation errors\n", vk.validation_errors()); + return 1; + } + return failures ? 1 : 0; +} diff --git a/runtime/test/xs_proxy_mock_test.cpp b/runtime/test/xs_proxy_mock_test.cpp index b99e14826d..dfe464d5ed 100644 --- a/runtime/test/xs_proxy_mock_test.cpp +++ b/runtime/test/xs_proxy_mock_test.cpp @@ -427,6 +427,65 @@ int check_levels() { EXPECT(xs::device_slot_overridden(133)); } + // 133 with a pages hook (set_placed_at_va_pages_hook): a buffer's range [va, va + width) is handed to it + // before the handler runs; a texture is not; a hook that fails still leaves the call to the handler. + { + static int order = 0; + static int hook_at = 0; + static int handler_at = 0; + static const void* hook_va = nullptr; + static std::size_t hook_bytes = 0; + static bool hook_result = true; + order = hook_at = handler_at = 0; + const xs::PlacedAtVaPagesHook hook = [](const void* va, std::size_t bytes) -> bool { + hook_at = ++order; + hook_va = va; + hook_bytes = bytes; + return hook_result; + }; + const xs::PlacedAtVaHandler handler = [](ID3D12Device*, void*, const D3D12_RESOURCE_DESC&, std::uint32_t, + REFIID, void** out) -> HRESULT { + handler_at = ++order; + *out = reinterpret_cast(0x1331); + return S_OK; + }; + xs::set_placed_at_va_handler(handler); + xs::set_placed_at_va_pages_hook(hook); + D3D12_RESOURCE_DESC xbox_desc{}; + xbox_desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + xbox_desc.Width = 0xadf0000; + xbox_desc.Height = xbox_desc.DepthOrArraySize = xbox_desc.MipLevels = 1; + xbox_desc.SampleDesc.Count = 1; + xbox_desc.Layout = static_cast(0x1); + const GUID resource_iid = __uuidof(ID3D12Resource); + void* placed = nullptr; + void* const va = reinterpret_cast(0x7f0000010000ull); + auto place = [&]() { + placed = nullptr; + return hr_of(raw(device, 133, word(va), word(&xbox_desc), 0xFFFFFFFFull, 0, word(&resource_iid), + word(&placed))); + }; + const HRESULT buffer_hr = place(); + EXPECT(buffer_hr == S_OK && placed == reinterpret_cast(0x1331)); + EXPECT(hook_at == 1 && handler_at == 2 && hook_va == va && hook_bytes == 0xadf0000); + + hook_result = false; + order = hook_at = handler_at = 0; + const HRESULT refused_hr = place(); + EXPECT(refused_hr == S_OK && hook_at == 1 && handler_at == 2); + hook_result = true; + + xbox_desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + xbox_desc.Width = 64; + xbox_desc.Height = 64; + order = hook_at = handler_at = 0; + const HRESULT texture_hr = place(); + EXPECT(texture_hr == S_OK && hook_at == 0 && handler_at == 1); + + xs::set_placed_at_va_pages_hook(nullptr); + xs::set_placed_at_va_handler(nullptr); + } + Mock* const queue_mock = reinterpret_cast(real_queue); Mock* const fence_mock = reinterpret_cast(real_fence); EXPECT(release(queue) == 0 && release(fence) == 0);