diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index 3d0bb02022..d4b66203b8 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) @@ -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_com.h b/runtime/shims/d3d12_com.h index 8f37b1ff24..14ead7b24f 100644 --- a/runtime/shims/d3d12_com.h +++ b/runtime/shims/d3d12_com.h @@ -187,6 +187,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 @@ -218,6 +222,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, + 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 176ab613c4..f079edd4c7 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -637,6 +637,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. @@ -1724,6 +1726,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_); @@ -1884,6 +1898,118 @@ 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 || 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); + // 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, + // and the ordinary-buffer fallback answers instead. + bool importable = true; + for (VkDeviceSize at = 0; at < bytes;) { + MEMORY_BASIC_INFORMATION region{}; + 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 - base; + } + 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; + 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, base_address, + &host) != VK_SUCCESS) + return E_NOTIMPL; + const std::uint32_t types = host.memoryTypeBits & requirements.memoryTypeBits; + // 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 = 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 + // 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_, offset) != 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}; + 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 || @@ -2415,6 +2541,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; @@ -2596,6 +2723,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. @@ -2608,6 +2749,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; } @@ -2617,7 +2760,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 {}; @@ -2659,6 +2802,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_; @@ -4749,6 +4893,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); @@ -4877,6 +5025,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); @@ -6699,16 +6850,176 @@ 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, 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 + // 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; + 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); + } + 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 = (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 | + 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, 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 != protect) return false; + size += region.RegionSize; + } + 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. + // 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 + // 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)); + // 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_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_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{}; + 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 (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)); } HRESULT STDMETHODCALLTYPE OpenExistingHeapFromFileMapping(HANDLE file_mapping, REFIID, void** out) override { @@ -6810,6 +7121,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); @@ -7695,7 +8013,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); @@ -8358,6 +8677,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, + 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, layout, riid, out); +} + bool device_supports_ray_tracing(ID3D12Device* device) { if (!device) return false; ID3D12Device* real = rt::d3d12_xs::device_proxy_real_device(device); @@ -9329,6 +9658,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(); @@ -9364,6 +9705,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/shims/d3d12_xs_device.cpp b/runtime/shims/d3d12_xs_device.cpp index e17a80353b..0f831f4e1a 100644 --- a/runtime/shims/d3d12_xs_device.cpp +++ b/runtime/shims/d3d12_xs_device.cpp @@ -44,7 +44,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, @@ -147,6 +150,7 @@ const char* slot_name(unsigned slot) { case 78: return "Xbox SetFrameIntervalX"; case 79: return "Xbox ScheduleFrameEventX"; case 80: return "Xbox WaitFrameEventX"; + case 133: return "Xbox CreatePlacedResourceX (a buffer on the title's pages)"; default: return "forwarded"; } } @@ -1480,6 +1484,57 @@ 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}; +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) { + 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; + // 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. + // 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); + // 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, + "[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); + } + // 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); +} + 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, @@ -1521,6 +1576,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), @@ -1698,6 +1758,14 @@ 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); +} + +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; @@ -1706,7 +1774,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/shims/d3d12_xs_device.h b/runtime/shims/d3d12_xs_device.h index 0019ec5069..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 { @@ -89,6 +90,24 @@ 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. +// `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); + +// 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/shims/xmem.cpp b/runtime/shims/xmem.cpp index 37f29459f1..1e286d7120 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. @@ -427,6 +453,7 @@ 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; if (!placeholder_api().unmap_view2(GetCurrentProcess(), reinterpret_cast(address), @@ -449,14 +476,81 @@ 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; - g_mapped[address] = page; + 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, 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(accessed), &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 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, accessed, 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 +581,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 +600,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 +797,59 @@ 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; + const uintptr_t page = first + i * kPhysicalPageSize; + if (commit_mapped_page(page, page, protect) == PageCommit::failed) return false; + } + 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)} // 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..beef935e65 --- /dev/null +++ b/runtime/shims/xmem.h @@ -0,0 +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/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_existing_heap_test.cpp b/runtime/test/d3d12_existing_heap_test.cpp index 6c036f277b..d2af3a1f45 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,9 @@ #include "host_wine.h" #include "../shims/d3d12_com.h" #include +#include +#include +#include #define EXPECT(condition) do { \ if (!(condition)) { std::fprintf(stderr, "%s line %d: %s\n", who, __LINE__, #condition); return 1; } \ @@ -49,6 +54,277 @@ 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); + // 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, combined, uncached, 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; + // 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; + 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; +} + +// 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. +// `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; + 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, 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); + + 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; + // 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, 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); + 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; +} + +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); + // 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; + if (!view) return failures + 1; + failures += check_title_placed(device, "section view", view, size, /*may_refuse=*/true); + UnmapViewOfFile(view); + CloseHandle(section); + + // 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; + desc.Width = size; + desc.Height = desc.DepthOrArraySize = desc.MipLevels = 1; + desc.SampleDesc.Count = 1; + desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + for (DWORD modifier : {DWORD(PAGE_WRITECOMBINE), DWORD(PAGE_NOCACHE)}) { + void* cached_pages = VirtualAlloc(nullptr, size, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE | modifier); + EXPECT(cached_pages != nullptr); + MEMORY_BASIC_INFORMATION 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, cached_pages, desc, 0xFFFFFFFFu, IID_PPV_ARGS(&buffer.p)), S_OK); + if (cache_modified) { + EXPECT(buffer->GetGPUVirtualAddress() != reinterpret_cast(cached_pages)); + } else { + EXPECT(region.Protect == PAGE_READWRITE); + 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(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); + { + // 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, 0xFFFFFFFFu, IID_PPV_ARGS(&fallback.p)), S_OK); + EXPECT(fallback->GetGPUVirtualAddress() != reinterpret_cast(partial)); + } + VirtualFree(partial, 0, MEM_RELEASE); + std::printf("%s: a partly committed range falls back to an ordinary buffer\n", who); + 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, + 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 +342,13 @@ 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); + 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}) { @@ -77,6 +358,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/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/vk_test_device.h b/runtime/test/vk_test_device.h index 949e5abfba..5cccd1836e 100644 --- a/runtime/test/vk_test_device.h +++ b/runtime/test/vk_test_device.h @@ -123,6 +123,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; @@ -548,6 +550,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(); @@ -563,6 +575,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) diff --git a/runtime/test/xmem_test.cpp b/runtime/test/xmem_test.cpp index eed030c129..3ec621b0b4 100644 --- a/runtime/test/xmem_test.cpp +++ b/runtime/test/xmem_test.cpp @@ -11,6 +11,7 @@ #include #include +#include #include #include #include @@ -18,9 +19,12 @@ #include #include #include +#include +#include #include "shims.h" #include "startup_trace.h" +#include "xmem.h" namespace { @@ -440,6 +444,222 @@ 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); + 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"); + 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"); +} + +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"); +} + +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( @@ -718,6 +938,9 @@ 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_commit_physical_pages(physical); + test_first_touch_during_remap(physical); test_placeholders(physical); } diff --git a/runtime/test/xs_proxy_mock_test.cpp b/runtime/test/xs_proxy_mock_test.cpp index f0030116bd..dfe464d5ed 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); } @@ -381,6 +381,111 @@ 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); + + // 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{}; + static std::uint32_t seen_layout = 0; + const xs::PlacedAtVaHandler handler = [](ID3D12Device* real_device, void* va, + 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; + 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(seen_layout == 0xFFFFFFFFu); // the title's third word, passed through as the barrier layout + 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);