diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index 597eaa0ea8..51c7872629 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -585,6 +585,13 @@ if(BUILD_TESTING) add_executable(buffer_va_index_test test/buffer_va_index_test.cpp) add_test(NAME buffer_va_index COMMAND buffer_va_index_test) + # Thread-safe host VA -> GPU BDA region table (runtime/src/title_host_regions.h): pure stdlib, no Vulkan instance. + add_executable(title_host_regions_test test/title_host_regions_test.cpp) + target_include_directories(title_host_regions_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/src) + find_package(Threads REQUIRED) + target_link_libraries(title_host_regions_test PRIVATE Threads::Threads) + add_test(NAME title_host_regions COMMAND title_host_regions_test) + add_executable(xbox_present_readback_size_test test/xbox_present_readback_size_test.cpp) add_test(NAME xbox_present_readback_size COMMAND xbox_present_readback_size_test) @@ -1482,13 +1489,14 @@ endif() if(TARGET Vulkan::Headers) foreach(tool vk_harness vk_ps_sweep vk_texture_test vk_sampler_test vk_compute_test vk_store_test vk_pipeline_check vk_command_replay_test vk_bindless_test vk_image_fuzz vk_descriptor_bench depth24_convert_test vk_predicate_capture_test vk_predicated_copy_test - vk_xdxr_build_test vk_queue_test vk_sandbox) + vk_xdxr_build_test vk_queue_test vk_sandbox title_host_region_gpu_test) add_executable(${tool} test/${tool}.cpp) target_link_libraries(${tool} PRIVATE Vulkan::Headers ${CMAKE_DL_LIBS}) if(WIN32) target_compile_definitions(${tool} PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) endif() endforeach() + add_test(NAME title_host_region_gpu COMMAND title_host_region_gpu_test) # OpFmaKHR width gate of vk_shader_fma.h (shaderFmaFloat32 / shaderFmaFloat64): no Vulkan instance, no GPU. add_executable(vk_shader_fma_test test/vk_shader_fma_test.cpp) target_link_libraries(vk_shader_fma_test PRIVATE Vulkan::Headers) diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index e9bc191952..47a5cfb7e9 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -5153,9 +5153,12 @@ class Device final } } if (info.host_image_copy) load_host_image_copy(get_device); - if (info.host_pointer_alignment) + if (info.host_pointer_alignment) { state_.get_host_pointer_properties = reinterpret_cast( get_device(info.device, "vkGetMemoryHostPointerPropertiesEXT")); + state_.context->configure_title_regions(state_.get_host_pointer_properties, info.host_pointer_alignment, + state_.memory); + } // 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); @@ -6402,6 +6405,16 @@ class Device final // A constant-buffer view is a 16-byte GFX10 raw buffer V# in the first half of the slot (zeros in the rest). // A null description, zero address, or zero size leaves the whole slot zeroed (null V#: reads return 0). + // Translates an external/title host VA into an arena-relative offset so a shader adding + // heap_base (arena.address) lands on the Vulkan-imported BDA. + std::uint64_t resolve_shader_va(std::uint64_t va) const { + if (!va || va < state_.arena.size || !state_.context || !state_.arena.address) return va; + const auto bda = state_.context->resolve_title_bda(va); + if (!bda || *bda < state_.arena.address) return va; + const std::uint64_t rel = *bda - state_.arena.address; + return (rel >> 48) == 0 ? rel : va; + } + void STDMETHODCALLTYPE CreateConstantBufferView(const D3D12_CONSTANT_BUFFER_VIEW_DESC* desc, D3D12_CPU_DESCRIPTOR_HANDLE destination) override { d3d12_trace::record("ID3D12Device::CreateConstantBufferView"); @@ -6409,7 +6422,7 @@ class Device final std::memset(reinterpret_cast(destination.ptr), 0, kDescriptorSize); if (!desc || !desc->BufferLocation || !desc->SizeInBytes) return; leonida::gfx10::Buffer buffer{}; - buffer.address = desc->BufferLocation; + buffer.address = resolve_shader_va(desc->BufferLocation); buffer.stride = 0; buffer.num_records = desc->SizeInBytes; buffer.format = leonida::gfx10::format_from_vulkan(VK_FORMAT_R32_UINT); @@ -6446,7 +6459,7 @@ class Device final log_once("shader-resource view dimension not supported for buffer:", desc->ViewDimension); return; } - const UINT64 base_va = const_cast(r)->GetGPUVirtualAddress(); + const UINT64 base_va = resolve_shader_va(const_cast(r)->GetGPUVirtualAddress()); const UINT64 width = r->desc().Width; if (!base_va || !desc->Buffer.NumElements || (desc->Buffer.Flags & ~D3D12_BUFFER_SRV_FLAG_RAW)) return; leonida::gfx10::Buffer buffer{}; @@ -6651,8 +6664,8 @@ class Device final return; } } - const UINT64 va = resource->GetGPUVirtualAddress(); - const UINT64 counter_va = counter ? counter->GetGPUVirtualAddress() : 0; + const UINT64 va = resolve_shader_va(resource->GetGPUVirtualAddress()); + const UINT64 counter_va = counter ? resolve_shader_va(counter->GetGPUVirtualAddress()) : 0; if (!va || (counter && !counter_va)) return; g::Buffer buffer{}; buffer.address = va + view.FirstElement * unit; diff --git a/runtime/shims/xmem.cpp b/runtime/shims/xmem.cpp index a0335a2376..38c596c94c 100644 --- a/runtime/shims/xmem.cpp +++ b/runtime/shims/xmem.cpp @@ -18,6 +18,8 @@ #include #include +#include "../src/title_host_regions.h" + #include #include #include @@ -428,8 +430,12 @@ void* WINAPI XMemVirtualAlloc(void* address, SIZE_T size, DWORD allocation_type, record_window(address, size, host_prot); return address; } - return placeholder_api().virtual_alloc2(GetCurrentProcess(), address, size, host_type | MEM_RESERVE, host_prot, - nullptr, 0); + void* const result = placeholder_api().virtual_alloc2(GetCurrentProcess(), address, size, + host_type | MEM_RESERVE, host_prot, nullptr, 0); + if (result && commit) { + leonida::title_host_regions().register_range(reinterpret_cast(result), size, 2); + } + return result; } if (new_placeholder || window) { void* const result = reserve_placeholder(address, size, base_granularity); @@ -445,10 +451,18 @@ void* WINAPI XMemVirtualAlloc(void* address, SIZE_T size, DWORD allocation_type, MEM_EXTENDED_PARAMETER parameter{}; parameter.Type = MemExtendedParameterAddressRequirements; parameter.Pointer = &requirements; - return placeholder_api().virtual_alloc2(GetCurrentProcess(), nullptr, size, host_type | MEM_RESERVE, host_prot, - ¶meter, 1); + void* const result = placeholder_api().virtual_alloc2(GetCurrentProcess(), nullptr, size, + host_type | MEM_RESERVE, host_prot, ¶meter, 1); + if (result && commit) { + leonida::title_host_regions().register_range(reinterpret_cast(result), size, 2); + } + return result; + } + void* const result = VirtualAlloc(address, size, host_type, host_prot); + if (result && commit) { + leonida::title_host_regions().register_range(reinterpret_cast(result), size, 2); } - return VirtualAlloc(address, size, host_type, host_prot); + return result; } // With g_phys_mutex held. Unmaps the page at `address` if one is mapped there; the address becomes a placeholder again. @@ -456,6 +470,7 @@ bool unmap_page(uintptr_t address) { const FaultLockExclusive lock; const auto it = g_mapped.find(address); if (it == g_mapped.end()) return true; + leonida::title_host_regions().unregister_range(address, kPhysicalPageSize); if (!placeholder_api().unmap_view2(GetCurrentProcess(), reinterpret_cast(address), MEM_PRESERVE_PLACEHOLDER)) { return false; @@ -482,6 +497,7 @@ bool map_page(uintptr_t address, uint64_t page, DWORD protect) { protect, nullptr, 0); if (!view) return false; g_mapped[address] = MappedPage{page, it->second.section, it->second.offset}; + leonida::title_host_regions().register_range(address, kPhysicalPageSize, 3); return true; } @@ -797,7 +813,28 @@ constexpr DWORD kMemGraphics = 0x10000000; constexpr DWORD kMemTitle = 0x40000000; LPVOID WINAPI TitleVirtualAlloc(LPVOID address, SIZE_T size, DWORD allocation_type, DWORD protect) { - return VirtualAlloc(address, size, allocation_type & ~(kMemGraphics | kMemTitle), host_protect(protect)); + LPVOID const result = + VirtualAlloc(address, size, allocation_type & ~(kMemGraphics | kMemTitle), host_protect(protect)); + if (result && (allocation_type & (kMemGraphics | MEM_COMMIT)) == (kMemGraphics | MEM_COMMIT)) { + leonida::title_host_regions().register_range(reinterpret_cast(result), size, 1); + } + return result; +} + +BOOL WINAPI TitleVirtualFree(LPVOID address, SIZE_T size, DWORD free_type) { + if (address && (free_type & (MEM_DECOMMIT | MEM_RELEASE)) != 0) { + uint64_t unreg_size = size; + if (unreg_size == 0) { + MEMORY_BASIC_INFORMATION mbi{}; + if (VirtualQuery(address, &mbi, sizeof(mbi))) { + unreg_size = mbi.RegionSize; + } + } + if (unreg_size != 0) { + leonida::title_host_regions().unregister_range(reinterpret_cast(address), unreg_size); + } + } + return VirtualFree(address, size, free_type); } } // namespace @@ -855,7 +892,9 @@ bool commit_physical_pages(const uint64_t* page_array, size_t count) { } -#define TITLE_VIRTUAL_ALLOC(dll) {dll, "VirtualAlloc", reinterpret_cast(&TitleVirtualAlloc)} +#define TITLE_VIRTUAL_ALLOC(dll) \ + {dll, "VirtualAlloc", reinterpret_cast(&TitleVirtualAlloc)}, \ + {dll, "VirtualFree", reinterpret_cast(&TitleVirtualFree)} // The classic libraries and the memory api sets a title's imports name. SHIM_TABLE(title_memory, diff --git a/runtime/src/title_host_regions.h b/runtime/src/title_host_regions.h new file mode 100644 index 0000000000..c2b8b3cf5b --- /dev/null +++ b/runtime/src/title_host_regions.h @@ -0,0 +1,266 @@ +#pragma once + +// Thread-safe interval table mapping non-overlapping title host virtual address ranges +// [host_va, host_va + size) to their optional Vulkan-imported GPU buffer device address (BDA) +// and import handle. Regions with gpu_bda == 0 are registered by the CPU allocator / xmem +// and pending lazy import by the Vulkan device; detached/replaced regions that hold a Vulkan +// import handle are queued for deferred destruction after GPU idle. + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace leonida { + +class TitleHostRegions { +public: + struct Region { + std::uint64_t host_va = 0; + std::uint64_t size = 0; + std::uint64_t gpu_bda = 0; + std::uint64_t tag = 0; + std::uint64_t handle = 0; + bool import_failed = false; + }; + + struct Retired { + std::uint64_t host_va = 0; + std::uint64_t size = 0; + std::uint64_t gpu_bda = 0; + std::uint64_t tag = 0; + std::uint64_t handle = 0; + }; + + struct Lookup { + bool found = false; + std::uint64_t host_va = 0; + std::uint64_t size = 0; + std::uint64_t gpu_bda = 0; + std::uint64_t offset = 0; + std::uint64_t handle = 0; + bool import_failed = false; + }; + + // Registers [host_va, host_va + size) with gpu_bda = 0 (pending Vulkan import). + // Overlapping stale entries are split or replaced; any detached entry with a Vulkan + // import handle is recorded in the retired list. Ignores host_va == 0 or size == 0. + void register_range(std::uint64_t host_va, std::uint64_t size, std::uint64_t tag = 0) { + if (host_va == 0 || size == 0) { + return; + } + const std::uint64_t end = clamp_end(host_va, size); + const std::uint64_t clamped_size = end - host_va; + if (clamped_size == 0) { + return; + } + + std::function hook; + { + std::lock_guard lock(mutex_); + detach_range_locked(host_va, end); + regions_.emplace(host_va, Region{host_va, clamped_size, 0, tag, 0, false}); + if (!retired_.empty()) { + hook = retire_hook_; + } + } + if (hook) { + hook(); + } + } + + // Removes [host_va, host_va + size), splitting larger regions if partially unmapped + // and removing fully covered regions. Detached entries with a Vulkan import handle + // are recorded in the retired list for safe destruction after GPU idle. + void unregister_range(std::uint64_t host_va, std::uint64_t size) { + if (host_va == 0 || size == 0) { + return; + } + const std::uint64_t end = clamp_end(host_va, size); + if (end <= host_va) { + return; + } + + std::function hook; + { + std::lock_guard lock(mutex_); + detach_range_locked(host_va, end); + if (!retired_.empty()) { + hook = retire_hook_; + } + } + if (hook) { + hook(); + } + } + + void set_retire_hook(std::function hook) { + std::lock_guard lock(mutex_); + retire_hook_ = std::move(hook); + } + + // O(log N) lookup returning the region containing `va` and `offset = va - region.host_va`. + Lookup find(std::uint64_t va) const { + if (va == 0) { + return {}; + } + + std::lock_guard lock(mutex_); + return find_locked(va); + } + + // Resolves `va` to `region.gpu_bda + offset` if `va` falls in an imported region + // (`gpu_bda != 0`), or `std::nullopt` otherwise. + std::optional resolve_bda(std::uint64_t va) const { + if (va == 0) { + return std::nullopt; + } + + std::lock_guard lock(mutex_); + const Lookup hit = find_locked(va); + if (!hit.found || hit.gpu_bda == 0) { + return std::nullopt; + } + return hit.gpu_bda + hit.offset; + } + + // Returns all currently registered regions that have not yet been imported into Vulkan (`gpu_bda == 0`). + std::vector pending_imports() const { + std::lock_guard lock(mutex_); + std::vector pending; + for (const auto& [va, region] : regions_) { + (void)va; + if (region.gpu_bda == 0 && !region.import_failed) { + pending.push_back(region); + } + } + return pending; + } + + // Marks a region as unimportable so subsequent lookups do not retry sync_pending() indefinitely. + void mark_failed(std::uint64_t host_va, std::uint64_t size) { + std::lock_guard lock(mutex_); + auto it = regions_.find(host_va); + if (it != regions_.end() && it->second.size == size && it->second.gpu_bda == 0) { + it->second.import_failed = true; + } + } + + // Marks a previously registered region [host_va, host_va + size) as imported with `gpu_bda` + // and Vulkan `handle`. If the region was unregistered or resized concurrently before this + // call arrived, any non-zero `handle` is queued into `retired` so it is not leaked. + void mark_imported(std::uint64_t host_va, std::uint64_t size, std::uint64_t gpu_bda, std::uint64_t handle) { + std::lock_guard lock(mutex_); + auto it = regions_.find(host_va); + if (it == regions_.end() || it->second.size != size) { + if (handle != 0) { + retired_.push_back(Retired{host_va, size, gpu_bda, 0, handle}); + } + return; + } + + if (it->second.handle != 0 && it->second.handle != handle) { + retired_.push_back(Retired{ + it->second.host_va, + it->second.size, + it->second.gpu_bda, + it->second.tag, + it->second.handle, + }); + } + + it->second.gpu_bda = gpu_bda; + it->second.handle = handle; + } + + // Drains all retired entries that had a Vulkan import handle (`handle != 0`). + std::vector take_retired() { + std::lock_guard lock(mutex_); + std::vector out; + out.swap(retired_); + return out; + } + + std::size_t size() const { + std::lock_guard lock(mutex_); + return regions_.size(); + } + + bool empty() const { + std::lock_guard lock(mutex_); + return regions_.empty(); + } + +private: + static std::uint64_t clamp_end(std::uint64_t start, std::uint64_t size) { + const std::uint64_t max_u64 = std::numeric_limits::max(); + return (size > max_u64 - start) ? max_u64 : (start + size); + } + + Lookup find_locked(std::uint64_t va) const { + if (regions_.empty()) { + return {}; + } + auto it = regions_.upper_bound(va); + if (it == regions_.begin()) { + return {}; + } + --it; + const std::uint64_t offset = va - it->first; + if (offset >= it->second.size) { + return {}; + } + return Lookup{true, it->second.host_va, it->second.size, it->second.gpu_bda, + offset, it->second.handle, it->second.import_failed}; + } + + void detach_range_locked(std::uint64_t start, std::uint64_t end) { + auto it = regions_.lower_bound(start); + if (it != regions_.begin()) { + auto prev = std::prev(it); + if (clamp_end(prev->second.host_va, prev->second.size) > start) { + it = prev; + } + } + + while (it != regions_.end() && it->first < end) { + const Region old = it->second; + const std::uint64_t old_start = old.host_va; + const std::uint64_t old_end = clamp_end(old.host_va, old.size); + + it = regions_.erase(it); + + if (old.handle != 0) { + retired_.push_back(Retired{old.host_va, old.size, old.gpu_bda, old.tag, old.handle}); + } + + if (old_start < start) { + const Region left{old_start, start - old_start, 0, old.tag, 0}; + regions_.emplace(left.host_va, left); + } + if (old_end > end) { + const Region right{end, old_end - end, 0, old.tag, 0}; + regions_.emplace(right.host_va, right); + } + } + } + + mutable std::mutex mutex_; + std::map regions_; + std::vector retired_; + std::function retire_hook_; +}; + +// Process-wide title host region table shared between the CPU/xmem shims and the Vulkan backend. +inline TitleHostRegions& title_host_regions() { + static TitleHostRegions instance; + return instance; +} + +} // namespace leonida diff --git a/runtime/src/vulkan_backend.h b/runtime/src/vulkan_backend.h index f4373787b1..1a25a324cd 100644 --- a/runtime/src/vulkan_backend.h +++ b/runtime/src/vulkan_backend.h @@ -19,6 +19,7 @@ #include "vulkan_depth24.h" #include "vulkan_indirect_dispatch_count.h" #include "vulkan_scratch.h" +#include "vulkan_title_regions.h" #include "vulkan_replay.h" #include "queue_families.h" #include "resource_tiling.h" @@ -1004,27 +1005,37 @@ class VulkanContext { // buffer as out of bounds, which is no reason to drop the submission. replay_.buffer_at = [this](std::uint64_t va, std::uint64_t& size, VkBuffer& buffer, VkDeviceSize& offset) { BufferVaIndex::Hit hit{}; - if (!buffer_vas_.find(va, hit, size)) return false; // prefers an aliasing buffer that holds all of it - const ResourceBinding* b = resolve(hit.id); - if (!b) return false; - buffer = b->buffer; - offset = b->buffer_offset + (va - b->va); - size = std::min(size, b->size - (va - b->va)); - return true; + if (buffer_vas_.find(va, hit, size)) { // prefers an aliasing buffer that holds all of it + const ResourceBinding* b = resolve(hit.id); + if (!b) return false; + buffer = b->buffer; + offset = b->buffer_offset + (va - b->va); + size = std::min(size, b->size - (va - b->va)); + return true; + } + return title_regions_.lookup(va, size, buffer, offset); }; // Host reads of small CPU-written inputs. Unlike buffer_at, the whole range must be in one CPU-writable // mapping: a partial read would see bytes the application has not written through the D3D12 API. The // binding's host pointer is null on DEFAULT and READBACK heaps, whose mapped bytes the GPU can write. replay_.host_at = [this](std::uint64_t va, std::uint64_t bytes, const std::uint8_t*& host) { BufferVaIndex::Hit hit{}; - if (!buffer_vas_.find(va, hit, bytes)) return HostReadStatus::absent; - const ResourceBinding* b = resolve(hit.id); - if (!b) return HostReadStatus::absent; - if (!b->host) return HostReadStatus::not_cpu_written; - const std::uint64_t offset = va - b->va; - if (offset > b->size || bytes > b->size - offset) return HostReadStatus::absent; - host = b->host + offset; - return HostReadStatus::ok; + if (buffer_vas_.find(va, hit, bytes)) { + const ResourceBinding* b = resolve(hit.id); + if (!b) return HostReadStatus::absent; + if (!b->host) return HostReadStatus::not_cpu_written; + const std::uint64_t offset = va - b->va; + if (offset > b->size || bytes > b->size - offset) return HostReadStatus::absent; + host = b->host + offset; + return HostReadStatus::ok; + } + VkBuffer dummy_buffer = VK_NULL_HANDLE; + VkDeviceSize dummy_offset = 0; + std::uint64_t available = bytes; + if (title_regions_.lookup(va, available, dummy_buffer, dummy_offset, &host) && available >= bytes) { + return HostReadStatus::ok; + } + return HostReadStatus::absent; }; if (xdxr && loaded_) { xdxr_ = std::make_unique(get, device); @@ -1133,6 +1144,26 @@ class VulkanContext { std::unique_lock lock(resource_mutex_); counted_dispatch_ = std::make_unique(get, device_, memory, limits); } + void configure_title_regions(PFN_vkGetMemoryHostPointerPropertiesEXT get_props, VkDeviceSize alignment, + const VkPhysicalDeviceMemoryProperties& memory, + TitleHostRegions* regions = &title_host_regions()) { + VulkanTitleRegionFunctions fn{}; + fn.vkCreateBuffer = vk.vkCreateBuffer; + fn.vkDestroyBuffer = vk.vkDestroyBuffer; + fn.vkGetBufferMemoryRequirements = vk.vkGetBufferMemoryRequirements; + fn.vkAllocateMemory = vk.vkAllocateMemory; + fn.vkFreeMemory = vk.vkFreeMemory; + fn.vkBindBufferMemory = vk.vkBindBufferMemory; + fn.vkGetBufferDeviceAddress = vk.vkGetBufferDeviceAddress; + fn.vkDeviceWaitIdle = vk.vkDeviceWaitIdle; + fn.vkCmdPipelineBarrier = vk.vkCmdPipelineBarrier; + fn.vkGetMemoryHostPointerPropertiesEXT = get_props; + title_regions_.configure(device_, fn, alignment, memory, regions); + } + void sync_title_regions() { title_regions_.sync_pending(); } + std::optional resolve_title_bda(std::uint64_t va) { return title_regions_.resolve_bda(va); } + void record_title_barrier(VkCommandBuffer cb) const { title_regions_.record_host_write_barrier(cb); } + const ReplayFunctions& replay_functions() const { return replay_; } VkDevice device() const { return device_; } // Debug markers become labels from here on; call before any queue or list uses the context. Incomplete sets @@ -1706,6 +1737,7 @@ class VulkanContext { QueueHolds holds_; std::unordered_map resources_; BufferVaIndex buffer_vas_; // the addressable buffers of resources_, by VA range (buffer_at) + VulkanTitleRegions title_regions_; std::unordered_map> sparse_resources_; std::unordered_map pipelines_; std::unordered_map graphics_pipelines_; @@ -2570,6 +2602,8 @@ class VulkanQueue : private QueueHolds::Holder { context_.vk.vkCmdPipelineBarrier(command_buffer, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, 0, 1, &full, 0, nullptr, 0, nullptr); } + context_.sync_title_regions(); + context_.record_title_barrier(command_buffer); if (!tracker_lock.owns_lock()) tracker_lock.lock(); if (!transfer_only && context_.bindless_prepare_ && !context_.bindless_prepare_(command_buffer)) { const bool ended = context_.vk.vkEndCommandBuffer(command_buffer) == VK_SUCCESS; diff --git a/runtime/src/vulkan_title_regions.h b/runtime/src/vulkan_title_regions.h new file mode 100644 index 0000000000..81c5154c2d --- /dev/null +++ b/runtime/src/vulkan_title_regions.h @@ -0,0 +1,434 @@ +#pragma once + +// Imports TitleHostRegions into Vulkan via VK_EXT_external_memory_host so CPU-allocated +// title memory ranges have valid VkBuffers and GPU buffer device addresses (BDA), and +// safely retires/destroys imported buffers when those ranges are unmapped or freed. + +#ifndef VK_NO_PROTOTYPES +#define VK_NO_PROTOTYPES +#endif +#include "title_host_regions.h" + +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +#ifdef _WIN32 +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN +#endif +#ifndef NOMINMAX +#define NOMINMAX +#endif +#include +#endif + +namespace leonida { + +struct VulkanTitleRegionFunctions { + PFN_vkCreateBuffer vkCreateBuffer = nullptr; + PFN_vkDestroyBuffer vkDestroyBuffer = nullptr; + PFN_vkGetBufferMemoryRequirements vkGetBufferMemoryRequirements = nullptr; + PFN_vkAllocateMemory vkAllocateMemory = nullptr; + PFN_vkFreeMemory vkFreeMemory = nullptr; + PFN_vkBindBufferMemory vkBindBufferMemory = nullptr; + PFN_vkGetBufferDeviceAddress vkGetBufferDeviceAddress = nullptr; + PFN_vkDeviceWaitIdle vkDeviceWaitIdle = nullptr; + PFN_vkCmdPipelineBarrier vkCmdPipelineBarrier = nullptr; + PFN_vkGetMemoryHostPointerPropertiesEXT vkGetMemoryHostPointerPropertiesEXT = nullptr; +}; + +class VulkanTitleRegions { +public: + VulkanTitleRegions() = default; + VulkanTitleRegions(const VulkanTitleRegions&) = delete; + VulkanTitleRegions& operator=(const VulkanTitleRegions&) = delete; + + ~VulkanTitleRegions() { + TitleHostRegions* regions = nullptr; + { + std::lock_guard lock(mutex_); + regions = regions_; + } + if (regions) { + regions->set_retire_hook({}); + } + destroy_all(); + } + + void configure(VkDevice device, const VulkanTitleRegionFunctions& fn, VkDeviceSize host_pointer_alignment, + const VkPhysicalDeviceMemoryProperties& memory_properties, + TitleHostRegions* regions = &title_host_regions()) { + destroy_all(); + { + std::lock_guard lock(mutex_); + if (regions_ && regions_ != regions) { + regions_->set_retire_hook({}); + } + device_ = device; + fn_ = fn; + alignment_ = host_pointer_alignment; + memory_properties_ = memory_properties; + regions_ = regions; + } + if (regions) { + regions->set_retire_hook([this]() { collect_retired(true); }); + } + } + + bool supported() const { + std::lock_guard lock(mutex_); + return supported_locked(); + } + + // Imports any pending TitleHostRegions entries into Vulkan via VK_EXT_external_memory_host. + void sync_pending() { + TitleHostRegions* regions = nullptr; + { + std::lock_guard lock(mutex_); + if (!supported_locked()) return; + regions = regions_; + } + + const auto pending = regions->pending_imports(); + for (const auto& region : pending) { + import_region(regions, region); + } + collect_retired(true); + } + + // Destroys Vulkan buffers/memory for any retired regions (after waiting for GPU idle if needed). + void collect_retired(bool wait_idle = true) { + TitleHostRegions* regions = nullptr; + { + std::lock_guard lock(mutex_); + regions = regions_; + if (!regions || device_ == VK_NULL_HANDLE) return; + } + + const auto retired = regions->take_retired(); + if (retired.empty()) return; + + std::vector to_destroy; + { + std::lock_guard lock(mutex_); + to_destroy.reserve(retired.size()); + for (const auto& r : retired) { + const auto it = entries_.find(r.handle); + if (it != entries_.end()) { + to_destroy.push_back(it->second); + entries_.erase(it); + } + } + } + + if (to_destroy.empty()) return; + if (wait_idle && fn_.vkDeviceWaitIdle) { + fn_.vkDeviceWaitIdle(device_); + } + for (const auto& entry : to_destroy) { + destroy_entry(entry); + } + } + + // Resolves a title host VA into an imported VkBuffer, byte offset, and optional host pointer. + bool lookup(std::uint64_t va, std::uint64_t& size, VkBuffer& buffer, VkDeviceSize& offset, + const std::uint8_t** host_ptr = nullptr) { + if (!va) return false; + TitleHostRegions* regions = nullptr; + { + std::lock_guard lock(mutex_); + if (!supported_locked()) return false; + regions = regions_; + } + + auto hit = regions->find(va); + if (!hit.found || hit.import_failed) return false; + if (hit.gpu_bda == 0 || hit.handle == 0) { + sync_pending(); + hit = regions->find(va); + if (!hit.found || hit.import_failed || hit.gpu_bda == 0 || hit.handle == 0) return false; + } + + std::lock_guard lock(mutex_); + const auto it = entries_.find(hit.handle); + if (it == entries_.end() || it->second.buffer == VK_NULL_HANDLE) return false; + if (va < it->second.aligned_start) return false; + const std::uint64_t buf_offset = va - it->second.aligned_start; + if (buf_offset >= it->second.aligned_size) return false; + + buffer = it->second.buffer; + offset = buf_offset; + const std::uint64_t remaining = hit.size - hit.offset; + size = size ? std::min(size, remaining) : remaining; + if (host_ptr) *host_ptr = reinterpret_cast(va); + return true; + } + + // Resolves a title host VA to its imported GPU BDA, lazily importing if still pending. + std::optional resolve_bda(std::uint64_t va) { + if (!va) return std::nullopt; + TitleHostRegions* regions = nullptr; + { + std::lock_guard lock(mutex_); + if (!supported_locked()) return std::nullopt; + regions = regions_; + } + + auto hit = regions->find(va); + if (!hit.found || hit.import_failed) return std::nullopt; + if (hit.gpu_bda == 0) { + sync_pending(); + return regions->resolve_bda(va); + } + return hit.gpu_bda + hit.offset; + } + + // Makes prior CPU writes to imported title host regions visible to GPU shaders and transfer/vertex/index stages. + void record_host_write_barrier(VkCommandBuffer cb) const { + if (!cb) return; + std::lock_guard lock(mutex_); + if (!supported_locked() || entries_.empty() || !fn_.vkCmdPipelineBarrier) return; + + VkMemoryBarrier barrier{VK_STRUCTURE_TYPE_MEMORY_BARRIER}; + barrier.srcAccessMask = VK_ACCESS_HOST_WRITE_BIT; + barrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_TRANSFER_READ_BIT | + VK_ACCESS_VERTEX_ATTRIBUTE_READ_BIT | VK_ACCESS_INDEX_READ_BIT | + VK_ACCESS_INDIRECT_COMMAND_READ_BIT; + fn_.vkCmdPipelineBarrier(cb, VK_PIPELINE_STAGE_HOST_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, 0, 1, &barrier, + 0, nullptr, 0, nullptr); + } + + void destroy_all() { + std::vector remaining; + VkDevice device = VK_NULL_HANDLE; + { + std::lock_guard lock(mutex_); + device = device_; + remaining.reserve(entries_.size()); + for (const auto& [handle, entry] : entries_) { + (void)handle; + remaining.push_back(entry); + } + entries_.clear(); + } + if (device != VK_NULL_HANDLE && !remaining.empty()) { + if (fn_.vkDeviceWaitIdle) fn_.vkDeviceWaitIdle(device); + for (const auto& entry : remaining) { + if (entry.buffer != VK_NULL_HANDLE && fn_.vkDestroyBuffer) { + fn_.vkDestroyBuffer(device, entry.buffer, nullptr); + } + if (entry.memory != VK_NULL_HANDLE && fn_.vkFreeMemory) { + fn_.vkFreeMemory(device, entry.memory, nullptr); + } + } + } + } + +private: + struct ImportedEntry { + VkBuffer buffer = VK_NULL_HANDLE; + VkDeviceMemory memory = VK_NULL_HANDLE; + std::uint64_t aligned_start = 0; + std::uint64_t aligned_size = 0; + std::uint64_t base_bda = 0; + }; + + bool supported_locked() const { + return device_ != VK_NULL_HANDLE && regions_ != nullptr && alignment_ != 0 && fn_.vkCreateBuffer && + fn_.vkDestroyBuffer && fn_.vkGetBufferMemoryRequirements && fn_.vkAllocateMemory && fn_.vkFreeMemory && + fn_.vkBindBufferMemory && fn_.vkGetBufferDeviceAddress && fn_.vkGetMemoryHostPointerPropertiesEXT; + } + + void destroy_entry(const ImportedEntry& entry) const { + if (entry.buffer != VK_NULL_HANDLE && fn_.vkDestroyBuffer) { + fn_.vkDestroyBuffer(device_, entry.buffer, nullptr); + } + if (entry.memory != VK_NULL_HANDLE && fn_.vkFreeMemory) { + fn_.vkFreeMemory(device_, entry.memory, nullptr); + } + } + + std::uint32_t choose_memory_type(std::uint32_t allowed_types) const { + constexpr VkMemoryPropertyFlags kPreferred = + VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT; + std::uint32_t fallback = memory_properties_.memoryTypeCount; + for (std::uint32_t i = 0; i < memory_properties_.memoryTypeCount; ++i) { + if (!(allowed_types & (1u << i))) continue; + if ((memory_properties_.memoryTypes[i].propertyFlags & kPreferred) == kPreferred) { + return i; + } + if (fallback == memory_properties_.memoryTypeCount) { + fallback = i; + } + } + return fallback; + } + + static void log_once(std::atomic& flag, const char* reason, std::uint64_t va, std::uint64_t size) { + if (!flag.exchange(true, std::memory_order_relaxed)) { + std::fprintf(stderr, "[rt] title_host_regions: %s (va=0x%llx size=0x%llx)\n", reason, + static_cast(va), static_cast(size)); + } + } + + void import_region(TitleHostRegions* regions, const TitleHostRegions::Region& region) { + if (!region.host_va || !region.size) return; + + const std::uint64_t align = alignment_; + const std::uint64_t aligned_start = region.host_va & ~(align - 1); + const std::uint64_t region_end = region.host_va + region.size; + if (region_end < region.host_va) { + regions->mark_failed(region.host_va, region.size); + return; + } + const std::uint64_t aligned_end = (region_end + (align - 1)) & ~(align - 1); + if (aligned_end <= aligned_start) { + regions->mark_failed(region.host_va, region.size); + return; + } + const std::uint64_t aligned_size = aligned_end - aligned_start; + +#ifdef _WIN32 + static std::atomic logged_uncommitted{false}; + constexpr DWORD kBadProtect = PAGE_NOACCESS | PAGE_GUARD | PAGE_WRITECOMBINE | PAGE_NOCACHE; + for (std::uint64_t at = aligned_start; at < aligned_end;) { + MEMORY_BASIC_INFORMATION mbi{}; + if (!VirtualQuery(reinterpret_cast(at), &mbi, sizeof(mbi)) || mbi.State != MEM_COMMIT || + (mbi.Protect & kBadProtect)) { + log_once(logged_uncommitted, "skipping uncommitted or uncacheable host range", aligned_start, + aligned_size); + regions->mark_failed(region.host_va, region.size); + return; + } + const std::uint64_t mbi_end = + reinterpret_cast(mbi.BaseAddress) + static_cast(mbi.RegionSize); + if (mbi_end <= at) { + regions->mark_failed(region.host_va, region.size); + return; + } + at = mbi_end; + } +#endif + + static std::atomic logged_props{false}; + VkMemoryHostPointerPropertiesEXT host_props{VK_STRUCTURE_TYPE_MEMORY_HOST_POINTER_PROPERTIES_EXT}; + if (fn_.vkGetMemoryHostPointerPropertiesEXT(device_, VK_EXTERNAL_MEMORY_HANDLE_TYPE_HOST_ALLOCATION_BIT_EXT, + reinterpret_cast(aligned_start), + &host_props) != VK_SUCCESS) { + log_once(logged_props, "vkGetMemoryHostPointerPropertiesEXT rejected host range", aligned_start, + aligned_size); + regions->mark_failed(region.host_va, region.size); + return; + } + + VkExternalMemoryBufferCreateInfo ext_buf{VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_BUFFER_CREATE_INFO}; + ext_buf.handleTypes = VK_EXTERNAL_MEMORY_HANDLE_TYPE_HOST_ALLOCATION_BIT_EXT; + + VkBufferCreateInfo buf_info{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO}; + buf_info.pNext = &ext_buf; + buf_info.size = aligned_size; + buf_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 | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT; + buf_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE; + + static std::atomic logged_buf{false}; + VkBuffer buffer = VK_NULL_HANDLE; + if (fn_.vkCreateBuffer(device_, &buf_info, nullptr, &buffer) != VK_SUCCESS) { + log_once(logged_buf, "vkCreateBuffer failed for host region", aligned_start, aligned_size); + regions->mark_failed(region.host_va, region.size); + return; + } + + static std::atomic logged_reqs{false}; + VkMemoryRequirements reqs{}; + fn_.vkGetBufferMemoryRequirements(device_, buffer, &reqs); + if (reqs.size > aligned_size) { + log_once(logged_reqs, "buffer memory requirements exceed checked host range", aligned_start, aligned_size); + fn_.vkDestroyBuffer(device_, buffer, nullptr); + regions->mark_failed(region.host_va, region.size); + return; + } + const std::uint32_t valid_types = reqs.memoryTypeBits & host_props.memoryTypeBits; + const std::uint32_t mem_type = choose_memory_type(valid_types); + static std::atomic logged_memtype{false}; + if (mem_type >= memory_properties_.memoryTypeCount) { + log_once(logged_memtype, "no compatible memory type for host region", aligned_start, aligned_size); + fn_.vkDestroyBuffer(device_, buffer, nullptr); + regions->mark_failed(region.host_va, region.size); + return; + } + + VkImportMemoryHostPointerInfoEXT import_info{VK_STRUCTURE_TYPE_IMPORT_MEMORY_HOST_POINTER_INFO_EXT}; + import_info.handleType = VK_EXTERNAL_MEMORY_HANDLE_TYPE_HOST_ALLOCATION_BIT_EXT; + import_info.pHostPointer = reinterpret_cast(aligned_start); + + VkMemoryAllocateFlagsInfo flags_info{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_FLAGS_INFO}; + flags_info.pNext = &import_info; + flags_info.flags = VK_MEMORY_ALLOCATE_DEVICE_ADDRESS_BIT; + + VkMemoryAllocateInfo alloc_info{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO}; + alloc_info.pNext = &flags_info; + alloc_info.allocationSize = aligned_size; + alloc_info.memoryTypeIndex = mem_type; + + static std::atomic logged_alloc{false}; + VkDeviceMemory memory = VK_NULL_HANDLE; + if (fn_.vkAllocateMemory(device_, &alloc_info, nullptr, &memory) != VK_SUCCESS) { + log_once(logged_alloc, "vkAllocateMemory failed for host region", aligned_start, aligned_size); + fn_.vkDestroyBuffer(device_, buffer, nullptr); + regions->mark_failed(region.host_va, region.size); + return; + } + + static std::atomic logged_bind{false}; + if (fn_.vkBindBufferMemory(device_, buffer, memory, 0) != VK_SUCCESS) { + log_once(logged_bind, "vkBindBufferMemory failed for host region", aligned_start, aligned_size); + fn_.vkDestroyBuffer(device_, buffer, nullptr); + fn_.vkFreeMemory(device_, memory, nullptr); + regions->mark_failed(region.host_va, region.size); + return; + } + + VkBufferDeviceAddressInfo bda_info{VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO}; + bda_info.buffer = buffer; + const std::uint64_t base_bda = fn_.vkGetBufferDeviceAddress(device_, &bda_info); + static std::atomic logged_bda{false}; + if (!base_bda) { + log_once(logged_bda, "vkGetBufferDeviceAddress returned 0 for host region", aligned_start, aligned_size); + fn_.vkDestroyBuffer(device_, buffer, nullptr); + fn_.vkFreeMemory(device_, memory, nullptr); + regions->mark_failed(region.host_va, region.size); + return; + } + + std::uint64_t handle = 0; + { + std::lock_guard lock(mutex_); + handle = next_handle_++; + entries_.emplace(handle, ImportedEntry{buffer, memory, aligned_start, aligned_size, base_bda}); + } + const std::uint64_t region_bda = base_bda + (region.host_va - aligned_start); + regions->mark_imported(region.host_va, region.size, region_bda, handle); + } + + mutable std::mutex mutex_; + VkDevice device_ = VK_NULL_HANDLE; + VulkanTitleRegionFunctions fn_{}; + VkDeviceSize alignment_ = 0; + VkPhysicalDeviceMemoryProperties memory_properties_{}; + TitleHostRegions* regions_ = nullptr; + std::uint64_t next_handle_ = 1; + std::unordered_map entries_; +}; + +} // namespace leonida diff --git a/runtime/test/title_host_region_gpu_test.cpp b/runtime/test/title_host_region_gpu_test.cpp new file mode 100644 index 0000000000..0fb11b5577 --- /dev/null +++ b/runtime/test/title_host_region_gpu_test.cpp @@ -0,0 +1,227 @@ +// GPU integration test for TitleHostRegions + VulkanTitleRegions + VulkanContext: +// registers a page-aligned host allocation, resolves it through VulkanContext::replay().buffer_at / host_at / +// resolve_title_bda, records a host-write barrier + vkCmdCopyBuffer into a readback buffer, verifies the GPU read +// the CPU-written pattern, and retires/unregisters without VK_ERROR_DEVICE_LOST. + +#include "../src/vulkan_backend.h" +#include "vk_test_device.h" + +#include +#include +#include +#include +#include + +#ifdef _WIN32 +#include +#endif + +namespace { + +void* alloc_host_pages(std::size_t bytes, std::size_t alignment) { +#ifdef _WIN32 + (void)alignment; + return VirtualAlloc(nullptr, bytes, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); +#else + return std::aligned_alloc(alignment, bytes); +#endif +} + +void free_host_pages(void* ptr) { +#ifdef _WIN32 + VirtualFree(ptr, 0, MEM_RELEASE); +#else + std::free(ptr); +#endif +} + +std::uint32_t find_host_visible_memory(const VkPhysicalDeviceMemoryProperties& mem, std::uint32_t type_bits) { + constexpr VkMemoryPropertyFlags kWant = + VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT; + for (std::uint32_t i = 0; i < mem.memoryTypeCount; ++i) { + if ((type_bits & (1u << i)) && (mem.memoryTypes[i].propertyFlags & kWant) == kWant) return i; + } + return mem.memoryTypeCount; +} + +} // namespace + +int main() { + vktest::Device dev; + dev.request_buffer_device_address = true; + const auto status = dev.initialize(); + if (status == vktest::DeviceStatus::unavailable) { + std::printf("title_host_region_gpu_test: skipped (no Vulkan device)\n"); + return 0; + } + if (status != vktest::DeviceStatus::ready) { + std::fprintf(stderr, "title_host_region_gpu_test: device init failed\n"); + return 1; + } + if (!dev.host_pointer_alignment || !dev.buffer_device_address) { + std::printf("title_host_region_gpu_test: skipped (missing VK_EXT_external_memory_host or BDA)\n"); + return 0; + } + + const std::size_t align = static_cast(dev.host_pointer_alignment); + const std::size_t region_size = std::max(align * 4, 16384); + void* host_mem = alloc_host_pages(region_size, align); + if (!host_mem) { + std::fprintf(stderr, "title_host_region_gpu_test: host allocation failed\n"); + return 1; + } + auto* words = static_cast(host_mem); + for (std::size_t i = 0; i < region_size / sizeof(std::uint32_t); ++i) { + words[i] = 0xA5000000u ^ static_cast(i); + } + + const auto get_mem_props = + dev.instance_fn("vkGetPhysicalDeviceMemoryProperties"); + VkPhysicalDeviceMemoryProperties mem_props{}; + get_mem_props(dev.physical, &mem_props); + + const auto get_host_props = + dev.fn("vkGetMemoryHostPointerPropertiesEXT"); + if (!get_host_props) { + std::fprintf(stderr, "title_host_region_gpu_test: vkGetMemoryHostPointerPropertiesEXT missing\n"); + free_host_pages(host_mem); + return 1; + } + + leonida::TitleHostRegions regions; + const std::uint64_t host_va = reinterpret_cast(host_mem); + regions.register_range(host_va, region_size, 1); + + int failures = 0; + { + leonida::VulkanContext ctx(dev.device_proc, dev.device, true); + ctx.configure_title_regions(get_host_props, dev.host_pointer_alignment, mem_props, ®ions); + + const auto bda = ctx.resolve_title_bda(host_va + 256); + if (!bda || *bda == 0) { + std::fprintf(stderr, "title_host_region_gpu_test: resolve_title_bda failed\n"); + ++failures; + } + + const std::uint8_t* resolved_host = nullptr; + if (ctx.replay_functions().host_at(host_va + 128, 64, resolved_host) != leonida::HostReadStatus::ok || + resolved_host != static_cast(host_mem) + 128) { + std::fprintf(stderr, "title_host_region_gpu_test: replay_functions().host_at failed\n"); + ++failures; + } + + VkBuffer src_buf = VK_NULL_HANDLE; + VkDeviceSize src_off = 0; + std::uint64_t lookup_size = 256; + if (!ctx.replay_functions().buffer_at(host_va + 64, lookup_size, src_buf, src_off) || + src_buf == VK_NULL_HANDLE || src_off != 64 || lookup_size != 256) { + std::fprintf(stderr, "title_host_region_gpu_test: replay_functions().buffer_at failed\n"); + ++failures; + } + + // Create a host-visible readback buffer and copy from the imported host region on the GPU. + const auto create_buf = dev.fn("vkCreateBuffer"); + const auto destroy_buf = dev.fn("vkDestroyBuffer"); + const auto get_reqs = dev.fn("vkGetBufferMemoryRequirements"); + const auto alloc_mem = dev.fn("vkAllocateMemory"); + const auto free_mem = dev.fn("vkFreeMemory"); + const auto bind_buf = dev.fn("vkBindBufferMemory"); + const auto map_mem = dev.fn("vkMapMemory"); + const auto unmap_mem = dev.fn("vkUnmapMemory"); + const auto create_pool = dev.fn("vkCreateCommandPool"); + const auto destroy_pool = dev.fn("vkDestroyCommandPool"); + const auto alloc_cb = dev.fn("vkAllocateCommandBuffers"); + const auto begin_cb = dev.fn("vkBeginCommandBuffer"); + const auto end_cb = dev.fn("vkEndCommandBuffer"); + const auto cmd_copy = dev.fn("vkCmdCopyBuffer"); + const auto queue_submit = dev.fn("vkQueueSubmit"); + const auto queue_wait = dev.fn("vkQueueWaitIdle"); + + VkBuffer dst_buf = VK_NULL_HANDLE; + VkDeviceMemory dst_mem = VK_NULL_HANDLE; + VkBufferCreateInfo dst_info{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO}; + dst_info.size = 256; + dst_info.usage = VK_BUFFER_USAGE_TRANSFER_DST_BIT; + dst_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE; + if (create_buf(dev.device, &dst_info, nullptr, &dst_buf) != VK_SUCCESS) { + std::fprintf(stderr, "title_host_region_gpu_test: create readback buffer failed\n"); + free_host_pages(host_mem); + return 1; + } + VkMemoryRequirements reqs{}; + get_reqs(dev.device, dst_buf, &reqs); + const std::uint32_t mem_idx = find_host_visible_memory(mem_props, reqs.memoryTypeBits); + VkMemoryAllocateInfo alloc_info{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO}; + alloc_info.allocationSize = reqs.size; + alloc_info.memoryTypeIndex = mem_idx; + if (alloc_mem(dev.device, &alloc_info, nullptr, &dst_mem) != VK_SUCCESS || + bind_buf(dev.device, dst_buf, dst_mem, 0) != VK_SUCCESS) { + std::fprintf(stderr, "title_host_region_gpu_test: readback memory failed\n"); + destroy_buf(dev.device, dst_buf, nullptr); + free_host_pages(host_mem); + return 1; + } + + VkCommandPool pool = VK_NULL_HANDLE; + VkCommandPoolCreateInfo pool_info{VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO}; + pool_info.queueFamilyIndex = dev.family; + create_pool(dev.device, &pool_info, nullptr, &pool); + VkCommandBuffer cb = VK_NULL_HANDLE; + VkCommandBufferAllocateInfo cb_info{VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO}; + cb_info.commandPool = pool; + cb_info.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY; + cb_info.commandBufferCount = 1; + alloc_cb(dev.device, &cb_info, &cb); + + VkCommandBufferBeginInfo begin_info{VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO}; + begin_info.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT; + begin_cb(cb, &begin_info); + ctx.record_title_barrier(cb); + const VkBufferCopy copy_region{src_off, 0, 256}; + cmd_copy(cb, src_buf, dst_buf, 1, ©_region); + end_cb(cb); + + VkSubmitInfo submit_info{VK_STRUCTURE_TYPE_SUBMIT_INFO}; + submit_info.commandBufferCount = 1; + submit_info.pCommandBuffers = &cb; + if (queue_submit(dev.queue, 1, &submit_info, VK_NULL_HANDLE) != VK_SUCCESS || + queue_wait(dev.queue) != VK_SUCCESS) { + std::fprintf(stderr, "title_host_region_gpu_test: GPU submit/wait failed\n"); + ++failures; + } + + void* mapped = nullptr; + if (map_mem(dev.device, dst_mem, 0, 256, 0, &mapped) == VK_SUCCESS) { + if (std::memcmp(mapped, static_cast(host_mem) + 64, 256) != 0) { + std::fprintf(stderr, "title_host_region_gpu_test: GPU readback mismatch\n"); + ++failures; + } + unmap_mem(dev.device, dst_mem); + } else { + std::fprintf(stderr, "title_host_region_gpu_test: map readback failed\n"); + ++failures; + } + + destroy_pool(dev.device, pool, nullptr); + destroy_buf(dev.device, dst_buf, nullptr); + free_mem(dev.device, dst_mem, nullptr); + + // Unregister and verify retired cleanup works before freeing host pages. + regions.unregister_range(host_va, region_size); + ctx.sync_title_regions(); + if (ctx.resolve_title_bda(host_va + 64).has_value()) { + std::fprintf(stderr, "title_host_region_gpu_test: region still resolved after unregister\n"); + ++failures; + } + } + + free_host_pages(host_mem); + if (dev.validation_errors() > dev.known_validation_errors()) { + std::fprintf(stderr, "title_host_region_gpu_test: Vulkan validation errors: %u\n", dev.validation_errors()); + ++failures; + } + if (failures == 0) { + std::printf("title_host_region_gpu_test: ok (align=%zu, bda supported)\n", align); + } + return failures ? 1 : 0; +} diff --git a/runtime/test/title_host_regions_test.cpp b/runtime/test/title_host_regions_test.cpp new file mode 100644 index 0000000000..2a4f2e7050 --- /dev/null +++ b/runtime/test/title_host_regions_test.cpp @@ -0,0 +1,233 @@ +// Unit tests for TitleHostRegions (runtime/src/title_host_regions.h). + +#include "title_host_regions.h" + +#include +#include +#include +#include +#include + +namespace { + +std::atomic failures{0}; + +void check(bool ok, const char* what) { + if (ok) { + return; + } + std::printf("FAIL: %s\n", what); + failures.fetch_add(1, std::memory_order_relaxed); +} + +void test_basic_register_and_lookup() { + leonida::TitleHostRegions table; + check(table.empty(), "starts empty"); + check(!table.find(0x1000).found, "empty table find misses"); + check(!table.resolve_bda(0x1000).has_value(), "empty table resolve_bda misses"); + + // Zero host_va or zero size is ignored. + table.register_range(0, 0x1000, 1); + table.register_range(0x1000, 0, 2); + check(table.empty(), "zero host_va or size ignored"); + + table.register_range(0x10000, 0x1000, 0xAA); + table.register_range(0x20000, 0x2000, 0xBB); + check(table.size() == 2, "two disjoint regions registered"); + + check(!table.find(0).found, "va=0 never matches"); + check(!table.find(0x0FFFF).found, "one byte before first region misses"); + check(!table.find(0x11000).found, "one byte past first region misses"); + check(!table.find(0x1FFFF).found, "gap before second region misses"); + check(!table.find(0x22000).found, "one byte past second region misses"); + + auto l1 = table.find(0x10000); + check(l1.found && l1.host_va == 0x10000 && l1.size == 0x1000 && l1.gpu_bda == 0 && l1.offset == 0, + "first byte of first region"); + + auto l2 = table.find(0x10FFF); + check(l2.found && l2.host_va == 0x10000 && l2.size == 0x1000 && l2.offset == 0x0FFF, + "last byte of first region"); + + auto l3 = table.find(0x20500); + check(l3.found && l3.host_va == 0x20000 && l3.size == 0x2000 && l3.offset == 0x500, + "interior byte of second region"); + + // Before mark_imported, resolve_bda must return nullopt. + check(!table.resolve_bda(0x10000).has_value(), "unimported region has no BDA"); + check(!table.resolve_bda(0x20500).has_value(), "unimported second region has no BDA"); +} + +void test_import_resolve_and_retire() { + leonida::TitleHostRegions table; + table.register_range(0x100000, 0x4000, 1); + table.register_range(0x200000, 0x8000, 2); + + auto pending = table.pending_imports(); + check(pending.size() == 2, "two pending imports"); + check(pending[0].host_va == 0x100000 && pending[0].size == 0x4000 && pending[0].tag == 1, + "first pending import matches"); + check(pending[1].host_va == 0x200000 && pending[1].size == 0x8000 && pending[1].tag == 2, + "second pending import matches"); + + table.mark_imported(0x100000, 0x4000, 0x8000'0000ULL, 0x1111ULL); + pending = table.pending_imports(); + check(pending.size() == 1 && pending[0].host_va == 0x200000, "only second region remains pending"); + + auto bda0 = table.resolve_bda(0x100000); + auto bda_mid = table.resolve_bda(0x101234); + auto bda_end = table.resolve_bda(0x103FFF); + check(bda0.has_value() && *bda0 == 0x8000'0000ULL, "resolve_bda at region start"); + check(bda_mid.has_value() && *bda_mid == 0x8000'1234ULL, "resolve_bda at region interior"); + check(bda_end.has_value() && *bda_end == 0x8000'3FFFULL, "resolve_bda at region last byte"); + check(!table.resolve_bda(0x104000).has_value(), "resolve_bda past region end"); + + // Unregistering an imported region detaches its handle into retired. + table.unregister_range(0x100000, 0x4000); + check(!table.find(0x100000).found, "unregistered region is gone"); + check(!table.resolve_bda(0x100000).has_value(), "unregistered region BDA is gone"); + + auto retired = table.take_retired(); + check(retired.size() == 1, "one retired entry after unregister"); + check(retired[0].host_va == 0x100000 && retired[0].size == 0x4000 && + retired[0].gpu_bda == 0x8000'0000ULL && retired[0].handle == 0x1111ULL, + "retired entry preserves handle and BDA"); + + // Second take_retired must be empty. + check(table.take_retired().empty(), "take_retired drains the queue"); + + // Unregistering an unimported region does not emit a retired entry. + table.unregister_range(0x200000, 0x8000); + check(table.take_retired().empty(), "unimported region produces no retired entry"); + check(table.empty(), "table is empty after unregistering all"); +} + +void test_partial_unmap_splitting() { + leonida::TitleHostRegions table; + + // 1. Punch a hole in the middle of an imported region. + table.register_range(0x10000, 0x6000, 77); // [0x10000, 0x16000) + table.mark_imported(0x10000, 0x6000, 0x9000'0000ULL, 0xCAFEULL); + + table.unregister_range(0x12000, 0x2000); // remove [0x12000, 0x14000) + check(table.size() == 2, "middle unmap splits into two regions"); + + auto retired = table.take_retired(); + check(retired.size() == 1 && retired[0].handle == 0xCAFEULL, "split retires original imported handle"); + + auto left = table.find(0x11FFF); + auto hole = table.find(0x12000); + auto right = table.find(0x14000); + check(left.found && left.host_va == 0x10000 && left.size == 0x2000 && left.gpu_bda == 0, + "left split [0x10000, 0x12000) reset to pending"); + check(!hole.found, "hole [0x12000, 0x14000) is unmapped"); + check(right.found && right.host_va == 0x14000 && right.size == 0x2000 && right.gpu_bda == 0, + "right split [0x14000, 0x16000) reset to pending"); + + // Surviving splits should be pending re-import with original tag preserved. + auto pending = table.pending_imports(); + check(pending.size() == 2 && pending[0].tag == 77 && pending[1].tag == 77, + "split remainders keep tag and are pending import"); + + // 2. Trim head and tail across multiple regions. + table.unregister_range(0x0F000, 0x2000); // trims [0x10000, 0x11000) from left + auto trimmed_left = table.find(0x11000); + check(trimmed_left.found && trimmed_left.host_va == 0x11000 && trimmed_left.size == 0x1000, + "head trim leaves [0x11000, 0x12000)"); + check(!table.find(0x10000).found, "trimmed head is gone"); + + table.unregister_range(0x15000, 0x4000); // trims [0x15000, 0x16000) from right + auto trimmed_right = table.find(0x14000); + check(trimmed_right.found && trimmed_right.host_va == 0x14000 && trimmed_right.size == 0x1000, + "tail trim leaves [0x14000, 0x15000)"); + check(!table.find(0x15000).found, "trimmed tail is gone"); + + // 3. Unregister spanning multiple disjoint regions. + table.register_range(0x20000, 0x1000, 1); + table.register_range(0x22000, 0x1000, 2); + table.mark_imported(0x20000, 0x1000, 0xA000'0000ULL, 10); + table.mark_imported(0x22000, 0x1000, 0xB000'0000ULL, 20); + table.unregister_range(0x10000, 0x20000); // covers [0x11000..0x23000) + check(table.empty(), "spanning unregister clears all covered regions"); + retired = table.take_retired(); + check(retired.size() == 2 && retired[0].handle == 10 && retired[1].handle == 20, + "spanning unregister retires both imported handles"); +} + +void test_overlapping_reregister_and_stale_import() { + leonida::TitleHostRegions table; + table.register_range(0x50000, 0x4000, 1); + table.mark_imported(0x50000, 0x4000, 0xC000'0000ULL, 0x5555ULL); + + // Registering an overlapping range splits/replaces the stale entry and retires its handle. + table.register_range(0x51000, 0x2000, 2); + check(table.size() == 3, "overlapping register splits old region into 3 parts"); + auto retired = table.take_retired(); + check(retired.size() == 1 && retired[0].handle == 0x5555ULL, "overlapping register retires stale handle"); + + auto mid = table.find(0x51500); + check(mid.found && mid.host_va == 0x51000 && mid.size == 0x2000 && mid.gpu_bda == 0, + "new overlapping region is pending"); + + // Stale mark_imported for a region that was already unregistered must retire the handle rather than leak it. + table.mark_imported(0x999000, 0x1000, 0xD000'0000ULL, 0xDEADULL); + retired = table.take_retired(); + check(retired.size() == 1 && retired[0].handle == 0xDEADULL, + "stale mark_imported for missing region retires handle"); +} + +void test_concurrent_access() { + leonida::TitleHostRegions table; + constexpr int kThreads = 4; + constexpr int kIters = 200; + std::atomic stop{false}; + + std::vector workers; + for (int t = 0; t < kThreads; ++t) { + workers.emplace_back([&, t]() { + const std::uint64_t base = 0x1000'0000ULL + static_cast(t) * 0x100'0000ULL; + for (int i = 0; i < kIters; ++i) { + const std::uint64_t va = base + static_cast(i) * 0x1000ULL; + table.register_range(va, 0x1000, static_cast(t)); + table.mark_imported(va, 0x1000, 0x8000'0000ULL + va, va); + auto bda = table.resolve_bda(va + 0x100); + check(bda.has_value() && *bda == 0x8000'0000ULL + va + 0x100, "concurrent resolve_bda"); + table.unregister_range(va, 0x800); + } + }); + } + + std::thread reader([&]() { + while (!stop.load(std::memory_order_relaxed)) { + (void)table.pending_imports(); + (void)table.take_retired(); + (void)table.find(0x1000'0100ULL); + } + }); + + for (auto& w : workers) { + w.join(); + } + stop.store(true, std::memory_order_relaxed); + reader.join(); + + (void)table.take_retired(); + check(table.size() == kThreads * kIters, "all half-unmapped regions remain"); +} + +} // namespace + +int main() { + test_basic_register_and_lookup(); + test_import_resolve_and_retire(); + test_partial_unmap_splitting(); + test_overlapping_reregister_and_stale_import(); + test_concurrent_access(); + + if (failures.load() != 0) { + std::printf("FAILED: %d check(s)\n", failures.load()); + return 1; + } + std::printf("PASS: all title_host_regions tests passed\n"); + return 0; +}