From 42636ba12750992bbb2cb0e6ebf289af330ea3bf Mon Sep 17 00:00:00 2001 From: CamilleLaVey Date: Fri, 7 Aug 2026 00:38:36 -0400 Subject: [PATCH 01/27] [memory, vulkan] Initial implementation for Unified Memory --- .../features/settings/model/BooleanSetting.kt | 1 + .../settings/model/view/SettingsItem.kt | 7 + .../settings/ui/SettingsFragmentPresenter.kt | 1 + .../app/src/main/res/values/strings.xml | 2 + src/common/heap_tracker.cpp | 48 +- src/common/heap_tracker.h | 6 + src/common/host_memory.cpp | 409 +++++++++++++++++- src/common/host_memory.h | 21 +- src/common/memory_detect.cpp | 55 +++ src/common/memory_detect.h | 4 + src/common/settings.h | 3 + src/core/core.cpp | 6 +- src/core/device_memory.cpp | 11 +- src/core/device_memory_manager.h | 35 ++ src/core/device_memory_manager.inc | 5 + src/qt_common/config/shared_translation.cpp | 2 + src/video_core/buffer_cache/buffer_cache.h | 222 +++++++++- .../buffer_cache/buffer_cache_base.h | 17 +- .../renderer_opengl/gl_buffer_cache.h | 1 + .../renderer_vulkan/vk_buffer_cache.cpp | 87 ++++ .../renderer_vulkan/vk_buffer_cache.h | 29 ++ .../renderer_vulkan/vk_rasterizer.cpp | 7 + .../vulkan_common/vulkan_device.cpp | 50 +++ src/video_core/vulkan_common/vulkan_device.h | 37 ++ .../vulkan_common/vulkan_memory_allocator.cpp | 310 +++++++++++++ .../vulkan_common/vulkan_memory_allocator.h | 62 +++ .../vulkan_common/vulkan_wrapper.cpp | 4 + src/video_core/vulkan_common/vulkan_wrapper.h | 32 ++ 28 files changed, 1427 insertions(+), 47 deletions(-) diff --git a/src/android/app/src/main/java/org/yuzu/yuzu_emu/features/settings/model/BooleanSetting.kt b/src/android/app/src/main/java/org/yuzu/yuzu_emu/features/settings/model/BooleanSetting.kt index ca3309245e..bef5194871 100644 --- a/src/android/app/src/main/java/org/yuzu/yuzu_emu/features/settings/model/BooleanSetting.kt +++ b/src/android/app/src/main/java/org/yuzu/yuzu_emu/features/settings/model/BooleanSetting.kt @@ -27,6 +27,7 @@ enum class BooleanSetting(override val key: String) : AbstractBooleanSetting { RENDERER_ASYNCHRONOUS_GPU_EMULATION("use_asynchronous_gpu_emulation"), RENDERER_ASYNC_PRESENTATION("async_presentation"), RENDERER_ASYNCHRONOUS_SHADERS("use_asynchronous_shaders"), + RENDERER_UNIFIED_MEMORY("use_unified_memory"), RENDERER_REACTIVE_FLUSHING("use_reactive_flushing"), ENABLE_BUFFER_HISTORY("enable_buffer_history"), USE_OPTIMIZED_VERTEX_BUFFERS("use_optimized_vertex_buffers"), diff --git a/src/android/app/src/main/java/org/yuzu/yuzu_emu/features/settings/model/view/SettingsItem.kt b/src/android/app/src/main/java/org/yuzu/yuzu_emu/features/settings/model/view/SettingsItem.kt index 3f38831a17..d8853985e4 100644 --- a/src/android/app/src/main/java/org/yuzu/yuzu_emu/features/settings/model/view/SettingsItem.kt +++ b/src/android/app/src/main/java/org/yuzu/yuzu_emu/features/settings/model/view/SettingsItem.kt @@ -785,6 +785,13 @@ abstract class SettingsItem( descriptionId = R.string.renderer_asynchronous_shaders_description ) ) + put( + SwitchSetting( + BooleanSetting.RENDERER_UNIFIED_MEMORY, + titleId = R.string.renderer_unified_memory, + descriptionId = R.string.renderer_unified_memory_description + ) + ) put( SingleChoiceSetting( IntSetting.FAST_GPU_TIME, diff --git a/src/android/app/src/main/java/org/yuzu/yuzu_emu/features/settings/ui/SettingsFragmentPresenter.kt b/src/android/app/src/main/java/org/yuzu/yuzu_emu/features/settings/ui/SettingsFragmentPresenter.kt index ca282ba159..9b987d8159 100644 --- a/src/android/app/src/main/java/org/yuzu/yuzu_emu/features/settings/ui/SettingsFragmentPresenter.kt +++ b/src/android/app/src/main/java/org/yuzu/yuzu_emu/features/settings/ui/SettingsFragmentPresenter.kt @@ -558,6 +558,7 @@ class SettingsFragmentPresenter( add(BooleanSetting.FIX_BLOOM_EFFECTS.key) add(BooleanSetting.EMULATE_BGR565.key) add(BooleanSetting.RENDERER_ASYNCHRONOUS_SHADERS.key) + add(BooleanSetting.RENDERER_UNIFIED_MEMORY.key) add(IntSetting.ANDROID_PIPELINE_WORKERS.key) add(BooleanSetting.RENDERER_ASYNCHRONOUS_GPU_EMULATION.key) add(BooleanSetting.RENDERER_ASYNC_PRESENTATION.key) diff --git a/src/android/app/src/main/res/values/strings.xml b/src/android/app/src/main/res/values/strings.xml index 730f6bbade..db55f4c262 100644 --- a/src/android/app/src/main/res/values/strings.xml +++ b/src/android/app/src/main/res/values/strings.xml @@ -605,6 +605,8 @@ Enables a legacy handling for the rescale configuration pass for games by using a quick rescale path Use asynchronous shaders Compiles shaders asynchronously. This may reduce stutters but may also introduce glitches. + Unified memory access + Allows GPU write buffer readbacks directly into guest memory, skipping the CPU staging copy. GPU Unswizzle Settings Configure GPU-based texture unswizzling parameters or disable it entirely. Adjust these settings to balance performance and texture loading quality. Enable GPU Unswizzle diff --git a/src/common/heap_tracker.cpp b/src/common/heap_tracker.cpp index b72abb16d8..0ca8683a34 100644 --- a/src/common/heap_tracker.cpp +++ b/src/common/heap_tracker.cpp @@ -4,34 +4,43 @@ // SPDX-FileCopyrightText: Copyright 2023 yuzu Emulator Project // SPDX-License-Identifier: GPL-2.0-or-later -#include +#include #include "common/heap_tracker.h" #include "common/logging.h" #include "common/assert.h" +#include "common/memory_detect.h" namespace Common { namespace { -s64 GetMaxPermissibleResidentMapCount() { +s64 GetMaxPermissibleResidentMapCount(const Common::HostMemory& buffer) { // Default value. - s64 value = 65530; + constexpr s64 DefaultMaxMapCount = 65530; // Try to read how many mappings we can make. - std::ifstream s("/proc/sys/vm/max_map_count"); - s >> value; + const u64 reported = Common::GetMaxMapCount(); + const s64 value = reported != 0 ? static_cast(reported) : DefaultMaxMapCount; // Print, for debug. LOG_INFO(HW_Memory, "Current maximum map count: {}", value); // Allow 20000 maps for other code and to account for split inaccuracy. - return std::max(value - 20000, 0); + constexpr s64 ForeignMapReservation = 20000; + + const size_t hardware_buffer_windows = buffer.BackingHardwareBuffers().size(); + const s64 unmergeable_window_boundaries = + hardware_buffer_windows != 0 ? static_cast(hardware_buffer_windows) + 1 : 0; + + return std::max(value - ForeignMapReservation - unmergeable_window_boundaries, 0); } } // namespace HeapTracker::HeapTracker(Common::HostMemory& buffer) - : m_buffer(buffer), m_max_resident_map_count(GetMaxPermissibleResidentMapCount()) {} + : m_buffer(buffer), + m_has_hardware_buffer_backing(!buffer.BackingHardwareBuffers().empty()), + m_max_resident_map_count(GetMaxPermissibleResidentMapCount(buffer)) {} HeapTracker::~HeapTracker() = default; void HeapTracker::Map(size_t virtual_offset, size_t host_offset, size_t length, @@ -85,7 +94,8 @@ void HeapTracker::Unmap(size_t virtual_offset, size_t size, bool is_separate_hea // If resident, erase from resident map. if (item->is_resident) { - ASSERT(--m_resident_map_count >= 0); + m_resident_map_count -= this->HostMapCount(item->paddr, item->size); + ASSERT(m_resident_map_count >= 0); m_resident_mappings.erase(m_resident_mappings.iterator_to(*item)); } @@ -191,7 +201,7 @@ bool HeapTracker::DeferredMapSeparateHeap(size_t virtual_offset) { // This map is now resident. it->is_resident = true; - m_resident_map_count++; + m_resident_map_count += this->HostMapCount(it->paddr, it->size); m_resident_mappings.insert(*it); } @@ -213,17 +223,17 @@ void HeapTracker::RebuildSeparateHeapAddressSpace() { // Despite being worse in theory, this has proven to be better in practice than more // regularly dumping a smaller amount, because it significantly reduces average case // lock contention. - std::size_t const desired_count = (std::min)(m_resident_map_count, m_max_resident_map_count) / 2; - std::size_t const evict_count = m_resident_map_count - desired_count; + s64 const desired_count = (std::min)(m_resident_map_count, m_max_resident_map_count) / 2; auto it = m_resident_mappings.begin(); - for (size_t i = 0; i < evict_count && it != m_resident_mappings.end(); i++) { + while (m_resident_map_count > desired_count && it != m_resident_mappings.end()) { // Unmark and unmap. it->is_resident = false; m_buffer.Unmap(it->vaddr, it->size, false); // Advance. - ASSERT(--m_resident_map_count >= 0); + m_resident_map_count -= this->HostMapCount(it->paddr, it->size); + ASSERT(m_resident_map_count >= 0); it = m_resident_mappings.erase(it); } } @@ -245,6 +255,7 @@ void HeapTracker::SplitHeapMapLocked(VAddr offset) { // Cache the original values. auto* const left = std::addressof(*it); const size_t orig_size = left->size; + const s64 orig_host_map_count = this->HostMapCount(left->paddr, orig_size); // Adjust the left map. const size_t left_size = offset - left->vaddr; @@ -266,11 +277,20 @@ void HeapTracker::SplitHeapMapLocked(VAddr offset) { // If resident, also insert into resident map. if (right->is_resident) { - m_resident_map_count++; + m_resident_map_count += this->HostMapCount(left->paddr, left->size) + + this->HostMapCount(right->paddr, right->size) - + orig_host_map_count; m_resident_mappings.insert(*right); } } +s64 HeapTracker::HostMapCount(PAddr paddr, size_t size) const { + if (!m_has_hardware_buffer_backing) { + return size != 0 ? 1 : 0; + } + return static_cast(m_buffer.BackingMapCount(paddr, size)); +} + HeapTracker::AddrTree::iterator HeapTracker::GetNearestHeapMapLocked(VAddr offset) { const SeparateHeapMap key{ .vaddr = offset, diff --git a/src/common/heap_tracker.h b/src/common/heap_tracker.h index ee5b0bf43a..8be66a1d4d 100644 --- a/src/common/heap_tracker.h +++ b/src/common/heap_tracker.h @@ -1,3 +1,6 @@ +// SPDX-FileCopyrightText: Copyright 2026 Eden Emulator Project +// SPDX-License-Identifier: GPL-3.0-or-later + // SPDX-FileCopyrightText: Copyright 2023 yuzu Emulator Project // SPDX-License-Identifier: GPL-2.0-or-later @@ -82,10 +85,13 @@ private: AddrTree::iterator GetNearestHeapMapLocked(VAddr offset); + s64 HostMapCount(PAddr paddr, size_t size) const; + void RebuildSeparateHeapAddressSpace(); private: Common::HostMemory& m_buffer; + const bool m_has_hardware_buffer_backing; const s64 m_max_resident_map_count; std::shared_mutex m_rebuild_lock{}; diff --git a/src/common/host_memory.cpp b/src/common/host_memory.cpp index 75a9da80e9..9110dbc914 100644 --- a/src/common/host_memory.cpp +++ b/src/common/host_memory.cpp @@ -51,14 +51,45 @@ #endif // ^^^ POSIX ^^^ +#include #include #include +#include #include "common/alignment.h" #include "common/assert.h" #include "common/free_region_manager.h" #include "common/host_memory.h" #include "common/logging.h" +#include "common/memory_detect.h" +#include "common/settings.h" + +#ifdef __ANDROID__ +#include +#include + +namespace { + +struct NativeHandle { + int version; + int numFds; + int numInts; + int data[1]; +}; + +using PFN_AHardwareBuffer_getNativeHandle = const NativeHandle* (*)(const AHardwareBuffer*); + +PFN_AHardwareBuffer_getNativeHandle ResolveGetNativeHandle() { + void* const lib = dlopen("libnativewindow.so", RTLD_NOW); + if (lib == nullptr) { + return nullptr; + } + return reinterpret_cast( + dlsym(lib, "AHardwareBuffer_getNativeHandle")); +} + +} // namespace +#endif #if defined(__ANDROID__) && __ANDROID_API__ < 30 #include @@ -75,6 +106,12 @@ namespace Common { [[maybe_unused]] constexpr size_t PageAlignment = 0x1000; [[maybe_unused]] constexpr size_t HugePageSize = 0x200000; +static std::atomic committed_backing_size{}; + +u64 GetCommittedBackingSize() noexcept { + return committed_backing_size.load(std::memory_order_relaxed); +} + #ifdef _WIN32 // Manually imported for MinGW compatibility @@ -122,7 +159,7 @@ static void GetFuncAddress(Common::DynamicLibrary& dll, const char* name, T& pfn class HostMemory::Impl { public: - explicit Impl(size_t backing_size_, size_t virtual_size_) + explicit Impl(size_t backing_size_, size_t virtual_size_, size_t) : backing_size{backing_size_} , virtual_size{virtual_size_} , process{GetCurrentProcess()} @@ -236,6 +273,10 @@ public: UNREACHABLE(); } + bool IsBackingShared() const noexcept { + return true; + } + const size_t backing_size; ///< Size of the backing memory in bytes const size_t virtual_size; ///< Size of the virtual address placeholder in bytes @@ -512,9 +553,10 @@ static int shm_open_anon(int flags, mode_t mode) { class HostMemory::Impl { public: - explicit Impl(size_t backing_size_, size_t virtual_size_) + explicit Impl(size_t backing_size_, size_t virtual_size_, size_t preferred_offset_) : backing_size{backing_size_} , virtual_size{virtual_size_} + , preferred_offset{preferred_offset_} {} bool Init() { @@ -554,10 +596,15 @@ public: LOG_WARNING(Common_Memory, "Using private mappings instead of shared ones"); backing_base = static_cast(mmap(nullptr, backing_size, PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_PRIVATE | MAP_NOCORE, -1, 0)); if (fd > 0) { - fd = -1; close(fd); } + fd = -1; } else { +#ifdef __ANDROID__ + if (InitAhbBacking()) { + return InitVirtual(); + } +#endif backing_base = static_cast(mmap(nullptr, backing_size, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_NOCORE, fd, 0)); } if (backing_base == MAP_FAILED) { @@ -565,7 +612,10 @@ public: return false; } - // Virtual memory initialization + return InitVirtual(); + } + + bool InitVirtual() { virtual_base = virtual_map_base = static_cast(ChooseVirtualBase(virtual_size)); if (virtual_base == MAP_FAILED) { LOG_CRITICAL(HW_Memory, "mmap failed: {}", strerror(errno)); @@ -578,6 +628,277 @@ public: return true; } +#ifdef __ANDROID__ + static AHardwareBuffer_Desc MakeBlobDesc(size_t len) { + return AHardwareBuffer_Desc{ + .width = static_cast(len), + .height = 1, + .layers = 1, + .format = AHARDWAREBUFFER_FORMAT_BLOB, + .usage = AHARDWAREBUFFER_USAGE_CPU_READ_OFTEN | + AHARDWAREBUFFER_USAGE_CPU_WRITE_OFTEN | + AHARDWAREBUFFER_USAGE_GPU_DATA_BUFFER, + .stride = 0, + .rfu0 = 0, + .rfu1 = 0, + }; + } + + static bool ProbeAhbBacking(PFN_AHardwareBuffer_getNativeHandle get_native_handle) { + const AHardwareBuffer_Desc desc = MakeBlobDesc(PageAlignment * 2); + AHardwareBuffer* buffer{}; + if (AHardwareBuffer_allocate(&desc, &buffer) != 0 || buffer == nullptr) { + LOG_WARNING(HW_Memory, "Hardware buffer probe allocation failed"); + return false; + } + const NativeHandle* const handle = get_native_handle(buffer); + if (handle == nullptr || handle->numFds < 1) { + LOG_WARNING(HW_Memory, "Hardware buffer has no mappable file descriptor"); + AHardwareBuffer_release(buffer); + return false; + } + const int probe_fd = handle->data[0]; + bool ok = true; + const auto try_map = [&](int prot, off_t offset, const char* what) { + if (!ok) { + return; + } + void* const ptr = mmap(nullptr, PageAlignment, prot, MAP_SHARED, probe_fd, offset); + if (ptr == MAP_FAILED) { + LOG_WARNING(HW_Memory, "Hardware buffer backing rejects {}: {}", what, + strerror(errno)); + ok = false; + return; + } + munmap(ptr, PageAlignment); + }; + try_map(PROT_READ | PROT_WRITE, 0, "shared mappings"); + try_map(PROT_READ | PROT_WRITE, static_cast(PageAlignment), "mappings at an offset"); +#ifdef ARCHITECTURE_arm64 + try_map(PROT_READ | PROT_EXEC, 0, "executable mappings"); +#endif + AHardwareBuffer_release(buffer); + return ok; + } + + size_t ComputeAhbWindowCount(size_t window_size) const { + const u64 total_physical = Common::GetMemInfo().TotalPhysicalMemory; + if (total_physical == 0) { + LOG_WARNING(HW_Memory, "Host memory size is unknown, not committing hardware buffers"); + return 0; + } + constexpr u64 MinimumTotalPhysical = 5632ULL << 20; + if (total_physical < MinimumTotalPhysical) { + LOG_INFO(HW_Memory, + "Skipping hardware buffer backing, {} MiB of RAM is below the {} MiB minimum", + total_physical >> 20, MinimumTotalPhysical >> 20); + return 0; + } + constexpr u64 MaxWindows = 2; + u64 windows = MaxWindows; + windows = (std::min)(windows, (total_physical / 6) / window_size); + const u64 available = Common::GetAvailablePhysicalMemory(); + if (available != 0) { + constexpr u64 Headroom = 2ULL << 30; + const u64 spare = available > Headroom ? available - Headroom : 0; + windows = (std::min)(windows, spare / window_size); + } + windows = (std::min)(windows, static_cast(backing_size) / window_size); + if (windows == 0) { + LOG_INFO(HW_Memory, + "Skipping hardware buffer backing, no {} MiB window fits on a {} MiB system " + "with {} MiB available", + window_size >> 20, total_physical >> 20, available >> 20); + return 0; + } + return static_cast(windows); + } + + bool InitAhbBacking() { + if (!Settings::values.use_unified_memory.GetValue()) { + return false; + } + static const PFN_AHardwareBuffer_getNativeHandle get_native_handle = + ResolveGetNativeHandle(); + if (get_native_handle == nullptr) { + LOG_WARNING(HW_Memory, "AHardwareBuffer_getNativeHandle is not available"); + return false; + } + constexpr size_t WindowCandidates[] = { + 512ULL << 20, + 256ULL << 20, + 128ULL << 20, + 64ULL << 20, + }; + static_assert(WindowCandidates[0] <= 0xFFFFFFFFull, + "AHARDWAREBUFFER_FORMAT_BLOB encodes its size in a u32 width"); + size_t window_size = 0; + for (const size_t candidate : WindowCandidates) { + const AHardwareBuffer_Desc candidate_desc = MakeBlobDesc(candidate); + if (AHardwareBuffer_isSupported(&candidate_desc) != 0) { + window_size = candidate; + break; + } + LOG_INFO(HW_Memory, "Allocator rejects {} MiB hardware buffer windows", candidate >> 20); + } + if (window_size == 0) { + LOG_WARNING(HW_Memory, "No hardware buffer window size is supported"); + return false; + } + const size_t num_windows = ComputeAhbWindowCount(window_size); + if (num_windows == 0) { + return false; + } + if (!ProbeAhbBacking(get_native_handle)) { + return false; + } + const size_t aligned_backing = Common::AlignDown(backing_size, window_size); + const size_t region_size = num_windows * window_size; + const size_t region_base = Common::AlignDown( + (std::min)(preferred_offset, aligned_backing - region_size), window_size); + + std::vector buffers; + std::vector buffer_fds; + const auto cleanup = [&] { + for (AHardwareBuffer* buffer : buffers) { + AHardwareBuffer_release(buffer); + } + buffers.clear(); + buffer_fds.clear(); + }; + for (size_t i = 0; i < num_windows; ++i) { + const AHardwareBuffer_Desc desc = MakeBlobDesc(window_size); + AHardwareBuffer* buffer{}; + if (AHardwareBuffer_allocate(&desc, &buffer) != 0 || buffer == nullptr) { + LOG_WARNING(HW_Memory, "Hardware buffer allocation failed for window {} of {}", i, + num_windows); + cleanup(); + return false; + } + buffers.push_back(buffer); + const NativeHandle* const handle = get_native_handle(buffer); + if (handle == nullptr || handle->numFds < 1) { + LOG_WARNING(HW_Memory, "Hardware buffer has no mappable file descriptor"); + cleanup(); + return false; + } + const int buffer_fd = handle->data[0]; + const off_t buffer_len = lseek(buffer_fd, 0, SEEK_END); + if (buffer_len < static_cast(window_size)) { + LOG_WARNING(HW_Memory, "Hardware buffer descriptor smaller than requested"); + cleanup(); + return false; + } + buffer_fds.push_back(buffer_fd); + } + u8* const base = static_cast(mmap(nullptr, backing_size, PROT_NONE, + MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0)); + if (base == MAP_FAILED) { + LOG_WARNING(HW_Memory, "Failed to reserve backing address space: {}", strerror(errno)); + cleanup(); + return false; + } + const auto map_over_reservation = [&](size_t offset, size_t len, int map_fd, + off_t map_offset) { + if (len == 0) { + return true; + } + if (mmap(base + offset, len, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_FIXED, map_fd, + map_offset) == MAP_FAILED) { + LOG_WARNING(HW_Memory, "Backing mmap failed: {}", strerror(errno)); + munmap(base, backing_size); + cleanup(); + return false; + } + return true; + }; + if (!map_over_reservation(0, region_base, fd, 0)) { + return false; + } + for (size_t i = 0; i < num_windows; ++i) { + if (!map_over_reservation(region_base + i * window_size, window_size, buffer_fds[i], + 0)) { + return false; + } + } + const size_t tail_offset = region_base + region_size; + if (!map_over_reservation(tail_offset, backing_size - tail_offset, fd, + static_cast(tail_offset))) { + return false; + } + backing_base = base; + ahb_windows = std::move(buffers); + ahb_fds = std::move(buffer_fds); + ahb_window_size = window_size; + ahb_base = region_base; + ahb_bytes = region_size; + committed_backing_size.store(region_size, std::memory_order_relaxed); + LOG_INFO(HW_Memory, + "Guest memory {:#x}-{:#x} backed by {} hardware buffer windows, {} MiB committed", + region_base, region_base + region_size, ahb_windows.size(), region_size >> 20); + return true; + } + + void MapBackingRange(size_t virtual_offset, size_t host_offset, size_t length, int prot_flags) { + while (length > 0) { + int map_fd = fd; + off_t map_offset = static_cast(host_offset); + size_t chunk = length; + if (host_offset < ahb_base) { + chunk = (std::min)(chunk, ahb_base - host_offset); + } else if (host_offset < ahb_base + ahb_bytes) { + const size_t relative = host_offset - ahb_base; + const size_t window = relative / ahb_window_size; + const size_t local = relative % ahb_window_size; + map_fd = ahb_fds[window]; + map_offset = static_cast(local); + chunk = (std::min)(chunk, ahb_window_size - local); + } + void* const ret = mmap(virtual_base + virtual_offset, chunk, prot_flags, + MAP_SHARED | MAP_FIXED, map_fd, map_offset); + ASSERT_MSG(ret != MAP_FAILED, "mmap: {}", strerror(errno)); + virtual_offset += chunk; + host_offset += chunk; + length -= chunk; + } + } + + size_t BackingMapCount(size_t host_offset, size_t length) const noexcept { + if (length == 0) { + return 0; + } + if (ahb_bytes == 0) { + return 1; + } + size_t count = 0; + while (length > 0) { + size_t chunk = length; + if (host_offset < ahb_base) { + chunk = (std::min)(chunk, ahb_base - host_offset); + } else if (host_offset < ahb_base + ahb_bytes) { + const size_t local = (host_offset - ahb_base) % ahb_window_size; + chunk = (std::min)(chunk, ahb_window_size - local); + } + host_offset += chunk; + length -= chunk; + ++count; + } + return count; + } + + std::span AhbWindows() const noexcept { + return ahb_windows; + } + + size_t AhbWindowSize() const noexcept { + return ahb_bytes != 0 ? ahb_window_size : 0; + } + + size_t AhbBase() const noexcept { + return ahb_base; + } +#endif + ~Impl() { Release(); } @@ -606,6 +927,12 @@ public: #ifdef ARCHITECTURE_arm64 if (True(perms & MemoryPermission::Execute)) prot_flags |= PROT_EXEC; +#endif +#ifdef __ANDROID__ + if (ahb_bytes != 0) { + MapBackingRange(virtual_offset, host_offset, length, prot_flags); + return; + } #endif int flags = (fd >= 0 ? MAP_SHARED : MAP_PRIVATE) | MAP_FIXED; void* ret = mmap(virtual_base + virtual_offset, length, prot_flags, flags, fd, host_offset); @@ -651,8 +978,18 @@ public: virtual_base = nullptr; } + bool IsBackingShared() const noexcept { +#ifdef __ANDROID__ + if (ahb_bytes != 0) { + return true; + } +#endif + return fd >= 0; + } + const size_t backing_size; ///< Size of the backing memory in bytes const size_t virtual_size; ///< Size of the virtual address placeholder in bytes + const size_t preferred_offset; u8* backing_base{reinterpret_cast(MAP_FAILED)}; u8* virtual_base{reinterpret_cast(MAP_FAILED)}; @@ -675,6 +1012,18 @@ private: int ret = close(fd); ASSERT_MSG(ret == 0, "close failed: {}", strerror(errno)); } + +#ifdef __ANDROID__ + for (AHardwareBuffer* buffer : ahb_windows) { + AHardwareBuffer_release(buffer); + } + ahb_windows.clear(); + ahb_fds.clear(); + if (ahb_bytes != 0) { + committed_backing_size.store(0, std::memory_order_relaxed); + ahb_bytes = 0; + } +#endif } void AdjustMap(size_t* virtual_offset, size_t* length) { @@ -700,11 +1049,19 @@ private: int fd{-1}; // memfd file descriptor, -1 is the error value of memfd_create FreeRegionManager free_manager{}; + +#ifdef __ANDROID__ + std::vector ahb_windows; + std::vector ahb_fds; + size_t ahb_window_size{}; + size_t ahb_base{}; + size_t ahb_bytes{}; +#endif }; #endif // ^^^ POSIX ^^^ -HostMemory::HostMemory(size_t backing_size_, size_t virtual_size_) +HostMemory::HostMemory(size_t backing_size_, size_t virtual_size_, size_t preferred_offset_) : backing_size(backing_size_) , virtual_size(virtual_size_) { @@ -714,7 +1071,7 @@ HostMemory::HostMemory(size_t backing_size_, size_t virtual_size_) virtual_base = nullptr; #else // Try to allocate a fastmem arena. - impl = std::make_unique(AlignUp(backing_size, PageAlignment), AlignUp(virtual_size, PageAlignment) + HugePageSize); + impl = std::make_unique(AlignUp(backing_size, PageAlignment), AlignUp(virtual_size, PageAlignment) + HugePageSize, preferred_offset_); if (impl->Init()) { backing_base = impl->backing_base; virtual_base = impl->virtual_base; @@ -794,6 +1151,46 @@ void HostMemory::ClearBackingRegion(size_t physical_offset, size_t length, u32 f std::memset(backing_base + physical_offset, fill_value, length); } +std::span HostMemory::BackingHardwareBuffers() const noexcept { +#ifdef __ANDROID__ + return impl ? impl->AhbWindows() : std::span{}; +#else + return {}; +#endif +} + +size_t HostMemory::BackingMapCount(size_t host_offset, size_t length) const noexcept { +#ifdef __ANDROID__ + return impl ? impl->BackingMapCount(host_offset, length) : (length != 0 ? 1 : 0); +#else + return length != 0 ? 1 : 0; +#endif +} + +size_t HostMemory::BackingHardwareBufferWindowSize() const noexcept { +#ifdef __ANDROID__ + return impl ? impl->AhbWindowSize() : 0; +#else + return 0; +#endif +} + +bool HostMemory::IsBackingShared() const noexcept { +#if defined(__OPENORBIS__) || defined(__managarm__) + return false; +#else + return impl && impl->IsBackingShared(); +#endif +} + +size_t HostMemory::BackingHardwareBufferBase() const noexcept { +#ifdef __ANDROID__ + return impl ? impl->AhbBase() : 0; +#else + return 0; +#endif +} + void HostMemory::EnableDirectMappedAddress() { #if !(defined(__OPENORBIS__) || defined(__managarm__)) if (impl) { diff --git a/src/common/host_memory.h b/src/common/host_memory.h index a7fd0532b7..547901bbe9 100644 --- a/src/common/host_memory.h +++ b/src/common/host_memory.h @@ -8,11 +8,16 @@ #include #include +#include #include "common/common_funcs.h" #include "common/common_types.h" +struct AHardwareBuffer; + namespace Common { +[[nodiscard]] u64 GetCommittedBackingSize() noexcept; + enum class MemoryPermission : u32 { Read = 1 << 0, Write = 1 << 1, @@ -27,7 +32,7 @@ DECLARE_ENUM_FLAG_OPERATORS(MemoryPermission) */ class HostMemory { public: - explicit HostMemory(size_t backing_size_, size_t virtual_size_); + explicit HostMemory(size_t backing_size_, size_t virtual_size_, size_t preferred_offset_ = 0); ~HostMemory(); /** @@ -61,6 +66,20 @@ public: return backing_base; } + [[nodiscard]] size_t BackingSize() const noexcept { + return backing_size; + } + + [[nodiscard]] size_t BackingMapCount(size_t host_offset, size_t length) const noexcept; + + [[nodiscard]] std::span BackingHardwareBuffers() const noexcept; + + [[nodiscard]] size_t BackingHardwareBufferWindowSize() const noexcept; + + [[nodiscard]] size_t BackingHardwareBufferBase() const noexcept; + + [[nodiscard]] bool IsBackingShared() const noexcept; + [[nodiscard]] u8* VirtualBasePointer() noexcept { return virtual_base; } diff --git a/src/common/memory_detect.cpp b/src/common/memory_detect.cpp index 86a3abcc6d..d0f9518bf5 100644 --- a/src/common/memory_detect.cpp +++ b/src/common/memory_detect.cpp @@ -17,6 +17,10 @@ #endif #endif +#include +#include +#include + #include "common/memory_detect.h" namespace Common { @@ -69,4 +73,55 @@ const MemoryInfo& GetMemInfo() { return mem_info; } +u64 GetAvailablePhysicalMemory() { +#ifdef _WIN32 + MEMORYSTATUSEX memorystatus; + memorystatus.dwLength = sizeof(memorystatus); + if (GlobalMemoryStatusEx(&memorystatus)) { + return memorystatus.ullAvailPhys; + } + return 0; +#elif defined(__linux__) + if (std::FILE* const file = std::fopen("/proc/meminfo", "re")) { + char line[256]; + u64 available = 0; + while (std::fgets(line, sizeof(line), file) != nullptr) { + if (std::strncmp(line, "MemAvailable:", 13) == 0) { + available = std::strtoull(line + 13, nullptr, 10) * 1024ULL; + break; + } + } + std::fclose(file); + if (available != 0) { + return available; + } + } + struct sysinfo info; + if (sysinfo(&info) == 0) { + const u64 unit = info.mem_unit != 0 ? info.mem_unit : 1ULL; + return (static_cast(info.freeram) + static_cast(info.bufferram)) * unit; + } + return 0; +#else + return 0; +#endif +} + +u64 GetMaxMapCount() { +#ifdef __linux__ + if (std::FILE* const file = std::fopen("/proc/sys/vm/max_map_count", "re")) { + char line[32]; + u64 count = 0; + if (std::fgets(line, sizeof(line), file) != nullptr) { + count = std::strtoull(line, nullptr, 10); + } + std::fclose(file); + return count; + } + return 0; +#else + return 0; +#endif +} + } // namespace Common diff --git a/src/common/memory_detect.h b/src/common/memory_detect.h index c8f239aed3..3bf013b79a 100644 --- a/src/common/memory_detect.h +++ b/src/common/memory_detect.h @@ -18,4 +18,8 @@ struct MemoryInfo { */ [[nodiscard]] const MemoryInfo& GetMemInfo(); +[[nodiscard]] u64 GetAvailablePhysicalMemory(); + +[[nodiscard]] u64 GetMaxMapCount(); + } // namespace Common diff --git a/src/common/settings.h b/src/common/settings.h index c1c2d4f0df..9638074501 100644 --- a/src/common/settings.h +++ b/src/common/settings.h @@ -666,6 +666,9 @@ struct Values { SwitchableSetting use_asynchronous_shaders{linkage, false, "use_asynchronous_shaders", Category::RendererHacks}; + SwitchableSetting use_unified_memory{linkage, false, "use_unified_memory", + Category::RendererHacks}; + SwitchableSetting gpu_unswizzle_texture_size{linkage, GpuUnswizzleSize::Large, "gpu_unswizzle_texture_size", diff --git a/src/core/core.cpp b/src/core/core.cpp index 046ee53346..6e56471a84 100644 --- a/src/core/core.cpp +++ b/src/core/core.cpp @@ -120,6 +120,7 @@ struct System::Impl { is_multicore = Settings::values.use_multi_core.GetValue(); extended_memory_layout = Settings::values.memory_layout_mode.GetValue() != Settings::MemoryLayout::Memory_4Gb; + unified_memory = Settings::values.use_unified_memory.GetValue(); core_timing.SetMulticore(is_multicore); core_timing.Initialize([&system]() { system.RegisterHostThread(); }); @@ -147,7 +148,8 @@ struct System::Impl { !device_memory.has_value() || is_multicore != Settings::values.use_multi_core.GetValue() || extended_memory_layout != (Settings::values.memory_layout_mode.GetValue() != - Settings::MemoryLayout::Memory_4Gb); + Settings::MemoryLayout::Memory_4Gb) || + unified_memory != Settings::values.use_unified_memory.GetValue(); if (!must_reinitialize) { return; @@ -158,6 +160,7 @@ struct System::Impl { is_multicore = Settings::values.use_multi_core.GetValue(); extended_memory_layout = Settings::values.memory_layout_mode.GetValue() != Settings::MemoryLayout::Memory_4Gb; + unified_memory = Settings::values.use_unified_memory.GetValue(); Initialize(system); } @@ -535,6 +538,7 @@ struct System::Impl { std::atomic_bool is_powered_on{}; bool is_multicore : 1 = false; bool extended_memory_layout : 1 = false; + bool unified_memory : 1 = false; bool exit_locked : 1 = false; bool exit_requested : 1 = false; diff --git a/src/core/device_memory.cpp b/src/core/device_memory.cpp index 1aea56a991..e36ed42e31 100644 --- a/src/core/device_memory.cpp +++ b/src/core/device_memory.cpp @@ -12,9 +12,18 @@ constexpr size_t VirtualReserveSize = 1ULL << 38; constexpr size_t VirtualReserveSize = 1ULL << 39; #endif +namespace { +size_t ApplicationPoolOffset() { + using Init = Kernel::Board::Nintendo::Nx::KSystemControl::Init; + const size_t dram_size = Init::GetIntendedMemorySize(); + const size_t application_pool_size = Init::GetApplicationPoolSize(); + return dram_size > application_pool_size ? dram_size - application_pool_size : 0; +} +} + DeviceMemory::DeviceMemory() : buffer{Kernel::Board::Nintendo::Nx::KSystemControl::Init::GetIntendedMemorySize(), - VirtualReserveSize} {} + VirtualReserveSize, ApplicationPoolOffset()} {} DeviceMemory::~DeviceMemory() = default; diff --git a/src/core/device_memory_manager.h b/src/core/device_memory_manager.h index b4b3b46088..9fa098c98c 100644 --- a/src/core/device_memory_manager.h +++ b/src/core/device_memory_manager.h @@ -20,6 +20,8 @@ #include "common/scratch_buffer.h" #include "common/sparse_large_vector.h" +struct AHardwareBuffer; + namespace Core { constexpr size_t DEVICE_PAGEBITS = 12ULL; @@ -95,6 +97,34 @@ public: ApplyOpOnPAddr(address, buffer, operation); } + u8* GetPhysicalBase() noexcept { + return reinterpret_cast(physical_base); + } + + const u8* GetPhysicalBase() const noexcept { + return reinterpret_cast(physical_base); + } + + size_t GetPhysicalSize() const noexcept { + return physical_size; + } + + std::span GetBackingHardwareBuffers() const noexcept { + return ahb_windows; + } + + size_t GetBackingHardwareBufferWindowSize() const noexcept { + return ahb_window_size; + } + + size_t GetBackingHardwareBufferBase() const noexcept { + return ahb_base; + } + + bool IsBackingShared() const noexcept { + return backing_is_shared; + } + PAddr GetPhysicalRawAddressFromDAddr(DAddr address) const { PAddr subbits = PAddr(address & page_mask); auto paddr = tracked_entries[(address >> page_bits)].compressed_physical_ptr; @@ -171,6 +201,11 @@ private: std::unique_ptr> impl; const uintptr_t physical_base; + const size_t physical_size; + const std::span ahb_windows; + const size_t ahb_window_size; + const size_t ahb_base; + const bool backing_is_shared; DeviceInterface* device_inter; struct TrackedEntry { diff --git a/src/core/device_memory_manager.inc b/src/core/device_memory_manager.inc index 97c2706abb..cd7d9f9411 100644 --- a/src/core/device_memory_manager.inc +++ b/src/core/device_memory_manager.inc @@ -171,6 +171,11 @@ struct DeviceMemoryManagerAllocator { template DeviceMemoryManager::DeviceMemoryManager(const DeviceMemory& device_memory_) : physical_base{uintptr_t(device_memory_.buffer.BackingBasePointer())} + , physical_size{device_memory_.buffer.BackingSize()} + , ahb_windows{device_memory_.buffer.BackingHardwareBuffers()} + , ahb_window_size{device_memory_.buffer.BackingHardwareBufferWindowSize()} + , ahb_base{device_memory_.buffer.BackingHardwareBufferBase()} + , backing_is_shared{device_memory_.buffer.IsBackingShared()} , device_inter{nullptr} , compressed_device_addr(1ULL << ((Settings::values.memory_layout_mode.GetValue() == Settings::MemoryLayout::Memory_4Gb ? physical_min_bits : physical_max_bits) - Memory::YUZU_PAGEBITS)) , tracked_entries(device_as_size >> Memory::YUZU_PAGEBITS) diff --git a/src/qt_common/config/shared_translation.cpp b/src/qt_common/config/shared_translation.cpp index be2f986eaf..f4dbea1f7f 100644 --- a/src/qt_common/config/shared_translation.cpp +++ b/src/qt_common/config/shared_translation.cpp @@ -228,6 +228,8 @@ std::unique_ptr InitializeTranslations(QObject* parent) { tr("Preserves GPU-modified data by reading it back before uploading.\nSome games require this to render certain effects properly.")); INSERT(Settings, use_asynchronous_shaders, tr("Enable asynchronous shader compilation"), tr("May reduce shader stutter.")); + INSERT(Settings, use_unified_memory, tr("Enable unified memory access"), + tr("Lets the GPU write buffer readbacks directly into guest memory.")); INSERT(Settings, gpu_clock, tr("GPU Clocks"), tr("Makes the game believe GPU work finishes faster than it does, so it stops lowering " "resolution and render distance to fit the Switch's clocks.")); diff --git a/src/video_core/buffer_cache/buffer_cache.h b/src/video_core/buffer_cache/buffer_cache.h index 4c345dd213..31a229f2cc 100644 --- a/src/video_core/buffer_cache/buffer_cache.h +++ b/src/video_core/buffer_cache/buffer_cache.h @@ -578,7 +578,11 @@ void BufferCache

::AccumulateFlushes() { template bool BufferCache

::ShouldWaitAsyncFlushes() const noexcept { - return (!async_buffers.empty() && async_buffers.front().has_value()); + if (async_buffers.empty()) { + return false; + } + return async_buffers.front().has_value() || + !pending_downloads.front().unified_copies.empty(); } template @@ -586,6 +590,7 @@ void BufferCache

::CommitAsyncFlushesHigh() { AccumulateFlushes(); if (committed_gpu_modified_ranges.empty()) { + pending_downloads.emplace_back(); async_buffers.emplace_back(std::optional{}); return; } @@ -645,27 +650,83 @@ void BufferCache

::CommitAsyncFlushesHigh() { } committed_gpu_modified_ranges.clear(); if (downloads.empty()) { + pending_downloads.emplace_back(); async_buffers.emplace_back(std::optional{}); return; } - auto download_staging = runtime.DownloadStagingBuffer(total_size_bytes, true); - boost::container::small_vector normalized_copies; - runtime.PreCopyBarrier(); + + struct QueuedUnifiedCopy { + u64 window; + BufferId buffer_id; + boost::container::small_vector copies; + }; + + AsyncDownloadBatch batch; + boost::container::small_vector, 16> staging_downloads; + boost::container::small_vector unified_copy_queue; + boost::container::small_vector window_ids; + UnifiedWindowGroups groups; + u64 staging_size_bytes = 0; for (auto& [copy, buffer_id] : downloads) { - copy.dst_offset += download_staging.offset; - const std::array copies{copy}; - BufferCopy second_copy{copy}; Buffer& buffer = slot_buffers[buffer_id]; - second_copy.src_offset = static_cast(buffer.CpuAddr()) + copy.src_offset; - const DAddr orig_device_addr = static_cast(second_copy.src_offset); + const DAddr orig_device_addr = buffer.CpuAddr() + copy.src_offset; + bool unified = false; + if constexpr (USE_UNIFIED_MEMORY) { + if (runtime.HasUnifiedMemory()) { + window_ids.clear(); + groups.clear(); + unified = ResolveUnifiedWindows(orig_device_addr, copy.src_offset, copy.size, + window_ids, groups); + } + } + BufferCopy record{copy}; + record.src_offset = static_cast(orig_device_addr); + if (unified) { + async_downloads.Add(orig_device_addr, copy.size); + buffer.MarkUsage(copy.src_offset, copy.size); + for (size_t i = 0; i < window_ids.size(); ++i) { + unified_copy_queue.push_back( + QueuedUnifiedCopy{window_ids[i], buffer_id, std::move(groups[i])}); + } + batch.unified_copies.push_back(record); + continue; + } + copy.dst_offset = staging_size_bytes; + constexpr u64 align = 64ULL; + staging_size_bytes += (copy.size + align - 1) & ~(align - 1ULL); + staging_downloads.push_back({copy, buffer_id}); + } + + std::optional download_staging; + if (!staging_downloads.empty()) { + download_staging = runtime.DownloadStagingBuffer(staging_size_bytes, true); + } + runtime.PreCopyBarrier(); + for (auto& [copy, buffer_id] : staging_downloads) { + copy.dst_offset += download_staging->offset; + const std::array copies{copy}; + Buffer& buffer = slot_buffers[buffer_id]; + BufferCopy record{copy}; + record.src_offset = static_cast(buffer.CpuAddr()) + copy.src_offset; + const DAddr orig_device_addr = static_cast(record.src_offset); async_downloads.Add(orig_device_addr, copy.size); buffer.MarkUsage(copy.src_offset, copy.size); - runtime.CopyBuffer(download_staging.buffer, buffer, copies, false); - normalized_copies.push_back(second_copy); + runtime.CopyBuffer(download_staging->buffer, buffer, copies, false); + batch.staging_copies.push_back(record); + } + if constexpr (USE_UNIFIED_MEMORY) { + for (const auto& queued : unified_copy_queue) { + const std::span group_span(queued.copies.data(), + queued.copies.size()); + runtime.CopyToUnifiedMemory(queued.window, slot_buffers[queued.buffer_id], group_span); + } + if (!unified_copy_queue.empty()) { + runtime.UnifiedMemoryHostBarrier(); + } } runtime.PostCopyBarrier(); - pending_downloads.emplace_back(std::move(normalized_copies)); - async_buffers.emplace_back(download_staging); + pending_downloads.emplace_back(std::move(batch)); + async_buffers.emplace_back(std::move(download_staging)); } template @@ -680,32 +741,49 @@ void BufferCache

::PopAsyncFlushes() { template void BufferCache

::PopAsyncBuffers() { + struct Writeback { + DAddr addr; + const u8* src; + u64 size; + }; + boost::container::small_vector writebacks; + { + std::scoped_lock lock{mutex}; if (async_buffers.empty()) { return; } - if (!async_buffers.front().has_value()) { - async_buffers.pop_front(); - return; - } - auto& downloads = pending_downloads.front(); + auto& batch = pending_downloads.front(); auto& async_buffer = async_buffers.front(); - u8* base = async_buffer->mapped_span.data(); + if (async_buffer.has_value()) { + const u8* base = async_buffer->mapped_span.data(); const size_t base_offset = async_buffer->offset; - for (const auto& copy : downloads) { + for (const auto& copy : batch.staging_copies) { const DAddr device_addr = static_cast(copy.src_offset); const u64 dst_offset = copy.dst_offset - base_offset; const u8* read_mapped_memory = base + dst_offset; - async_downloads.ForEachInRange(device_addr, copy.size, [&](DAddr start, DAddr end, s32) { - device_memory.WriteBlockUnsafe(start, &read_mapped_memory[start - device_addr], - end - start); + async_downloads.ForEachInRange( + device_addr, copy.size, [&](DAddr start, DAddr end, s32) { + writebacks.push_back( + {start, &read_mapped_memory[start - device_addr], end - start}); }); async_downloads.Subtract(device_addr, copy.size, [&](DAddr start, DAddr end) { gpu_modified_ranges.Subtract(start, end - start); }); } async_buffers_death_ring.emplace_back(*async_buffer); + } + for (const auto& copy : batch.unified_copies) { + const DAddr device_addr = static_cast(copy.src_offset); + async_downloads.Subtract(device_addr, copy.size, [&](DAddr start, DAddr end) { + gpu_modified_ranges.Subtract(start, end - start); + }); + } async_buffers.pop_front(); pending_downloads.pop_front(); + } + for (const auto& wb : writebacks) { + device_memory.WriteBlockUnsafe(wb.addr, wb.src, wb.size); + } } template @@ -1799,6 +1877,98 @@ void BufferCache

::ImmediateUploadMemory([[maybe_unused]] Buffer& buffer, } } +template +bool BufferCache

::ResolveUnifiedWindows( + [[maybe_unused]] DAddr device_addr, [[maybe_unused]] u64 buffer_offset, + [[maybe_unused]] u64 size, [[maybe_unused]] boost::container::small_vector& window_ids, + [[maybe_unused]] UnifiedWindowGroups& groups) { + if constexpr (USE_UNIFIED_MEMORY) { + const u8* const physical_base = device_memory.GetPhysicalBase(); + const u64 unified_base = runtime.UnifiedMemoryBase(); + const u64 unified_size = runtime.UnifiedMemorySize(); + const u64 window_size = runtime.UnifiedMemoryWindowSize(); + if (window_size == 0) { + return false; + } + const auto group_for = [&](u64 window) -> boost::container::small_vector& { + for (size_t i = 0; i < window_ids.size(); ++i) { + if (window_ids[i] == window) { + return groups[i]; + } + } + window_ids.push_back(window); + groups.emplace_back(); + return groups.back(); + }; + u64 downloaded = 0; + while (downloaded < size) { + const DAddr page_addr = device_addr + downloaded; + const u8* const ptr = device_memory.GetPointer(page_addr); + if (ptr == nullptr) { + return false; + } + const u64 page_offset = page_addr & Core::DEVICE_PAGEMASK; + u64 chunk = (std::min)(size - downloaded, + static_cast(Core::DEVICE_PAGESIZE) - page_offset); + const u64 phys_offset = static_cast(ptr - physical_base); + if (phys_offset < unified_base || phys_offset - unified_base + chunk > unified_size) { + return false; + } + const u64 relative = phys_offset - unified_base; + const u64 window = relative / window_size; + const u64 local_offset = relative % window_size; + chunk = (std::min)(chunk, window_size - local_offset); + auto& group = group_for(window); + if (!group.empty()) { + BufferCopy& last = group.back(); + if (last.src_offset + last.size == buffer_offset + downloaded && + last.dst_offset + last.size == local_offset) { + last.size += chunk; + downloaded += chunk; + continue; + } + } + group.push_back(BufferCopy{ + .src_offset = buffer_offset + downloaded, + .dst_offset = local_offset, + .size = chunk, + }); + downloaded += chunk; + } + return true; + } else { + return false; + } +} + +template +bool BufferCache

::TryUnifiedDownloadMemory([[maybe_unused]] Buffer& buffer, + [[maybe_unused]] std::span copies) { + if constexpr (USE_UNIFIED_MEMORY) { + boost::container::small_vector window_ids; + UnifiedWindowGroups groups; + for (const BufferCopy& copy : copies) { + if (!ResolveUnifiedWindows(buffer.CpuAddr() + copy.src_offset, copy.src_offset, + copy.size, window_ids, groups)) { + return false; + } + } + for (const BufferCopy& copy : copies) { + buffer.MarkUsage(copy.src_offset, copy.size); + } + runtime.PreCopyBarrier(); + for (size_t i = 0; i < window_ids.size(); ++i) { + const std::span group_span(groups[i].data(), groups[i].size()); + runtime.CopyToUnifiedMemory(window_ids[i], buffer, group_span); + } + runtime.UnifiedMemoryHostBarrier(); + runtime.Finish(); + return true; + } else { + return false; + } +} + template void BufferCache

::MappedUploadMemory([[maybe_unused]] Buffer& buffer, [[maybe_unused]] u64 total_size_bytes, @@ -1902,6 +2072,12 @@ void BufferCache

::DownloadBufferMemory(Buffer& buffer, DAddr device_addr, u64 } if constexpr (USE_MEMORY_MAPS) { + if constexpr (USE_UNIFIED_MEMORY) { + if (runtime.HasUnifiedMemory() && + TryUnifiedDownloadMemory(buffer, std::span(copies.data(), copies.size()))) { + return; + } + } auto download_staging = runtime.DownloadStagingBuffer(total_size_bytes); const u8* const mapped_memory = download_staging.mapped_span.data(); const std::span copies_span(copies.data(), copies.data() + copies.size()); diff --git a/src/video_core/buffer_cache/buffer_cache_base.h b/src/video_core/buffer_cache/buffer_cache_base.h index 0dbb368c47..b7ed422d19 100644 --- a/src/video_core/buffer_cache/buffer_cache_base.h +++ b/src/video_core/buffer_cache/buffer_cache_base.h @@ -190,6 +190,7 @@ class BufferCache : public VideoCommon::ChannelSetupCaches copies); + bool TryUnifiedDownloadMemory(Buffer& buffer, std::span copies); + + using UnifiedWindowGroups = + boost::container::small_vector, 4>; + + bool ResolveUnifiedWindows(DAddr device_addr, u64 buffer_offset, u64 size, + boost::container::small_vector& window_ids, + UnifiedWindowGroups& groups); + void DownloadBufferMemory(Buffer& buffer_id); void DownloadBufferMemory(Buffer& buffer_id, DAddr device_addr, u64 size); @@ -517,9 +527,14 @@ private: std::deque> committed_gpu_modified_ranges; // Async Buffers + struct AsyncDownloadBatch { + boost::container::small_vector staging_copies; + boost::container::small_vector unified_copies; + }; + Common::OverlapRangeSet async_downloads; std::deque> async_buffers; - std::deque> pending_downloads; + std::deque pending_downloads; std::optional current_buffer; std::deque async_buffers_death_ring; diff --git a/src/video_core/renderer_opengl/gl_buffer_cache.h b/src/video_core/renderer_opengl/gl_buffer_cache.h index 6fee58a0eb..4df68bbe35 100644 --- a/src/video_core/renderer_opengl/gl_buffer_cache.h +++ b/src/video_core/renderer_opengl/gl_buffer_cache.h @@ -262,6 +262,7 @@ struct BufferCacheParams { // TODO: Investigate why OpenGL seems to perform worse with persistently mapped buffer uploads static constexpr bool USE_MEMORY_MAPS_FOR_UPLOADS = false; + static constexpr bool USE_UNIFIED_MEMORY = false; }; using BufferCache = VideoCommon::BufferCache; diff --git a/src/video_core/renderer_vulkan/vk_buffer_cache.cpp b/src/video_core/renderer_vulkan/vk_buffer_cache.cpp index 958f3b2a2e..375fca6856 100644 --- a/src/video_core/renderer_vulkan/vk_buffer_cache.cpp +++ b/src/video_core/renderer_vulkan/vk_buffer_cache.cpp @@ -374,6 +374,93 @@ BufferCacheRuntime::BufferCacheRuntime(const Device& device_, MemoryAllocator& m scheduler_, staging_pool_); } +void BufferCacheRuntime::TryEnableUnifiedMemory(void* base, size_t size, + std::span hardware_buffers, + size_t hardware_buffer_window, + size_t hardware_buffer_base) { + unified_memory = std::make_unique( + device, base, size, hardware_buffers, hardware_buffer_window, hardware_buffer_base); + if (!unified_memory->IsValid()) { + unified_memory.reset(); + } +} + +void BufferCacheRuntime::CopyToUnifiedMemory( + size_t window_index, VkBuffer src_buffer, + std::span copies) { + if (!unified_memory || src_buffer == VK_NULL_HANDLE || copies.empty() || + window_index >= unified_memory->GetWindowCount()) { + return; + } + const VkBuffer dst_buffer = unified_memory->GetWindowBuffer(window_index); + if (dst_buffer == VK_NULL_HANDLE) { + return; + } + VkDeviceSize covered_begin = std::numeric_limits::max(); + VkDeviceSize covered_end = 0; + for (const VideoCommon::BufferCopy& copy : copies) { + covered_begin = (std::min)(covered_begin, static_cast(copy.dst_offset)); + covered_end = (std::max)(covered_end, + static_cast(copy.dst_offset + copy.size)); + } + + boost::container::small_vector vk_copies(copies.size()); + std::ranges::transform(copies, vk_copies.begin(), MakeBufferCopy); + + const bool foreign = unified_memory->NeedsForeignOwnershipTransfer(); + const u32 queue_family = device.GetGraphicsFamily(); + + scheduler.RequestOutsideRenderPassOperationContext(); + scheduler.Record([src_buffer, dst_buffer, vk_copies, foreign, queue_family, covered_begin, + covered_end](vk::CommandBuffer cmdbuf) { + if (foreign) { + const VkBufferMemoryBarrier acquire{ + .sType = VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER, + .pNext = nullptr, + .srcAccessMask = 0, + .dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT, + .srcQueueFamilyIndex = VK_QUEUE_FAMILY_FOREIGN_EXT, + .dstQueueFamilyIndex = queue_family, + .buffer = dst_buffer, + .offset = covered_begin, + .size = covered_end - covered_begin, + }; + cmdbuf.PipelineBarrier(VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, + VK_PIPELINE_STAGE_TRANSFER_BIT, 0, acquire); + } + cmdbuf.CopyBuffer(src_buffer, dst_buffer, VideoCommon::FixSmallVectorADL(vk_copies)); + if (foreign) { + const VkBufferMemoryBarrier release{ + .sType = VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER, + .pNext = nullptr, + .srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT, + .dstAccessMask = 0, + .srcQueueFamilyIndex = queue_family, + .dstQueueFamilyIndex = VK_QUEUE_FAMILY_FOREIGN_EXT, + .buffer = dst_buffer, + .offset = covered_begin, + .size = covered_end - covered_begin, + }; + cmdbuf.PipelineBarrier(VK_PIPELINE_STAGE_TRANSFER_BIT, + VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, 0, release); + } + }); +} + +void BufferCacheRuntime::UnifiedMemoryHostBarrier() { + static constexpr VkMemoryBarrier HOST_BARRIER{ + .sType = VK_STRUCTURE_TYPE_MEMORY_BARRIER, + .pNext = nullptr, + .srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT, + .dstAccessMask = VK_ACCESS_HOST_READ_BIT, + }; + scheduler.RequestOutsideRenderPassOperationContext(); + scheduler.Record([](vk::CommandBuffer cmdbuf) { + cmdbuf.PipelineBarrier(VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_HOST_BIT, 0, + HOST_BARRIER); + }); +} + StagingBufferRef BufferCacheRuntime::UploadStagingBuffer(size_t size) { return staging_pool.Request(size, MemoryUsage::Upload); } diff --git a/src/video_core/renderer_vulkan/vk_buffer_cache.h b/src/video_core/renderer_vulkan/vk_buffer_cache.h index fbd8c2e753..583b990060 100644 --- a/src/video_core/renderer_vulkan/vk_buffer_cache.h +++ b/src/video_core/renderer_vulkan/vk_buffer_cache.h @@ -7,6 +7,8 @@ #pragma once #include +#include +#include #include @@ -110,6 +112,31 @@ public: void TickFrame(Common::SlotVector& slot_buffers) noexcept; + void TryEnableUnifiedMemory(void* base, size_t size, + std::span hardware_buffers, + size_t hardware_buffer_window, size_t hardware_buffer_base); + + [[nodiscard]] bool HasUnifiedMemory() const noexcept { + return unified_memory != nullptr && unified_memory->IsValid(); + } + + [[nodiscard]] u64 UnifiedMemorySize() const noexcept { + return unified_memory ? unified_memory->GetSize() : 0; + } + + [[nodiscard]] u64 UnifiedMemoryBase() const noexcept { + return unified_memory ? unified_memory->GetBaseOffset() : 0; + } + + [[nodiscard]] u64 UnifiedMemoryWindowSize() const noexcept { + return unified_memory ? unified_memory->GetWindowSize() : 0; + } + + void CopyToUnifiedMemory(size_t window_index, VkBuffer src_buffer, + std::span copies); + + void UnifiedMemoryHostBarrier(); + u64 CurrentTick(); u64 KnownGpuTick(); @@ -257,6 +284,7 @@ private: std::shared_ptr quad_strip_index_buffer; vk::Buffer null_buffer; + std::unique_ptr unified_memory; std::unique_ptr uint8_pass; QuadIndexedPass quad_index_pass; @@ -283,6 +311,7 @@ struct BufferCacheParams { static constexpr bool USE_MEMORY_MAPS = true; static constexpr bool SEPARATE_IMAGE_BUFFER_BINDINGS = false; static constexpr bool USE_MEMORY_MAPS_FOR_UPLOADS = true; + static constexpr bool USE_UNIFIED_MEMORY = true; }; using BufferCache = VideoCommon::BufferCache; diff --git a/src/video_core/renderer_vulkan/vk_rasterizer.cpp b/src/video_core/renderer_vulkan/vk_rasterizer.cpp index f43bea1220..58c32201ec 100644 --- a/src/video_core/renderer_vulkan/vk_rasterizer.cpp +++ b/src/video_core/renderer_vulkan/vk_rasterizer.cpp @@ -225,6 +225,13 @@ RasterizerVulkan::RasterizerVulkan(Core::Frontend::EmuWindow& emu_window_, Tegra fence_manager(*this, gpu, texture_cache, buffer_cache, query_cache, device, scheduler), wfi_event(device.GetLogical().CreateEvent()) { scheduler.SetQueryCache(query_cache); + if (Settings::values.use_unified_memory.GetValue() && device_memory.IsBackingShared()) { + buffer_cache_runtime.TryEnableUnifiedMemory( + device_memory.GetPhysicalBase(), device_memory.GetPhysicalSize(), + device_memory.GetBackingHardwareBuffers(), + device_memory.GetBackingHardwareBufferWindowSize(), + device_memory.GetBackingHardwareBufferBase()); + } } RasterizerVulkan::~RasterizerVulkan() { diff --git a/src/video_core/vulkan_common/vulkan_device.cpp b/src/video_core/vulkan_common/vulkan_device.cpp index be09bca8d3..83b76b9776 100644 --- a/src/video_core/vulkan_common/vulkan_device.cpp +++ b/src/video_core/vulkan_common/vulkan_device.cpp @@ -21,6 +21,7 @@ #include "common/assert.h" #include "common/fs/fs.h" #include "common/fs/path_util.h" +#include "common/host_memory.h" #include "common/literals.h" #include #include "common/settings.h" @@ -1045,6 +1046,7 @@ bool Device::GetSuitability(bool requires_swapchain) { FOR_EACH_VK_FEATURE_EXT(FEATURE_EXTENSION); FOR_EACH_VK_EXTENSION(EXTENSION); + FOR_EACH_VK_PLATFORM_EXTENSION(EXTENSION); extensions.depth_stencil_resolve = extensions.depth_stencil_resolve && @@ -1063,6 +1065,17 @@ bool Device::GetSuitability(bool requires_swapchain) { extensions.robustness_2 = false; } +#ifdef __ANDROID__ + if (extensions.external_memory_ahb && !extensions.queue_family_foreign) { + LOG_INFO(Render_Vulkan, + "Not loading {} because its dependency {} is unavailable", + VK_ANDROID_EXTERNAL_MEMORY_ANDROID_HARDWARE_BUFFER_EXTENSION_NAME, + VK_EXT_QUEUE_FAMILY_FOREIGN_EXTENSION_NAME); + loaded_extensions.erase(VK_ANDROID_EXTERNAL_MEMORY_ANDROID_HARDWARE_BUFFER_EXTENSION_NAME); + extensions.external_memory_ahb = false; + } +#endif + #undef FEATURE_EXTENSION #undef EXTENSION @@ -1229,6 +1242,21 @@ bool Device::GetSuitability(bool requires_swapchain) { VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_CUSTOM_BORDER_COLOR_PROPERTIES_EXT; SetNext(next, properties.custom_border_color); } + if (extensions.external_memory_host) { + properties.external_memory_host.sType = + VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTERNAL_MEMORY_HOST_PROPERTIES_EXT; + SetNext(next, properties.external_memory_host); + } + if (extensions.maintenance3 || instance_version >= VK_API_VERSION_1_1) { + properties.maintenance3.sType = + VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MAINTENANCE_3_PROPERTIES; + SetNext(next, properties.maintenance3); + } + if (extensions.maintenance4 || features.maintenance4.maintenance4) { + properties.maintenance4.sType = + VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MAINTENANCE_4_PROPERTIES; + SetNext(next, properties.maintenance4); + } // Perform the property fetch. physical.GetProperties2(properties2); @@ -1623,12 +1651,27 @@ void Device::CollectPhysicalMemoryInfo() { device_access_memory = 0; u64 device_initial_usage = 0; u64 local_memory = 0; + const auto heap_has_usable_type = [&mem_properties](size_t heap) { + for (u32 index = 0; index < mem_properties.memoryTypeCount; ++index) { + if (mem_properties.memoryTypes[index].heapIndex != heap) { + continue; + } + if ((mem_properties.memoryTypes[index].propertyFlags & + VK_MEMORY_PROPERTY_PROTECTED_BIT) == 0) { + return true; + } + } + return false; + }; for (size_t element = 0; element < num_properties; ++element) { const bool is_heap_local = (mem_properties.memoryHeaps[element].flags & VK_MEMORY_HEAP_DEVICE_LOCAL_BIT) != 0; if (!is_integrated && !is_heap_local) { continue; } + if (!heap_has_usable_type(element)) { + continue; + } valid_heap_memory.push_back(element); if (is_heap_local) { local_memory += mem_properties.memoryHeaps[element].size; @@ -1640,6 +1683,13 @@ void Device::CollectPhysicalMemoryInfo() { } device_access_memory += mem_properties.memoryHeaps[element].size; } + const u64 committed_backing = Common::GetCommittedBackingSize(); + if (committed_backing != 0) { + LOG_INFO(Render_Vulkan, "Discounting {} MiB of guest memory committed by the host", + committed_backing >> 20); + local_memory -= std::min(local_memory, committed_backing); + device_access_memory -= std::min(device_access_memory, committed_backing); + } if (is_integrated) { const s64 available_memory = static_cast(device_access_memory - device_initial_usage); const u64 memory_size = Settings::values.vram_usage_mode.GetValue() == Settings::VramUsageMode::Aggressive ? 6_GiB : 4_GiB; diff --git a/src/video_core/vulkan_common/vulkan_device.h b/src/video_core/vulkan_common/vulkan_device.h index 077b1c3e23..cdd683f016 100644 --- a/src/video_core/vulkan_common/vulkan_device.h +++ b/src/video_core/vulkan_common/vulkan_device.h @@ -86,6 +86,7 @@ VK_DEFINE_HANDLE(VmaAllocator) EXTENSION(EXT, CONDITIONAL_RENDERING, conditional_rendering) \ EXTENSION(EXT, CONSERVATIVE_RASTERIZATION, conservative_rasterization) \ EXTENSION(EXT, DEPTH_RANGE_UNRESTRICTED, depth_range_unrestricted) \ + EXTENSION(EXT, EXTERNAL_MEMORY_HOST, external_memory_host) \ EXTENSION(EXT, MEMORY_BUDGET, memory_budget) \ EXTENSION(EXT, ROBUSTNESS_2, robustness_2) \ EXTENSION(EXT, SAMPLER_FILTER_MINMAX, sampler_filter_minmax) \ @@ -117,6 +118,14 @@ VK_DEFINE_HANDLE(VmaAllocator) EXTENSION(IMG, FILTER_CUBIC, filter_cubic_img) \ EXTENSION(QCOM, FILTER_CUBIC_WEIGHTS, filter_cubic_weights) +#ifdef __ANDROID__ +#define FOR_EACH_VK_PLATFORM_EXTENSION(EXTENSION) \ + EXTENSION(EXT, QUEUE_FAMILY_FOREIGN, queue_family_foreign) \ + EXTENSION(ANDROID, EXTERNAL_MEMORY_ANDROID_HARDWARE_BUFFER, external_memory_ahb) +#else +#define FOR_EACH_VK_PLATFORM_EXTENSION(EXTENSION) +#endif + // Define extensions which must be supported. #define FOR_EACH_VK_MANDATORY_EXTENSION(EXTENSION_NAME) \ EXTENSION_NAME(VK_EXT_VERTEX_ATTRIBUTE_DIVISOR_EXTENSION_NAME) \ @@ -891,6 +900,30 @@ FN_MAX_LIMIT_LIST return extensions.conditional_rendering; } + bool IsExtExternalMemoryHostSupported() const { + return extensions.external_memory_host; + } + + bool IsExtExternalMemoryAhbSupported() const { +#ifdef __ANDROID__ + return extensions.external_memory_ahb && extensions.queue_family_foreign; +#else + return false; +#endif + } + + u64 GetMinImportedHostPointerAlignment() const { + return properties.external_memory_host.minImportedHostPointerAlignment; + } + + u64 GetMaxBufferSize() const { + return properties.maintenance4.maxBufferSize; + } + + u64 GetMaxMemoryAllocationSize() const { + return properties.maintenance3.maxMemoryAllocationSize; + } + bool IsExtAstcDecodeModeSupported() const { return extensions.astc_decode_mode; } @@ -1163,6 +1196,7 @@ private: FOR_EACH_VK_FEATURE_1_4(FEATURE); FOR_EACH_VK_FEATURE_EXT(FEATURE); FOR_EACH_VK_EXTENSION(EXTENSION); + FOR_EACH_VK_PLATFORM_EXTENSION(EXTENSION); #undef EXTENSION #undef FEATURE @@ -1194,9 +1228,12 @@ private: VkPhysicalDeviceDescriptorBufferPropertiesEXT descriptor_buffer{}; VkPhysicalDeviceSubgroupSizeControlProperties subgroup_size_control{}; VkPhysicalDeviceTransformFeedbackPropertiesEXT transform_feedback{}; + VkPhysicalDeviceMaintenance3Properties maintenance3{}; + VkPhysicalDeviceMaintenance4Properties maintenance4{}; VkPhysicalDeviceMaintenance5PropertiesKHR maintenance5{}; VkPhysicalDeviceDepthStencilResolveProperties depth_stencil_resolve{}; VkPhysicalDeviceCustomBorderColorPropertiesEXT custom_border_color{}; + VkPhysicalDeviceExternalMemoryHostPropertiesEXT external_memory_host{}; VkPhysicalDeviceProperties properties{}; }; diff --git a/src/video_core/vulkan_common/vulkan_memory_allocator.cpp b/src/video_core/vulkan_common/vulkan_memory_allocator.cpp index f4721543ae..3e7dea4a49 100644 --- a/src/video_core/vulkan_common/vulkan_memory_allocator.cpp +++ b/src/video_core/vulkan_common/vulkan_memory_allocator.cpp @@ -25,9 +25,34 @@ #include "video_core/gpu_logging/gpu_logging.h" #include "common/settings.h" +#ifdef __ANDROID__ +#include +#endif + namespace Vulkan { namespace { + [[nodiscard]] std::optional FindImportMemoryType( + const VkPhysicalDeviceMemoryProperties &props, u32 type_mask) { + const auto find = [&](VkMemoryPropertyFlags wanted) -> std::optional { + for (u32 i = 0; i < props.memoryTypeCount; ++i) { + if (((type_mask >> i) & 1u) != 0 && + (props.memoryTypes[i].propertyFlags & wanted) == wanted) { + return i; + } + } + return std::nullopt; + }; + auto type_index = find(VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | + VK_MEMORY_PROPERTY_HOST_COHERENT_BIT | + VK_MEMORY_PROPERTY_HOST_CACHED_BIT); + if (!type_index) { + type_index = find(VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | + VK_MEMORY_PROPERTY_HOST_COHERENT_BIT); + } + return type_index; + } + // Helpers translating MemoryUsage to flags/usage [[maybe_unused]] VkMemoryPropertyFlags MemoryUsagePropertyFlags(MemoryUsage usage) { @@ -181,6 +206,291 @@ void MemoryCommit::Release() { size = 0; } +HostMemoryImport::HostMemoryImport(const Device &device_, void *base, size_t size, + std::span hardware_buffers, + size_t hardware_buffer_window, size_t hardware_buffer_base) + : device{device_} { + if (ImportHardwareBuffers(hardware_buffers, hardware_buffer_window, hardware_buffer_base, + size)) { + return; + } + if (device.IsTiler()) { + LOG_INFO(Render_Vulkan, + "Unified memory disabled, hardware buffer import is the only path supported " + "by tiler drivers"); + return; + } + if (ImportHostPointer(base, size)) { + return; + } + LOG_INFO(Render_Vulkan, "Unified memory disabled, no host memory import path"); +} + +bool HostMemoryImport::ImportHostPointer(void *base, size_t size) { + if (!device.IsExtExternalMemoryHostSupported()) { + LOG_INFO(Render_Vulkan, + "Unified memory disabled, VK_EXT_external_memory_host is not supported"); + return false; + } + const u64 alignment = device.GetMinImportedHostPointerAlignment(); + if (alignment == 0 || !Common::IsAligned(reinterpret_cast(base), alignment) || + !Common::IsAligned(size, alignment)) { + LOG_INFO(Render_Vulkan, + "Unified memory disabled, host allocation does not satisfy alignment {}", + alignment); + return false; + } + using namespace Common::Literals; + constexpr VkDeviceSize DesktopWindowSize = 4_GiB; + VkDeviceSize candidate_window = DesktopWindowSize; + const u64 max_buffer_size = device.GetMaxBufferSize(); + if (max_buffer_size != 0 && max_buffer_size < candidate_window) { + candidate_window = max_buffer_size; + } + const u64 max_allocation_size = device.GetMaxMemoryAllocationSize(); + if (max_allocation_size != 0 && max_allocation_size < candidate_window) { + candidate_window = max_allocation_size; + } + candidate_window = Common::AlignDown(candidate_window, alignment); + if (candidate_window == 0) { + return false; + } + window_size = candidate_window; + + const auto &logical = device.GetLogical(); + const auto memory_props = device.GetPhysical().GetMemoryProperties().memoryProperties; + + for (size_t offset = 0; offset < size; offset += window_size) { + u8 *const window_base = static_cast(base) + offset; + const VkDeviceSize window_len = + (std::min)(static_cast(size - offset), window_size); + VkMemoryHostPointerPropertiesEXT host_props{ + .sType = VK_STRUCTURE_TYPE_MEMORY_HOST_POINTER_PROPERTIES_EXT, + .pNext = nullptr, + .memoryTypeBits = 0, + }; + if (logical.GetMemoryHostPointerPropertiesEXT( + VK_EXTERNAL_MEMORY_HANDLE_TYPE_HOST_ALLOCATION_BIT_EXT, window_base, + &host_props) != VK_SUCCESS || + host_props.memoryTypeBits == 0) { + break; + } + const VkExternalMemoryBufferCreateInfo external_info{ + .sType = VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_BUFFER_CREATE_INFO, + .pNext = nullptr, + .handleTypes = VK_EXTERNAL_MEMORY_HANDLE_TYPE_HOST_ALLOCATION_BIT_EXT, + }; + const VkBufferCreateInfo buffer_ci{ + .sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO, + .pNext = &external_info, + .flags = 0, + .size = window_len, + .usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT, + .sharingMode = VK_SHARING_MODE_EXCLUSIVE, + .queueFamilyIndexCount = 0, + .pQueueFamilyIndices = nullptr, + }; + VkBuffer new_buffer{}; + if (logical.CreateBufferRaw(buffer_ci, &new_buffer) != VK_SUCCESS) { + break; + } + const VkMemoryRequirements requirements = + logical.GetBufferMemoryRequirements(new_buffer); + const u32 type_mask = requirements.memoryTypeBits & host_props.memoryTypeBits; + if (type_mask == 0 || requirements.size > window_len) { + logical.DestroyBufferRaw(new_buffer); + break; + } + const auto type_index = FindImportMemoryType(memory_props, type_mask); + if (!type_index) { + logical.DestroyBufferRaw(new_buffer); + break; + } + constexpr VkDeviceSize MaxHeapFractionDenominator = 2; + const u32 heap_index = memory_props.memoryTypes[*type_index].heapIndex; + const VkDeviceSize heap_size = memory_props.memoryHeaps[heap_index].size; + const VkDeviceSize heap_import_limit = heap_size / MaxHeapFractionDenominator; + if (imported_size + window_len > heap_import_limit) { + LOG_INFO(Render_Vulkan, + "Stopping guest memory import at {} MiB to leave room on heap {} of {} MiB", + imported_size >> 20, heap_index, heap_size >> 20); + logical.DestroyBufferRaw(new_buffer); + break; + } + const VkImportMemoryHostPointerInfoEXT import_info{ + .sType = VK_STRUCTURE_TYPE_IMPORT_MEMORY_HOST_POINTER_INFO_EXT, + .pNext = nullptr, + .handleType = VK_EXTERNAL_MEMORY_HANDLE_TYPE_HOST_ALLOCATION_BIT_EXT, + .pHostPointer = window_base, + }; + const VkMemoryAllocateInfo alloc_info{ + .sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO, + .pNext = &import_info, + .allocationSize = window_len, + .memoryTypeIndex = *type_index, + }; + vk::DeviceMemory memory = logical.TryAllocateMemory(alloc_info); + if (!memory) { + logical.DestroyBufferRaw(new_buffer); + break; + } + if (logical.BindBufferMemory(new_buffer, *memory, 0) != VK_SUCCESS) { + logical.DestroyBufferRaw(new_buffer); + break; + } + windows.push_back(Window{ + .memory = std::move(memory), + .buffer = new_buffer, + }); + imported_size += static_cast(window_len); + } + if (windows.empty()) { + LOG_INFO(Render_Vulkan, "Host pointer import failed"); + return false; + } + LOG_INFO(Render_Vulkan, + "Imported {} MiB of guest memory for unified memory access in {} windows", + imported_size >> 20, windows.size()); + return true; +} + +bool HostMemoryImport::ImportHardwareBuffers( + [[maybe_unused]] std::span hardware_buffers, + [[maybe_unused]] size_t hardware_buffer_window, + [[maybe_unused]] size_t hardware_buffer_base, [[maybe_unused]] size_t size) { +#ifdef __ANDROID__ + if (hardware_buffers.empty() || hardware_buffer_window == 0 || + !device.IsExtExternalMemoryAhbSupported()) { + return false; + } + using namespace Common::Literals; + u64 max_allocation_size = device.GetMaxMemoryAllocationSize(); + if (device.IsTiler()) { + constexpr u64 TilerAllocationLimit = 1_GiB; + max_allocation_size = max_allocation_size != 0 + ? (std::min)(max_allocation_size, TilerAllocationLimit) + : TilerAllocationLimit; + } + if (max_allocation_size != 0 && hardware_buffer_window > max_allocation_size) { + LOG_WARNING(Render_Vulkan, + "Hardware buffer windows of {} MiB exceed the {} MiB allocation limit", + hardware_buffer_window >> 20, max_allocation_size >> 20); + return false; + } + if (hardware_buffer_base >= size) { + return false; + } + const auto &logical = device.GetLogical(); + const auto memory_props = device.GetPhysical().GetMemoryProperties().memoryProperties; + window_size = hardware_buffer_window; + base_offset = hardware_buffer_base; + for (size_t i = 0; i < hardware_buffers.size(); ++i) { + const size_t offset = hardware_buffer_base + i * hardware_buffer_window; + if (offset >= size) { + break; + } + const VkDeviceSize window_len = (std::min)( + static_cast(size - offset), + static_cast(hardware_buffer_window)); + VkAndroidHardwareBufferPropertiesANDROID ahb_props{ + .sType = VK_STRUCTURE_TYPE_ANDROID_HARDWARE_BUFFER_PROPERTIES_ANDROID, + .pNext = nullptr, + .allocationSize = 0, + .memoryTypeBits = 0, + }; + if (logical.GetAndroidHardwareBufferPropertiesANDROID(hardware_buffers[i], + &ahb_props) != VK_SUCCESS || + ahb_props.memoryTypeBits == 0 || ahb_props.allocationSize < window_len) { + break; + } + const VkExternalMemoryBufferCreateInfo external_info{ + .sType = VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_BUFFER_CREATE_INFO, + .pNext = nullptr, + .handleTypes = + VK_EXTERNAL_MEMORY_HANDLE_TYPE_ANDROID_HARDWARE_BUFFER_BIT_ANDROID, + }; + const VkBufferCreateInfo buffer_ci{ + .sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO, + .pNext = &external_info, + .flags = 0, + .size = window_len, + .usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT, + .sharingMode = VK_SHARING_MODE_EXCLUSIVE, + .queueFamilyIndexCount = 0, + .pQueueFamilyIndices = nullptr, + }; + VkBuffer new_buffer{}; + if (logical.CreateBufferRaw(buffer_ci, &new_buffer) != VK_SUCCESS) { + break; + } + const VkMemoryRequirements requirements = + logical.GetBufferMemoryRequirements(new_buffer); + const u32 type_mask = requirements.memoryTypeBits & ahb_props.memoryTypeBits; + if (type_mask == 0 || requirements.size > ahb_props.allocationSize) { + logical.DestroyBufferRaw(new_buffer); + break; + } + const auto type_index = FindImportMemoryType(memory_props, type_mask); + if (!type_index) { + logical.DestroyBufferRaw(new_buffer); + break; + } + const VkImportAndroidHardwareBufferInfoANDROID import_info{ + .sType = VK_STRUCTURE_TYPE_IMPORT_ANDROID_HARDWARE_BUFFER_INFO_ANDROID, + .pNext = nullptr, + .buffer = hardware_buffers[i], + }; + const VkMemoryDedicatedAllocateInfo dedicated_info{ + .sType = VK_STRUCTURE_TYPE_MEMORY_DEDICATED_ALLOCATE_INFO, + .pNext = &import_info, + .image = VK_NULL_HANDLE, + .buffer = new_buffer, + }; + const VkMemoryAllocateInfo alloc_info{ + .sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO, + .pNext = &dedicated_info, + .allocationSize = ahb_props.allocationSize, + .memoryTypeIndex = *type_index, + }; + vk::DeviceMemory memory = logical.TryAllocateMemory(alloc_info); + if (!memory) { + logical.DestroyBufferRaw(new_buffer); + break; + } + if (logical.BindBufferMemory(new_buffer, *memory, 0) != VK_SUCCESS) { + logical.DestroyBufferRaw(new_buffer); + break; + } + windows.push_back(Window{ + .memory = std::move(memory), + .buffer = new_buffer, + }); + imported_size += static_cast(window_len); + } + if (windows.empty()) { + LOG_INFO(Render_Vulkan, "Hardware buffer import failed"); + window_size = 0; + base_offset = 0; + return false; + } + foreign_ownership = true; + LOG_INFO(Render_Vulkan, + "Imported {} MiB of guest memory at {:#x} via hardware buffers in {} windows", + imported_size >> 20, base_offset, windows.size()); + return true; +#else + return false; +#endif +} + +HostMemoryImport::~HostMemoryImport() { + for (Window &window : windows) { + if (window.buffer != VK_NULL_HANDLE) { + device.GetLogical().DestroyBufferRaw(window.buffer); + } + } +} + MemoryAllocator::MemoryAllocator(const Device &device_) : device{device_}, allocator{device.GetAllocator()}, properties{device_.GetPhysical().GetMemoryProperties().memoryProperties}, diff --git a/src/video_core/vulkan_common/vulkan_memory_allocator.h b/src/video_core/vulkan_common/vulkan_memory_allocator.h index a0f9081fc0..bbcb7288df 100644 --- a/src/video_core/vulkan_common/vulkan_memory_allocator.h +++ b/src/video_core/vulkan_common/vulkan_memory_allocator.h @@ -15,6 +15,8 @@ #include "video_core/vulkan_common/vulkan_wrapper.h" #include "video_core/vulkan_common/vma.h" +struct AHardwareBuffer; + namespace Vulkan { class Device; @@ -84,6 +86,66 @@ namespace Vulkan { void *mapped_ptr{}; ///< Optional persistent mapped pointer }; + class HostMemoryImport { + public: + explicit HostMemoryImport(const Device &device_, void *base, size_t size, + std::span hardware_buffers, + size_t hardware_buffer_window, size_t hardware_buffer_base); + + ~HostMemoryImport(); + + HostMemoryImport(const HostMemoryImport &) = delete; + + HostMemoryImport &operator=(const HostMemoryImport &) = delete; + + [[nodiscard]] bool IsValid() const noexcept { + return !windows.empty(); + } + + [[nodiscard]] size_t GetSize() const noexcept { + return imported_size; + } + + [[nodiscard]] size_t GetBaseOffset() const noexcept { + return base_offset; + } + + [[nodiscard]] bool NeedsForeignOwnershipTransfer() const noexcept { + return foreign_ownership; + } + + [[nodiscard]] VkDeviceSize GetWindowSize() const noexcept { + return window_size; + } + + [[nodiscard]] VkBuffer GetWindowBuffer(size_t index) const noexcept { + return windows[index].buffer; + } + + [[nodiscard]] size_t GetWindowCount() const noexcept { + return windows.size(); + } + + private: + struct Window { + vk::DeviceMemory memory; + VkBuffer buffer{}; + }; + + bool ImportHostPointer(void *base, size_t size); + + bool ImportHardwareBuffers(std::span hardware_buffers, + size_t hardware_buffer_window, size_t hardware_buffer_base, + size_t size); + + const Device &device; + std::vector windows; + VkDeviceSize window_size{}; + size_t imported_size{}; + size_t base_offset{}; + bool foreign_ownership{}; + }; + /// Memory allocator container. /// Allocates and releases memory allocations on demand. class MemoryAllocator { diff --git a/src/video_core/vulkan_common/vulkan_wrapper.cpp b/src/video_core/vulkan_common/vulkan_wrapper.cpp index 5044881598..9c86ee15ad 100644 --- a/src/video_core/vulkan_common/vulkan_wrapper.cpp +++ b/src/video_core/vulkan_common/vulkan_wrapper.cpp @@ -217,12 +217,16 @@ void Load(VkDevice device, DeviceDispatch& dld) noexcept { X(vkGetBufferMemoryRequirements2); X(vkGetDeviceQueue); X(vkGetEventStatus); + X(vkGetMemoryHostPointerPropertiesEXT); X(vkGetFenceStatus); X(vkGetImageMemoryRequirements); X(vkGetPipelineCacheData); X(vkGetMemoryFdKHR); #ifdef _WIN32 X(vkGetMemoryWin32HandleKHR); +#endif +#ifdef __ANDROID__ + X(vkGetAndroidHardwareBufferPropertiesANDROID); #endif X(vkGetQueryPoolResults); X(vkGetPipelineExecutablePropertiesKHR); diff --git a/src/video_core/vulkan_common/vulkan_wrapper.h b/src/video_core/vulkan_common/vulkan_wrapper.h index 97d2ba3700..d23f8fd8a2 100644 --- a/src/video_core/vulkan_common/vulkan_wrapper.h +++ b/src/video_core/vulkan_common/vulkan_wrapper.h @@ -333,12 +333,16 @@ struct DeviceDispatch : InstanceDispatch { PFN_vkGetBufferMemoryRequirements2 vkGetBufferMemoryRequirements2{}; PFN_vkGetDeviceQueue vkGetDeviceQueue{}; PFN_vkGetEventStatus vkGetEventStatus{}; + PFN_vkGetMemoryHostPointerPropertiesEXT vkGetMemoryHostPointerPropertiesEXT{}; PFN_vkGetFenceStatus vkGetFenceStatus{}; PFN_vkGetImageMemoryRequirements vkGetImageMemoryRequirements{}; PFN_vkGetPipelineCacheData vkGetPipelineCacheData{}; PFN_vkGetMemoryFdKHR vkGetMemoryFdKHR{}; #ifdef _WIN32 PFN_vkGetMemoryWin32HandleKHR vkGetMemoryWin32HandleKHR{}; +#endif +#ifdef __ANDROID__ + PFN_vkGetAndroidHardwareBufferPropertiesANDROID vkGetAndroidHardwareBufferPropertiesANDROID{}; #endif PFN_vkGetPipelineExecutablePropertiesKHR vkGetPipelineExecutablePropertiesKHR{}; PFN_vkGetPipelineExecutableStatisticsKHR vkGetPipelineExecutableStatisticsKHR{}; @@ -1104,6 +1108,34 @@ public: VkMemoryRequirements GetBufferMemoryRequirements(VkBuffer buffer, void* pnext = nullptr) const noexcept; + VkResult GetMemoryHostPointerPropertiesEXT( + VkExternalMemoryHandleTypeFlagBits handle_type, const void* host_pointer, + VkMemoryHostPointerPropertiesEXT* out_properties) const noexcept { + return dld->vkGetMemoryHostPointerPropertiesEXT(handle, handle_type, host_pointer, + out_properties); + } + +#ifdef __ANDROID__ + VkResult GetAndroidHardwareBufferPropertiesANDROID( + const struct AHardwareBuffer* buffer, + VkAndroidHardwareBufferPropertiesANDROID* out_properties) const noexcept { + return dld->vkGetAndroidHardwareBufferPropertiesANDROID(handle, buffer, out_properties); + } +#endif + + VkResult CreateBufferRaw(const VkBufferCreateInfo& ci, VkBuffer* out_buffer) const noexcept { + return dld->vkCreateBuffer(handle, &ci, nullptr, out_buffer); + } + + void DestroyBufferRaw(VkBuffer buffer) const noexcept { + dld->vkDestroyBuffer(handle, buffer, nullptr); + } + + VkResult BindBufferMemory(VkBuffer buffer, VkDeviceMemory memory, + VkDeviceSize offset) const noexcept { + return dld->vkBindBufferMemory(handle, buffer, memory, offset); + } + VkMemoryRequirements GetImageMemoryRequirements(VkImage image) const noexcept; std::vector GetPipelineExecutablePropertiesKHR( From 4a3a2c0a1171525ac1e8da0174c8d2b1fa30507f Mon Sep 17 00:00:00 2001 From: CamilleLaVey Date: Fri, 7 Aug 2026 15:54:08 -0400 Subject: [PATCH 02/27] [TEST] Adjustment AHB to tiled-gpu-v2 state --- src/common/heap_tracker.cpp | 48 +++------- src/common/heap_tracker.h | 3 - src/common/host_memory.cpp | 95 ++++++------------- src/common/host_memory.h | 2 - .../vulkan_common/vulkan_memory_allocator.cpp | 22 ++--- 5 files changed, 49 insertions(+), 121 deletions(-) diff --git a/src/common/heap_tracker.cpp b/src/common/heap_tracker.cpp index 0ca8683a34..b72abb16d8 100644 --- a/src/common/heap_tracker.cpp +++ b/src/common/heap_tracker.cpp @@ -4,43 +4,34 @@ // SPDX-FileCopyrightText: Copyright 2023 yuzu Emulator Project // SPDX-License-Identifier: GPL-2.0-or-later -#include +#include #include "common/heap_tracker.h" #include "common/logging.h" #include "common/assert.h" -#include "common/memory_detect.h" namespace Common { namespace { -s64 GetMaxPermissibleResidentMapCount(const Common::HostMemory& buffer) { +s64 GetMaxPermissibleResidentMapCount() { // Default value. - constexpr s64 DefaultMaxMapCount = 65530; + s64 value = 65530; // Try to read how many mappings we can make. - const u64 reported = Common::GetMaxMapCount(); - const s64 value = reported != 0 ? static_cast(reported) : DefaultMaxMapCount; + std::ifstream s("/proc/sys/vm/max_map_count"); + s >> value; // Print, for debug. LOG_INFO(HW_Memory, "Current maximum map count: {}", value); // Allow 20000 maps for other code and to account for split inaccuracy. - constexpr s64 ForeignMapReservation = 20000; - - const size_t hardware_buffer_windows = buffer.BackingHardwareBuffers().size(); - const s64 unmergeable_window_boundaries = - hardware_buffer_windows != 0 ? static_cast(hardware_buffer_windows) + 1 : 0; - - return std::max(value - ForeignMapReservation - unmergeable_window_boundaries, 0); + return std::max(value - 20000, 0); } } // namespace HeapTracker::HeapTracker(Common::HostMemory& buffer) - : m_buffer(buffer), - m_has_hardware_buffer_backing(!buffer.BackingHardwareBuffers().empty()), - m_max_resident_map_count(GetMaxPermissibleResidentMapCount(buffer)) {} + : m_buffer(buffer), m_max_resident_map_count(GetMaxPermissibleResidentMapCount()) {} HeapTracker::~HeapTracker() = default; void HeapTracker::Map(size_t virtual_offset, size_t host_offset, size_t length, @@ -94,8 +85,7 @@ void HeapTracker::Unmap(size_t virtual_offset, size_t size, bool is_separate_hea // If resident, erase from resident map. if (item->is_resident) { - m_resident_map_count -= this->HostMapCount(item->paddr, item->size); - ASSERT(m_resident_map_count >= 0); + ASSERT(--m_resident_map_count >= 0); m_resident_mappings.erase(m_resident_mappings.iterator_to(*item)); } @@ -201,7 +191,7 @@ bool HeapTracker::DeferredMapSeparateHeap(size_t virtual_offset) { // This map is now resident. it->is_resident = true; - m_resident_map_count += this->HostMapCount(it->paddr, it->size); + m_resident_map_count++; m_resident_mappings.insert(*it); } @@ -223,17 +213,17 @@ void HeapTracker::RebuildSeparateHeapAddressSpace() { // Despite being worse in theory, this has proven to be better in practice than more // regularly dumping a smaller amount, because it significantly reduces average case // lock contention. - s64 const desired_count = (std::min)(m_resident_map_count, m_max_resident_map_count) / 2; + std::size_t const desired_count = (std::min)(m_resident_map_count, m_max_resident_map_count) / 2; + std::size_t const evict_count = m_resident_map_count - desired_count; auto it = m_resident_mappings.begin(); - while (m_resident_map_count > desired_count && it != m_resident_mappings.end()) { + for (size_t i = 0; i < evict_count && it != m_resident_mappings.end(); i++) { // Unmark and unmap. it->is_resident = false; m_buffer.Unmap(it->vaddr, it->size, false); // Advance. - m_resident_map_count -= this->HostMapCount(it->paddr, it->size); - ASSERT(m_resident_map_count >= 0); + ASSERT(--m_resident_map_count >= 0); it = m_resident_mappings.erase(it); } } @@ -255,7 +245,6 @@ void HeapTracker::SplitHeapMapLocked(VAddr offset) { // Cache the original values. auto* const left = std::addressof(*it); const size_t orig_size = left->size; - const s64 orig_host_map_count = this->HostMapCount(left->paddr, orig_size); // Adjust the left map. const size_t left_size = offset - left->vaddr; @@ -277,20 +266,11 @@ void HeapTracker::SplitHeapMapLocked(VAddr offset) { // If resident, also insert into resident map. if (right->is_resident) { - m_resident_map_count += this->HostMapCount(left->paddr, left->size) + - this->HostMapCount(right->paddr, right->size) - - orig_host_map_count; + m_resident_map_count++; m_resident_mappings.insert(*right); } } -s64 HeapTracker::HostMapCount(PAddr paddr, size_t size) const { - if (!m_has_hardware_buffer_backing) { - return size != 0 ? 1 : 0; - } - return static_cast(m_buffer.BackingMapCount(paddr, size)); -} - HeapTracker::AddrTree::iterator HeapTracker::GetNearestHeapMapLocked(VAddr offset) { const SeparateHeapMap key{ .vaddr = offset, diff --git a/src/common/heap_tracker.h b/src/common/heap_tracker.h index 8be66a1d4d..9cc25f7964 100644 --- a/src/common/heap_tracker.h +++ b/src/common/heap_tracker.h @@ -85,13 +85,10 @@ private: AddrTree::iterator GetNearestHeapMapLocked(VAddr offset); - s64 HostMapCount(PAddr paddr, size_t size) const; - void RebuildSeparateHeapAddressSpace(); private: Common::HostMemory& m_buffer; - const bool m_has_hardware_buffer_backing; const s64 m_max_resident_map_count; std::shared_mutex m_rebuild_lock{}; diff --git a/src/common/host_memory.cpp b/src/common/host_memory.cpp index 9110dbc914..26e1bdf316 100644 --- a/src/common/host_memory.cpp +++ b/src/common/host_memory.cpp @@ -681,37 +681,44 @@ public: return ok; } - size_t ComputeAhbWindowCount(size_t window_size) const { + size_t ComputeAhbBudget(size_t window_size) const { const u64 total_physical = Common::GetMemInfo().TotalPhysicalMemory; if (total_physical == 0) { LOG_WARNING(HW_Memory, "Host memory size is unknown, not committing hardware buffers"); return 0; } - constexpr u64 MinimumTotalPhysical = 5632ULL << 20; + constexpr u64 MinimumTotalPhysical = 7ULL << 30; if (total_physical < MinimumTotalPhysical) { LOG_INFO(HW_Memory, "Skipping hardware buffer backing, {} MiB of RAM is below the {} MiB minimum", total_physical >> 20, MinimumTotalPhysical >> 20); return 0; } - constexpr u64 MaxWindows = 2; - u64 windows = MaxWindows; - windows = (std::min)(windows, (total_physical / 6) / window_size); + const u64 max_map_count = Common::GetMaxMapCount(); + constexpr u64 ReservedMaps = 24576; + if (max_map_count == 0 || max_map_count <= ReservedMaps) { + LOG_WARNING(HW_Memory, + "Skipping hardware buffer backing, vm.max_map_count is unknown or too low"); + return 0; + } + u64 budget = total_physical / 6; + budget = (std::min)(budget, (max_map_count - ReservedMaps) * PageAlignment); const u64 available = Common::GetAvailablePhysicalMemory(); if (available != 0) { constexpr u64 Headroom = 2ULL << 30; - const u64 spare = available > Headroom ? available - Headroom : 0; - windows = (std::min)(windows, spare / window_size); + budget = (std::min)(budget, available > Headroom ? available - Headroom : 0); } - windows = (std::min)(windows, static_cast(backing_size) / window_size); - if (windows == 0) { + budget = (std::min)(budget, static_cast(backing_size)); + budget = Common::AlignDown(budget, window_size); + constexpr u64 MinimumBudget = 256ULL << 20; + if (budget < MinimumBudget) { LOG_INFO(HW_Memory, - "Skipping hardware buffer backing, no {} MiB window fits on a {} MiB system " - "with {} MiB available", - window_size >> 20, total_physical >> 20, available >> 20); + "Skipping hardware buffer backing, only {} MiB could be committed on a {} MiB " + "system with {} MiB available and vm.max_map_count {}", + budget >> 20, total_physical >> 20, available >> 20, max_map_count); return 0; } - return static_cast(windows); + return static_cast(budget); } bool InitAhbBacking() { @@ -724,38 +731,25 @@ public: LOG_WARNING(HW_Memory, "AHardwareBuffer_getNativeHandle is not available"); return false; } - constexpr size_t WindowCandidates[] = { - 512ULL << 20, - 256ULL << 20, - 128ULL << 20, - 64ULL << 20, - }; - static_assert(WindowCandidates[0] <= 0xFFFFFFFFull, - "AHARDWAREBUFFER_FORMAT_BLOB encodes its size in a u32 width"); - size_t window_size = 0; - for (const size_t candidate : WindowCandidates) { - const AHardwareBuffer_Desc candidate_desc = MakeBlobDesc(candidate); - if (AHardwareBuffer_isSupported(&candidate_desc) != 0) { - window_size = candidate; - break; - } - LOG_INFO(HW_Memory, "Allocator rejects {} MiB hardware buffer windows", candidate >> 20); - } - if (window_size == 0) { - LOG_WARNING(HW_Memory, "No hardware buffer window size is supported"); + constexpr size_t window_size = 64ULL << 20; + const AHardwareBuffer_Desc window_desc = MakeBlobDesc(window_size); + if (AHardwareBuffer_isSupported(&window_desc) == 0) { + LOG_WARNING(HW_Memory, "Allocator rejects {} MiB hardware buffer windows", + window_size >> 20); return false; } - const size_t num_windows = ComputeAhbWindowCount(window_size); - if (num_windows == 0) { + const size_t budget = ComputeAhbBudget(window_size); + if (budget == 0) { return false; } if (!ProbeAhbBacking(get_native_handle)) { return false; } const size_t aligned_backing = Common::AlignDown(backing_size, window_size); - const size_t region_size = num_windows * window_size; + const size_t region_size = (std::min)(budget, aligned_backing); const size_t region_base = Common::AlignDown( (std::min)(preferred_offset, aligned_backing - region_size), window_size); + const size_t num_windows = region_size / window_size; std::vector buffers; std::vector buffer_fds; @@ -863,29 +857,6 @@ public: } } - size_t BackingMapCount(size_t host_offset, size_t length) const noexcept { - if (length == 0) { - return 0; - } - if (ahb_bytes == 0) { - return 1; - } - size_t count = 0; - while (length > 0) { - size_t chunk = length; - if (host_offset < ahb_base) { - chunk = (std::min)(chunk, ahb_base - host_offset); - } else if (host_offset < ahb_base + ahb_bytes) { - const size_t local = (host_offset - ahb_base) % ahb_window_size; - chunk = (std::min)(chunk, ahb_window_size - local); - } - host_offset += chunk; - length -= chunk; - ++count; - } - return count; - } - std::span AhbWindows() const noexcept { return ahb_windows; } @@ -1159,14 +1130,6 @@ std::span HostMemory::BackingHardwareBuffers() const noe #endif } -size_t HostMemory::BackingMapCount(size_t host_offset, size_t length) const noexcept { -#ifdef __ANDROID__ - return impl ? impl->BackingMapCount(host_offset, length) : (length != 0 ? 1 : 0); -#else - return length != 0 ? 1 : 0; -#endif -} - size_t HostMemory::BackingHardwareBufferWindowSize() const noexcept { #ifdef __ANDROID__ return impl ? impl->AhbWindowSize() : 0; diff --git a/src/common/host_memory.h b/src/common/host_memory.h index 547901bbe9..26069aceba 100644 --- a/src/common/host_memory.h +++ b/src/common/host_memory.h @@ -70,8 +70,6 @@ public: return backing_size; } - [[nodiscard]] size_t BackingMapCount(size_t host_offset, size_t length) const noexcept; - [[nodiscard]] std::span BackingHardwareBuffers() const noexcept; [[nodiscard]] size_t BackingHardwareBufferWindowSize() const noexcept; diff --git a/src/video_core/vulkan_common/vulkan_memory_allocator.cpp b/src/video_core/vulkan_common/vulkan_memory_allocator.cpp index 3e7dea4a49..9f44cd3584 100644 --- a/src/video_core/vulkan_common/vulkan_memory_allocator.cpp +++ b/src/video_core/vulkan_common/vulkan_memory_allocator.cpp @@ -214,10 +214,10 @@ HostMemoryImport::HostMemoryImport(const Device &device_, void *base, size_t siz size)) { return; } - if (device.IsTiler()) { + if (!hardware_buffers.empty()) { LOG_INFO(Render_Vulkan, - "Unified memory disabled, hardware buffer import is the only path supported " - "by tiler drivers"); + "Unified memory disabled, guest memory is backed by hardware buffers that " + "could not be imported"); return; } if (ImportHostPointer(base, size)) { @@ -241,8 +241,7 @@ bool HostMemoryImport::ImportHostPointer(void *base, size_t size) { return false; } using namespace Common::Literals; - constexpr VkDeviceSize DesktopWindowSize = 4_GiB; - VkDeviceSize candidate_window = DesktopWindowSize; + VkDeviceSize candidate_window = 1_GiB; const u64 max_buffer_size = device.GetMaxBufferSize(); if (max_buffer_size != 0 && max_buffer_size < candidate_window) { candidate_window = max_buffer_size; @@ -306,11 +305,9 @@ bool HostMemoryImport::ImportHostPointer(void *base, size_t size) { logical.DestroyBufferRaw(new_buffer); break; } - constexpr VkDeviceSize MaxHeapFractionDenominator = 2; const u32 heap_index = memory_props.memoryTypes[*type_index].heapIndex; const VkDeviceSize heap_size = memory_props.memoryHeaps[heap_index].size; - const VkDeviceSize heap_import_limit = heap_size / MaxHeapFractionDenominator; - if (imported_size + window_len > heap_import_limit) { + if (imported_size + window_len > heap_size / 2) { LOG_INFO(Render_Vulkan, "Stopping guest memory import at {} MiB to leave room on heap {} of {} MiB", imported_size >> 20, heap_index, heap_size >> 20); @@ -363,14 +360,7 @@ bool HostMemoryImport::ImportHardwareBuffers( !device.IsExtExternalMemoryAhbSupported()) { return false; } - using namespace Common::Literals; - u64 max_allocation_size = device.GetMaxMemoryAllocationSize(); - if (device.IsTiler()) { - constexpr u64 TilerAllocationLimit = 1_GiB; - max_allocation_size = max_allocation_size != 0 - ? (std::min)(max_allocation_size, TilerAllocationLimit) - : TilerAllocationLimit; - } + const u64 max_allocation_size = device.GetMaxMemoryAllocationSize(); if (max_allocation_size != 0 && hardware_buffer_window > max_allocation_size) { LOG_WARNING(Render_Vulkan, "Hardware buffer windows of {} MiB exceed the {} MiB allocation limit", From ce864eac3825a5a8ca8e1ccc4d6c5d397a873a12 Mon Sep 17 00:00:00 2001 From: CamilleLaVey Date: Fri, 7 Aug 2026 20:09:33 -0400 Subject: [PATCH 03/27] [TEST] Increased window limiter on AHB --- src/common/host_memory.cpp | 28 +------------------ .../vulkan_common/vulkan_device.cpp | 4 --- .../vulkan_common/vulkan_memory_allocator.cpp | 28 ++++--------------- 3 files changed, 6 insertions(+), 54 deletions(-) diff --git a/src/common/host_memory.cpp b/src/common/host_memory.cpp index 26e1bdf316..e7b2d01e84 100644 --- a/src/common/host_memory.cpp +++ b/src/common/host_memory.cpp @@ -648,12 +648,10 @@ public: const AHardwareBuffer_Desc desc = MakeBlobDesc(PageAlignment * 2); AHardwareBuffer* buffer{}; if (AHardwareBuffer_allocate(&desc, &buffer) != 0 || buffer == nullptr) { - LOG_WARNING(HW_Memory, "Hardware buffer probe allocation failed"); return false; } const NativeHandle* const handle = get_native_handle(buffer); if (handle == nullptr || handle->numFds < 1) { - LOG_WARNING(HW_Memory, "Hardware buffer has no mappable file descriptor"); AHardwareBuffer_release(buffer); return false; } @@ -665,8 +663,6 @@ public: } void* const ptr = mmap(nullptr, PageAlignment, prot, MAP_SHARED, probe_fd, offset); if (ptr == MAP_FAILED) { - LOG_WARNING(HW_Memory, "Hardware buffer backing rejects {}: {}", what, - strerror(errno)); ok = false; return; } @@ -684,21 +680,15 @@ public: size_t ComputeAhbBudget(size_t window_size) const { const u64 total_physical = Common::GetMemInfo().TotalPhysicalMemory; if (total_physical == 0) { - LOG_WARNING(HW_Memory, "Host memory size is unknown, not committing hardware buffers"); return 0; } constexpr u64 MinimumTotalPhysical = 7ULL << 30; if (total_physical < MinimumTotalPhysical) { - LOG_INFO(HW_Memory, - "Skipping hardware buffer backing, {} MiB of RAM is below the {} MiB minimum", - total_physical >> 20, MinimumTotalPhysical >> 20); return 0; } const u64 max_map_count = Common::GetMaxMapCount(); constexpr u64 ReservedMaps = 24576; if (max_map_count == 0 || max_map_count <= ReservedMaps) { - LOG_WARNING(HW_Memory, - "Skipping hardware buffer backing, vm.max_map_count is unknown or too low"); return 0; } u64 budget = total_physical / 6; @@ -712,10 +702,6 @@ public: budget = Common::AlignDown(budget, window_size); constexpr u64 MinimumBudget = 256ULL << 20; if (budget < MinimumBudget) { - LOG_INFO(HW_Memory, - "Skipping hardware buffer backing, only {} MiB could be committed on a {} MiB " - "system with {} MiB available and vm.max_map_count {}", - budget >> 20, total_physical >> 20, available >> 20, max_map_count); return 0; } return static_cast(budget); @@ -728,14 +714,11 @@ public: static const PFN_AHardwareBuffer_getNativeHandle get_native_handle = ResolveGetNativeHandle(); if (get_native_handle == nullptr) { - LOG_WARNING(HW_Memory, "AHardwareBuffer_getNativeHandle is not available"); return false; } - constexpr size_t window_size = 64ULL << 20; + constexpr size_t window_size = 128ULL << 20; const AHardwareBuffer_Desc window_desc = MakeBlobDesc(window_size); if (AHardwareBuffer_isSupported(&window_desc) == 0) { - LOG_WARNING(HW_Memory, "Allocator rejects {} MiB hardware buffer windows", - window_size >> 20); return false; } const size_t budget = ComputeAhbBudget(window_size); @@ -764,22 +747,18 @@ public: const AHardwareBuffer_Desc desc = MakeBlobDesc(window_size); AHardwareBuffer* buffer{}; if (AHardwareBuffer_allocate(&desc, &buffer) != 0 || buffer == nullptr) { - LOG_WARNING(HW_Memory, "Hardware buffer allocation failed for window {} of {}", i, - num_windows); cleanup(); return false; } buffers.push_back(buffer); const NativeHandle* const handle = get_native_handle(buffer); if (handle == nullptr || handle->numFds < 1) { - LOG_WARNING(HW_Memory, "Hardware buffer has no mappable file descriptor"); cleanup(); return false; } const int buffer_fd = handle->data[0]; const off_t buffer_len = lseek(buffer_fd, 0, SEEK_END); if (buffer_len < static_cast(window_size)) { - LOG_WARNING(HW_Memory, "Hardware buffer descriptor smaller than requested"); cleanup(); return false; } @@ -788,7 +767,6 @@ public: u8* const base = static_cast(mmap(nullptr, backing_size, PROT_NONE, MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0)); if (base == MAP_FAILED) { - LOG_WARNING(HW_Memory, "Failed to reserve backing address space: {}", strerror(errno)); cleanup(); return false; } @@ -799,7 +777,6 @@ public: } if (mmap(base + offset, len, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_FIXED, map_fd, map_offset) == MAP_FAILED) { - LOG_WARNING(HW_Memory, "Backing mmap failed: {}", strerror(errno)); munmap(base, backing_size); cleanup(); return false; @@ -827,9 +804,6 @@ public: ahb_base = region_base; ahb_bytes = region_size; committed_backing_size.store(region_size, std::memory_order_relaxed); - LOG_INFO(HW_Memory, - "Guest memory {:#x}-{:#x} backed by {} hardware buffer windows, {} MiB committed", - region_base, region_base + region_size, ahb_windows.size(), region_size >> 20); return true; } diff --git a/src/video_core/vulkan_common/vulkan_device.cpp b/src/video_core/vulkan_common/vulkan_device.cpp index 83b76b9776..d36c6b85e1 100644 --- a/src/video_core/vulkan_common/vulkan_device.cpp +++ b/src/video_core/vulkan_common/vulkan_device.cpp @@ -1067,10 +1067,6 @@ bool Device::GetSuitability(bool requires_swapchain) { #ifdef __ANDROID__ if (extensions.external_memory_ahb && !extensions.queue_family_foreign) { - LOG_INFO(Render_Vulkan, - "Not loading {} because its dependency {} is unavailable", - VK_ANDROID_EXTERNAL_MEMORY_ANDROID_HARDWARE_BUFFER_EXTENSION_NAME, - VK_EXT_QUEUE_FAMILY_FOREIGN_EXTENSION_NAME); loaded_extensions.erase(VK_ANDROID_EXTERNAL_MEMORY_ANDROID_HARDWARE_BUFFER_EXTENSION_NAME); extensions.external_memory_ahb = false; } diff --git a/src/video_core/vulkan_common/vulkan_memory_allocator.cpp b/src/video_core/vulkan_common/vulkan_memory_allocator.cpp index 9f44cd3584..0209834045 100644 --- a/src/video_core/vulkan_common/vulkan_memory_allocator.cpp +++ b/src/video_core/vulkan_common/vulkan_memory_allocator.cpp @@ -214,10 +214,10 @@ HostMemoryImport::HostMemoryImport(const Device &device_, void *base, size_t siz size)) { return; } + if (device.IsTiler()) { + return; + } if (!hardware_buffers.empty()) { - LOG_INFO(Render_Vulkan, - "Unified memory disabled, guest memory is backed by hardware buffers that " - "could not be imported"); return; } if (ImportHostPointer(base, size)) { @@ -228,20 +228,16 @@ HostMemoryImport::HostMemoryImport(const Device &device_, void *base, size_t siz bool HostMemoryImport::ImportHostPointer(void *base, size_t size) { if (!device.IsExtExternalMemoryHostSupported()) { - LOG_INFO(Render_Vulkan, - "Unified memory disabled, VK_EXT_external_memory_host is not supported"); return false; } const u64 alignment = device.GetMinImportedHostPointerAlignment(); if (alignment == 0 || !Common::IsAligned(reinterpret_cast(base), alignment) || !Common::IsAligned(size, alignment)) { - LOG_INFO(Render_Vulkan, - "Unified memory disabled, host allocation does not satisfy alignment {}", - alignment); return false; } using namespace Common::Literals; - VkDeviceSize candidate_window = 1_GiB; + constexpr VkDeviceSize DesktopWindowSize = 4_GiB; + VkDeviceSize candidate_window = DesktopWindowSize; const u64 max_buffer_size = device.GetMaxBufferSize(); if (max_buffer_size != 0 && max_buffer_size < candidate_window) { candidate_window = max_buffer_size; @@ -308,9 +304,6 @@ bool HostMemoryImport::ImportHostPointer(void *base, size_t size) { const u32 heap_index = memory_props.memoryTypes[*type_index].heapIndex; const VkDeviceSize heap_size = memory_props.memoryHeaps[heap_index].size; if (imported_size + window_len > heap_size / 2) { - LOG_INFO(Render_Vulkan, - "Stopping guest memory import at {} MiB to leave room on heap {} of {} MiB", - imported_size >> 20, heap_index, heap_size >> 20); logical.DestroyBufferRaw(new_buffer); break; } @@ -342,12 +335,8 @@ bool HostMemoryImport::ImportHostPointer(void *base, size_t size) { imported_size += static_cast(window_len); } if (windows.empty()) { - LOG_INFO(Render_Vulkan, "Host pointer import failed"); return false; } - LOG_INFO(Render_Vulkan, - "Imported {} MiB of guest memory for unified memory access in {} windows", - imported_size >> 20, windows.size()); return true; } @@ -362,9 +351,6 @@ bool HostMemoryImport::ImportHardwareBuffers( } const u64 max_allocation_size = device.GetMaxMemoryAllocationSize(); if (max_allocation_size != 0 && hardware_buffer_window > max_allocation_size) { - LOG_WARNING(Render_Vulkan, - "Hardware buffer windows of {} MiB exceed the {} MiB allocation limit", - hardware_buffer_window >> 20, max_allocation_size >> 20); return false; } if (hardware_buffer_base >= size) { @@ -458,15 +444,11 @@ bool HostMemoryImport::ImportHardwareBuffers( imported_size += static_cast(window_len); } if (windows.empty()) { - LOG_INFO(Render_Vulkan, "Hardware buffer import failed"); window_size = 0; base_offset = 0; return false; } foreign_ownership = true; - LOG_INFO(Render_Vulkan, - "Imported {} MiB of guest memory at {:#x} via hardware buffers in {} windows", - imported_size >> 20, base_offset, windows.size()); return true; #else return false; From a8589321bcbd4588f87f0b640fd1c6b85f35d163 Mon Sep 17 00:00:00 2001 From: CamilleLaVey Date: Fri, 7 Aug 2026 20:50:03 -0400 Subject: [PATCH 04/27] Increased windows size --- src/common/host_memory.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/common/host_memory.cpp b/src/common/host_memory.cpp index e7b2d01e84..e4f45e84d6 100644 --- a/src/common/host_memory.cpp +++ b/src/common/host_memory.cpp @@ -716,7 +716,7 @@ public: if (get_native_handle == nullptr) { return false; } - constexpr size_t window_size = 128ULL << 20; + constexpr size_t window_size = 256ULL << 20; const AHardwareBuffer_Desc window_desc = MakeBlobDesc(window_size); if (AHardwareBuffer_isSupported(&window_desc) == 0) { return false; From c0c0af60858b2220d53a719ce74c816515396ee8 Mon Sep 17 00:00:00 2001 From: CamilleLaVey Date: Fri, 7 Aug 2026 20:58:31 -0400 Subject: [PATCH 05/27] [TEST] Another increased on windows size --- src/common/host_memory.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/common/host_memory.cpp b/src/common/host_memory.cpp index e4f45e84d6..8715cf3458 100644 --- a/src/common/host_memory.cpp +++ b/src/common/host_memory.cpp @@ -716,7 +716,7 @@ public: if (get_native_handle == nullptr) { return false; } - constexpr size_t window_size = 256ULL << 20; + constexpr size_t window_size = 512ULL << 20; const AHardwareBuffer_Desc window_desc = MakeBlobDesc(window_size); if (AHardwareBuffer_isSupported(&window_desc) == 0) { return false; From 0ebf1ff07cb123cfab4daa80ad34adf1f22ce426 Mon Sep 17 00:00:00 2001 From: CamilleLaVey Date: Tue, 11 Aug 2026 14:44:58 -0400 Subject: [PATCH 06/27] Keep AHB limitations --- src/common/heap_tracker.cpp | 29 +++++++++---- src/common/heap_tracker.h | 3 ++ src/common/host_memory.cpp | 80 ++++++++++++++++++++++++------------ src/common/host_memory.h | 2 + src/common/memory_detect.cpp | 3 ++ src/common/memory_detect.h | 3 ++ src/core/device_memory.cpp | 3 ++ 7 files changed, 89 insertions(+), 34 deletions(-) diff --git a/src/common/heap_tracker.cpp b/src/common/heap_tracker.cpp index b72abb16d8..4475ab5f0e 100644 --- a/src/common/heap_tracker.cpp +++ b/src/common/heap_tracker.cpp @@ -31,7 +31,9 @@ s64 GetMaxPermissibleResidentMapCount() { } // namespace HeapTracker::HeapTracker(Common::HostMemory& buffer) - : m_buffer(buffer), m_max_resident_map_count(GetMaxPermissibleResidentMapCount()) {} + : m_buffer(buffer), + m_has_hardware_buffer_backing(!buffer.BackingHardwareBuffers().empty()), + m_max_resident_map_count(GetMaxPermissibleResidentMapCount()) {} HeapTracker::~HeapTracker() = default; void HeapTracker::Map(size_t virtual_offset, size_t host_offset, size_t length, @@ -85,7 +87,8 @@ void HeapTracker::Unmap(size_t virtual_offset, size_t size, bool is_separate_hea // If resident, erase from resident map. if (item->is_resident) { - ASSERT(--m_resident_map_count >= 0); + m_resident_map_count -= this->HostMapCount(item->paddr, item->size); + ASSERT(m_resident_map_count >= 0); m_resident_mappings.erase(m_resident_mappings.iterator_to(*item)); } @@ -191,7 +194,7 @@ bool HeapTracker::DeferredMapSeparateHeap(size_t virtual_offset) { // This map is now resident. it->is_resident = true; - m_resident_map_count++; + m_resident_map_count += this->HostMapCount(it->paddr, it->size); m_resident_mappings.insert(*it); } @@ -213,17 +216,17 @@ void HeapTracker::RebuildSeparateHeapAddressSpace() { // Despite being worse in theory, this has proven to be better in practice than more // regularly dumping a smaller amount, because it significantly reduces average case // lock contention. - std::size_t const desired_count = (std::min)(m_resident_map_count, m_max_resident_map_count) / 2; - std::size_t const evict_count = m_resident_map_count - desired_count; + s64 const desired_count = (std::min)(m_resident_map_count, m_max_resident_map_count) / 2; auto it = m_resident_mappings.begin(); - for (size_t i = 0; i < evict_count && it != m_resident_mappings.end(); i++) { + while (m_resident_map_count > desired_count && it != m_resident_mappings.end()) { // Unmark and unmap. it->is_resident = false; m_buffer.Unmap(it->vaddr, it->size, false); // Advance. - ASSERT(--m_resident_map_count >= 0); + m_resident_map_count -= this->HostMapCount(it->paddr, it->size); + ASSERT(m_resident_map_count >= 0); it = m_resident_mappings.erase(it); } } @@ -245,6 +248,7 @@ void HeapTracker::SplitHeapMapLocked(VAddr offset) { // Cache the original values. auto* const left = std::addressof(*it); const size_t orig_size = left->size; + const s64 orig_host_map_count = this->HostMapCount(left->paddr, orig_size); // Adjust the left map. const size_t left_size = offset - left->vaddr; @@ -266,11 +270,20 @@ void HeapTracker::SplitHeapMapLocked(VAddr offset) { // If resident, also insert into resident map. if (right->is_resident) { - m_resident_map_count++; + m_resident_map_count += this->HostMapCount(left->paddr, left->size) + + this->HostMapCount(right->paddr, right->size) - + orig_host_map_count; m_resident_mappings.insert(*right); } } +s64 HeapTracker::HostMapCount(PAddr paddr, size_t size) const { + if (!m_has_hardware_buffer_backing) { + return size != 0 ? 1 : 0; + } + return static_cast(m_buffer.BackingMapCount(paddr, size)); +} + HeapTracker::AddrTree::iterator HeapTracker::GetNearestHeapMapLocked(VAddr offset) { const SeparateHeapMap key{ .vaddr = offset, diff --git a/src/common/heap_tracker.h b/src/common/heap_tracker.h index 9cc25f7964..8be66a1d4d 100644 --- a/src/common/heap_tracker.h +++ b/src/common/heap_tracker.h @@ -85,10 +85,13 @@ private: AddrTree::iterator GetNearestHeapMapLocked(VAddr offset); + s64 HostMapCount(PAddr paddr, size_t size) const; + void RebuildSeparateHeapAddressSpace(); private: Common::HostMemory& m_buffer; + const bool m_has_hardware_buffer_backing; const s64 m_max_resident_map_count; std::shared_mutex m_rebuild_lock{}; diff --git a/src/common/host_memory.cpp b/src/common/host_memory.cpp index 8715cf3458..a318733cd5 100644 --- a/src/common/host_memory.cpp +++ b/src/common/host_memory.cpp @@ -679,11 +679,8 @@ public: size_t ComputeAhbBudget(size_t window_size) const { const u64 total_physical = Common::GetMemInfo().TotalPhysicalMemory; - if (total_physical == 0) { - return 0; - } - constexpr u64 MinimumTotalPhysical = 7ULL << 30; - if (total_physical < MinimumTotalPhysical) { + constexpr u64 BaselineFootprint = 6ULL << 30; + if (total_physical <= BaselineFootprint) { return 0; } const u64 max_map_count = Common::GetMaxMapCount(); @@ -691,12 +688,13 @@ public: if (max_map_count == 0 || max_map_count <= ReservedMaps) { return 0; } - u64 budget = total_physical / 6; - budget = (std::min)(budget, (max_map_count - ReservedMaps) * PageAlignment); + u64 budget = (total_physical - BaselineFootprint) / 2; + constexpr u64 MapSlotsPerWindow = 4096; + const u64 affordable_windows = (max_map_count - ReservedMaps) / MapSlotsPerWindow; + budget = (std::min)(budget, affordable_windows * window_size); const u64 available = Common::GetAvailablePhysicalMemory(); if (available != 0) { - constexpr u64 Headroom = 2ULL << 30; - budget = (std::min)(budget, available > Headroom ? available - Headroom : 0); + budget = (std::min)(budget, available / 2); } budget = (std::min)(budget, static_cast(backing_size)); budget = Common::AlignDown(budget, window_size); @@ -716,11 +714,7 @@ public: if (get_native_handle == nullptr) { return false; } - constexpr size_t window_size = 512ULL << 20; - const AHardwareBuffer_Desc window_desc = MakeBlobDesc(window_size); - if (AHardwareBuffer_isSupported(&window_desc) == 0) { - return false; - } + constexpr size_t window_size = 256ULL << 20; const size_t budget = ComputeAhbBudget(window_size); if (budget == 0) { return false; @@ -729,10 +723,7 @@ public: return false; } const size_t aligned_backing = Common::AlignDown(backing_size, window_size); - const size_t region_size = (std::min)(budget, aligned_backing); - const size_t region_base = Common::AlignDown( - (std::min)(preferred_offset, aligned_backing - region_size), window_size); - const size_t num_windows = region_size / window_size; + const size_t max_windows = (std::min)(budget, aligned_backing) / window_size; std::vector buffers; std::vector buffer_fds; @@ -743,27 +734,33 @@ public: buffers.clear(); buffer_fds.clear(); }; - for (size_t i = 0; i < num_windows; ++i) { + for (size_t i = 0; i < max_windows; ++i) { const AHardwareBuffer_Desc desc = MakeBlobDesc(window_size); AHardwareBuffer* buffer{}; if (AHardwareBuffer_allocate(&desc, &buffer) != 0 || buffer == nullptr) { - cleanup(); - return false; + break; } - buffers.push_back(buffer); const NativeHandle* const handle = get_native_handle(buffer); if (handle == nullptr || handle->numFds < 1) { - cleanup(); - return false; + AHardwareBuffer_release(buffer); + break; } const int buffer_fd = handle->data[0]; const off_t buffer_len = lseek(buffer_fd, 0, SEEK_END); if (buffer_len < static_cast(window_size)) { - cleanup(); - return false; + AHardwareBuffer_release(buffer); + break; } + buffers.push_back(buffer); buffer_fds.push_back(buffer_fd); } + const size_t num_windows = buffers.size(); + if (num_windows == 0) { + return false; + } + const size_t region_size = num_windows * window_size; + const size_t region_base = Common::AlignDown( + (std::min)(preferred_offset, aligned_backing - region_size), window_size); u8* const base = static_cast(mmap(nullptr, backing_size, PROT_NONE, MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0)); if (base == MAP_FAILED) { @@ -831,6 +828,29 @@ public: } } + size_t BackingMapCount(size_t host_offset, size_t length) const noexcept { + if (length == 0) { + return 0; + } + if (ahb_bytes == 0) { + return 1; + } + size_t count = 0; + while (length > 0) { + size_t chunk = length; + if (host_offset < ahb_base) { + chunk = (std::min)(chunk, ahb_base - host_offset); + } else if (host_offset < ahb_base + ahb_bytes) { + const size_t local = (host_offset - ahb_base) % ahb_window_size; + chunk = (std::min)(chunk, ahb_window_size - local); + } + host_offset += chunk; + length -= chunk; + ++count; + } + return count; + } + std::span AhbWindows() const noexcept { return ahb_windows; } @@ -1104,6 +1124,14 @@ std::span HostMemory::BackingHardwareBuffers() const noe #endif } +size_t HostMemory::BackingMapCount(size_t host_offset, size_t length) const noexcept { +#ifdef __ANDROID__ + return impl ? impl->BackingMapCount(host_offset, length) : (length != 0 ? 1 : 0); +#else + return length != 0 ? 1 : 0; +#endif +} + size_t HostMemory::BackingHardwareBufferWindowSize() const noexcept { #ifdef __ANDROID__ return impl ? impl->AhbWindowSize() : 0; diff --git a/src/common/host_memory.h b/src/common/host_memory.h index 26069aceba..547901bbe9 100644 --- a/src/common/host_memory.h +++ b/src/common/host_memory.h @@ -70,6 +70,8 @@ public: return backing_size; } + [[nodiscard]] size_t BackingMapCount(size_t host_offset, size_t length) const noexcept; + [[nodiscard]] std::span BackingHardwareBuffers() const noexcept; [[nodiscard]] size_t BackingHardwareBufferWindowSize() const noexcept; diff --git a/src/common/memory_detect.cpp b/src/common/memory_detect.cpp index d0f9518bf5..457168a6ca 100644 --- a/src/common/memory_detect.cpp +++ b/src/common/memory_detect.cpp @@ -1,3 +1,6 @@ +// SPDX-FileCopyrightText: Copyright 2026 Eden Emulator Project +// SPDX-License-Identifier: GPL-3.0-or-later + // SPDX-FileCopyrightText: Copyright 2020 yuzu Emulator Project // SPDX-License-Identifier: GPL-2.0-or-later diff --git a/src/common/memory_detect.h b/src/common/memory_detect.h index 3bf013b79a..ce5d03788f 100644 --- a/src/common/memory_detect.h +++ b/src/common/memory_detect.h @@ -1,3 +1,6 @@ +// SPDX-FileCopyrightText: Copyright 2026 Eden Emulator Project +// SPDX-License-Identifier: GPL-3.0-or-later + // SPDX-FileCopyrightText: Copyright 2020 yuzu Emulator Project // SPDX-License-Identifier: GPL-2.0-or-later diff --git a/src/core/device_memory.cpp b/src/core/device_memory.cpp index e36ed42e31..afb590c9a6 100644 --- a/src/core/device_memory.cpp +++ b/src/core/device_memory.cpp @@ -1,3 +1,6 @@ +// SPDX-FileCopyrightText: Copyright 2026 Eden Emulator Project +// SPDX-License-Identifier: GPL-3.0-or-later + // SPDX-FileCopyrightText: Copyright 2020 yuzu Emulator Project // SPDX-License-Identifier: GPL-2.0-or-later From 17463f7b0da6302abcbf2e343734575a6fdf9655 Mon Sep 17 00:00:00 2001 From: CamilleLaVey Date: Tue, 11 Aug 2026 17:37:46 -0400 Subject: [PATCH 07/27] another take --- src/video_core/buffer_cache/buffer_cache.h | 48 +++++ .../buffer_cache/buffer_cache_base.h | 2 + .../renderer_vulkan/vk_buffer_cache.cpp | 202 ++++++++++++++---- .../renderer_vulkan/vk_buffer_cache.h | 16 ++ 4 files changed, 230 insertions(+), 38 deletions(-) diff --git a/src/video_core/buffer_cache/buffer_cache.h b/src/video_core/buffer_cache/buffer_cache.h index 31a229f2cc..46ed87b776 100644 --- a/src/video_core/buffer_cache/buffer_cache.h +++ b/src/video_core/buffer_cache/buffer_cache.h @@ -721,6 +721,7 @@ void BufferCache

::CommitAsyncFlushesHigh() { runtime.CopyToUnifiedMemory(queued.window, slot_buffers[queued.buffer_id], group_span); } if (!unified_copy_queue.empty()) { + runtime.FlushUnifiedMemoryCopies(); runtime.UnifiedMemoryHostBarrier(); } } @@ -1961,6 +1962,7 @@ bool BufferCache

::TryUnifiedDownloadMemory([[maybe_unused]] Buffer& buffer, const std::span group_span(groups[i].data(), groups[i].size()); runtime.CopyToUnifiedMemory(window_ids[i], buffer, group_span); } + runtime.FlushUnifiedMemoryCopies(); runtime.UnifiedMemoryHostBarrier(); runtime.Finish(); return true; @@ -1969,11 +1971,57 @@ bool BufferCache

::TryUnifiedDownloadMemory([[maybe_unused]] Buffer& buffer, } } +template +bool BufferCache

::TryUnifiedUploadMemory([[maybe_unused]] Buffer& buffer, + [[maybe_unused]] std::span copies) { + if constexpr (USE_UNIFIED_MEMORY) { + boost::container::small_vector window_ids; + UnifiedWindowGroups groups; + for (const BufferCopy& copy : copies) { + if (!ResolveUnifiedWindows(buffer.CpuAddr() + copy.dst_offset, copy.dst_offset, + copy.size, window_ids, groups)) { + return false; + } + } + for (const BufferCopy& copy : copies) { + buffer.MarkUsage(copy.dst_offset, copy.size); + } + runtime.PreCopyBarrier(); + boost::container::small_vector window_source_copies; + for (size_t i = 0; i < window_ids.size(); ++i) { + window_source_copies.clear(); + window_source_copies.reserve(groups[i].size()); + for (const BufferCopy& copy : groups[i]) { + window_source_copies.push_back(BufferCopy{ + .src_offset = copy.dst_offset, + .dst_offset = copy.src_offset, + .size = copy.size, + }); + } + const std::span group_span(window_source_copies.data(), + window_source_copies.size()); + runtime.CopyFromUnifiedMemory(window_ids[i], buffer, group_span); + } + runtime.FlushUnifiedMemoryCopies(); + runtime.PostCopyBarrier(); + return true; + } else { + return false; + } +} + template void BufferCache

::MappedUploadMemory([[maybe_unused]] Buffer& buffer, [[maybe_unused]] u64 total_size_bytes, [[maybe_unused]] std::span copies) { if constexpr (USE_MEMORY_MAPS) { + if constexpr (USE_UNIFIED_MEMORY) { + if (runtime.HasUnifiedMemory() && + !Settings::values.enable_gpu_buffer_readback.GetValue() && + TryUnifiedUploadMemory(buffer, copies)) { + return; + } + } auto upload_staging = runtime.UploadStagingBuffer(total_size_bytes); const std::span staging_pointer = upload_staging.mapped_span; for (BufferCopy& copy : copies) { diff --git a/src/video_core/buffer_cache/buffer_cache_base.h b/src/video_core/buffer_cache/buffer_cache_base.h index b7ed422d19..c1622baba1 100644 --- a/src/video_core/buffer_cache/buffer_cache_base.h +++ b/src/video_core/buffer_cache/buffer_cache_base.h @@ -465,6 +465,8 @@ private: bool TryUnifiedDownloadMemory(Buffer& buffer, std::span copies); + bool TryUnifiedUploadMemory(Buffer& buffer, std::span copies); + using UnifiedWindowGroups = boost::container::small_vector, 4>; diff --git a/src/video_core/renderer_vulkan/vk_buffer_cache.cpp b/src/video_core/renderer_vulkan/vk_buffer_cache.cpp index 375fca6856..cdadce83cb 100644 --- a/src/video_core/renderer_vulkan/vk_buffer_cache.cpp +++ b/src/video_core/renderer_vulkan/vk_buffer_cache.cpp @@ -8,6 +8,7 @@ #include #include #include +#include #include #include "video_core/buffer_cache/buffer_cache_base.h" @@ -32,6 +33,32 @@ VkBufferCopy MakeBufferCopy(const VideoCommon::BufferCopy& copy) { }; } +constexpr size_t MAX_WINDOW_BARRIER_RANGES = 8; + +using WindowRange = std::pair; +using WindowRanges = boost::container::small_vector; + +void CoalesceWindowRanges(WindowRanges& ranges) { + if (ranges.size() < 2) { + return; + } + std::sort(ranges.begin(), ranges.end()); + size_t merged = 0; + for (size_t index = 1; index < ranges.size(); ++index) { + if (ranges[index].first <= ranges[merged].second) { + ranges[merged].second = (std::max)(ranges[merged].second, ranges[index].second); + } else { + ranges[++merged] = ranges[index]; + } + } + ranges.resize(merged + 1); + if (ranges.size() > MAX_WINDOW_BARRIER_RANGES) { + const WindowRange bounding{ranges.front().first, ranges.back().second}; + ranges.clear(); + ranges.push_back(bounding); + } +} + VkIndexType IndexTypeFromNumElements(const Device& device, u32 num_elements) { if (num_elements <= 0xff && device.IsExtIndexTypeUint8Supported()) { return VK_INDEX_TYPE_UINT8_EXT; @@ -385,66 +412,164 @@ void BufferCacheRuntime::TryEnableUnifiedMemory(void* base, size_t size, } } +void BufferCacheRuntime::QueueUnifiedCopy(size_t window_index, VkBuffer buffer, + std::span copies, + bool reads_window) { + if (!unified_memory || buffer == VK_NULL_HANDLE || copies.empty() || + window_index >= unified_memory->GetWindowCount() || + unified_memory->GetWindowBuffer(window_index) == VK_NULL_HANDLE) { + return; + } + PendingUnifiedCopy& pending = pending_unified_copies.emplace_back(); + pending.window = window_index; + pending.buffer = buffer; + pending.reads_window = reads_window; + pending.copies.resize(copies.size()); + std::ranges::transform(copies, pending.copies.begin(), MakeBufferCopy); +} + void BufferCacheRuntime::CopyToUnifiedMemory( size_t window_index, VkBuffer src_buffer, std::span copies) { - if (!unified_memory || src_buffer == VK_NULL_HANDLE || copies.empty() || - window_index >= unified_memory->GetWindowCount()) { - return; - } - const VkBuffer dst_buffer = unified_memory->GetWindowBuffer(window_index); - if (dst_buffer == VK_NULL_HANDLE) { - return; - } - VkDeviceSize covered_begin = std::numeric_limits::max(); - VkDeviceSize covered_end = 0; - for (const VideoCommon::BufferCopy& copy : copies) { - covered_begin = (std::min)(covered_begin, static_cast(copy.dst_offset)); - covered_end = (std::max)(covered_end, - static_cast(copy.dst_offset + copy.size)); - } + QueueUnifiedCopy(window_index, src_buffer, copies, false); +} - boost::container::small_vector vk_copies(copies.size()); - std::ranges::transform(copies, vk_copies.begin(), MakeBufferCopy); +void BufferCacheRuntime::CopyFromUnifiedMemory( + size_t window_index, VkBuffer dst_buffer, + std::span copies) { + QueueUnifiedCopy(window_index, dst_buffer, copies, true); +} + +void BufferCacheRuntime::FlushUnifiedMemoryCopies() { + if (pending_unified_copies.empty()) { + return; + } + struct UnifiedCopyCommand { + VkBuffer buffer; + bool reads_window; + boost::container::small_vector copies; + }; + static constexpr VkMemoryBarrier WINDOW_TRANSFER_BARRIER{ + .sType = VK_STRUCTURE_TYPE_MEMORY_BARRIER, + .pNext = nullptr, + .srcAccessMask = VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_TRANSFER_WRITE_BIT, + .dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_TRANSFER_WRITE_BIT, + }; + + std::stable_sort(pending_unified_copies.begin(), pending_unified_copies.end(), + [](const PendingUnifiedCopy& lhs, const PendingUnifiedCopy& rhs) { + if (lhs.window != rhs.window) { + return lhs.window < rhs.window; + } + return lhs.reads_window && !rhs.reads_window; + }); const bool foreign = unified_memory->NeedsForeignOwnershipTransfer(); const u32 queue_family = device.GetGraphicsFamily(); - scheduler.RequestOutsideRenderPassOperationContext(); - scheduler.Record([src_buffer, dst_buffer, vk_copies, foreign, queue_family, covered_begin, - covered_end](vk::CommandBuffer cmdbuf) { + size_t group_begin = 0; + while (group_begin < pending_unified_copies.size()) { + const size_t window = pending_unified_copies[group_begin].window; + size_t group_end = group_begin; + while (group_end < pending_unified_copies.size() && + pending_unified_copies[group_end].window == window) { + ++group_end; + } + const VkBuffer window_buffer = unified_memory->GetWindowBuffer(window); + + WindowRanges ranges; + VkAccessFlags window_access = 0; + size_t reads_in_group = 0; + for (size_t index = group_begin; index < group_end; ++index) { + const PendingUnifiedCopy& pending = pending_unified_copies[index]; + if (pending.reads_window) { + window_access |= VK_ACCESS_TRANSFER_READ_BIT; + ++reads_in_group; + } else { + window_access |= VK_ACCESS_TRANSFER_WRITE_BIT; + } + for (const VkBufferCopy& copy : pending.copies) { + const VkDeviceSize offset = + pending.reads_window ? copy.srcOffset : copy.dstOffset; + ranges.emplace_back(offset, offset + copy.size); + } + } + CoalesceWindowRanges(ranges); + + boost::container::small_vector acquire; + boost::container::small_vector release; if (foreign) { - const VkBufferMemoryBarrier acquire{ + for (const WindowRange& range : ranges) { + acquire.push_back(VkBufferMemoryBarrier{ .sType = VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER, .pNext = nullptr, .srcAccessMask = 0, - .dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT, + .dstAccessMask = window_access, .srcQueueFamilyIndex = VK_QUEUE_FAMILY_FOREIGN_EXT, .dstQueueFamilyIndex = queue_family, - .buffer = dst_buffer, - .offset = covered_begin, - .size = covered_end - covered_begin, - }; - cmdbuf.PipelineBarrier(VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, - VK_PIPELINE_STAGE_TRANSFER_BIT, 0, acquire); - } - cmdbuf.CopyBuffer(src_buffer, dst_buffer, VideoCommon::FixSmallVectorADL(vk_copies)); - if (foreign) { - const VkBufferMemoryBarrier release{ + .buffer = window_buffer, + .offset = range.first, + .size = range.second - range.first, + }); + release.push_back(VkBufferMemoryBarrier{ .sType = VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER, .pNext = nullptr, - .srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT, + .srcAccessMask = window_access, .dstAccessMask = 0, .srcQueueFamilyIndex = queue_family, .dstQueueFamilyIndex = VK_QUEUE_FAMILY_FOREIGN_EXT, - .buffer = dst_buffer, - .offset = covered_begin, - .size = covered_end - covered_begin, - }; + .buffer = window_buffer, + .offset = range.first, + .size = range.second - range.first, + }); + } + } + + boost::container::small_vector commands; + commands.reserve(group_end - group_begin); + for (size_t index = group_begin; index < group_end; ++index) { + PendingUnifiedCopy& pending = pending_unified_copies[index]; + commands.push_back(UnifiedCopyCommand{pending.buffer, pending.reads_window, + std::move(pending.copies)}); + } + const size_t barrier_before_writes = (reads_in_group > 0 && reads_in_group < commands.size()) + ? reads_in_group + : commands.size(); + + scheduler.RequestOutsideRenderPassOperationContext(); + scheduler.Record([window_buffer, barrier_before_writes, acquire = std::move(acquire), + release = std::move(release), + commands = std::move(commands)](vk::CommandBuffer cmdbuf) { + if (!acquire.empty()) { + cmdbuf.PipelineBarrier(VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, + VK_PIPELINE_STAGE_TRANSFER_BIT, 0, {}, + VideoCommon::FixSmallVectorADL(acquire), {}); + } + for (size_t index = 0; index < commands.size(); ++index) { + if (index == barrier_before_writes) { cmdbuf.PipelineBarrier(VK_PIPELINE_STAGE_TRANSFER_BIT, - VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, 0, release); + VK_PIPELINE_STAGE_TRANSFER_BIT, 0, + WINDOW_TRANSFER_BARRIER); + } + const UnifiedCopyCommand& command = commands[index]; + if (command.reads_window) { + cmdbuf.CopyBuffer(window_buffer, command.buffer, + VideoCommon::FixSmallVectorADL(command.copies)); + } else { + cmdbuf.CopyBuffer(command.buffer, window_buffer, + VideoCommon::FixSmallVectorADL(command.copies)); + } + } + if (!release.empty()) { + cmdbuf.PipelineBarrier(VK_PIPELINE_STAGE_TRANSFER_BIT, + VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, 0, {}, + VideoCommon::FixSmallVectorADL(release), {}); } }); + + group_begin = group_end; + } + pending_unified_copies.clear(); } void BufferCacheRuntime::UnifiedMemoryHostBarrier() { @@ -498,6 +623,7 @@ u32 BufferCacheRuntime::GetStorageBufferAlignment() const { } void BufferCacheRuntime::TickFrame(Common::SlotVector& slot_buffers) noexcept { + FlushUnifiedMemoryCopies(); for (auto it = slot_buffers.begin(); it != slot_buffers.end(); it++) { if (scheduler.IsFree(it->LastUsageTick())) { it->ResetUsageTracking(); diff --git a/src/video_core/renderer_vulkan/vk_buffer_cache.h b/src/video_core/renderer_vulkan/vk_buffer_cache.h index 583b990060..d3fd89719b 100644 --- a/src/video_core/renderer_vulkan/vk_buffer_cache.h +++ b/src/video_core/renderer_vulkan/vk_buffer_cache.h @@ -135,6 +135,11 @@ public: void CopyToUnifiedMemory(size_t window_index, VkBuffer src_buffer, std::span copies); + void CopyFromUnifiedMemory(size_t window_index, VkBuffer dst_buffer, + std::span copies); + + void FlushUnifiedMemoryCopies(); + void UnifiedMemoryHostBarrier(); u64 CurrentTick(); @@ -260,6 +265,16 @@ public: } private: + struct PendingUnifiedCopy { + size_t window; + VkBuffer buffer; + bool reads_window; + boost::container::small_vector copies; + }; + + void QueueUnifiedCopy(size_t window_index, VkBuffer buffer, + std::span copies, bool reads_window); + void BindBuffer(const Buffer& buffer, u32 offset, u32 size) { const VkBuffer handle = buffer.Handle(); if (handle == VK_NULL_HANDLE) { @@ -285,6 +300,7 @@ private: vk::Buffer null_buffer; std::unique_ptr unified_memory; + boost::container::small_vector pending_unified_copies; std::unique_ptr uint8_pass; QuadIndexedPass quad_index_pass; From d93039fb426569d6bd18992dbcd8fde5accc82e5 Mon Sep 17 00:00:00 2001 From: CamilleLaVey Date: Tue, 11 Aug 2026 18:50:22 -0400 Subject: [PATCH 08/27] Step back + keeping fixes from unified download + shared mem refactor --- .../backend/spirv/emit_spirv_atomic.cpp | 4 +- .../spirv/emit_spirv_shared_memory.cpp | 12 +++ .../backend/spirv/spirv_emit_context.cpp | 21 +++++- .../backend/spirv/spirv_emit_context.h | 2 + src/shader_recompiler/profile.h | 3 + src/video_core/buffer_cache/buffer_cache.h | 46 ------------ .../buffer_cache/buffer_cache_base.h | 2 - .../renderer_opengl/gl_shader_cache.cpp | 1 + .../renderer_vulkan/vk_buffer_cache.cpp | 74 +++---------------- .../renderer_vulkan/vk_buffer_cache.h | 7 -- .../renderer_vulkan/vk_pipeline_cache.cpp | 14 +--- 11 files changed, 53 insertions(+), 133 deletions(-) diff --git a/src/shader_recompiler/backend/spirv/emit_spirv_atomic.cpp b/src/shader_recompiler/backend/spirv/emit_spirv_atomic.cpp index d1c08c1131..d42e3a24e5 100644 --- a/src/shader_recompiler/backend/spirv/emit_spirv_atomic.cpp +++ b/src/shader_recompiler/backend/spirv/emit_spirv_atomic.cpp @@ -13,6 +13,7 @@ namespace Shader::Backend::SPIRV { namespace { Id SharedPointer(EmitContext& ctx, Id offset, u32 index_offset = 0) { + offset = ctx.BoundSharedOffset(offset, 4 + index_offset * 4); const Id shift_id{ctx.Const(2U)}; Id index{ctx.OpShiftRightArithmetic(ctx.U32[1], offset, shift_id)}; if (index_offset > 0) { @@ -160,7 +161,8 @@ Id EmitSharedAtomicExchange32(EmitContext& ctx, Id offset, Id value) { Id EmitSharedAtomicExchange64(EmitContext& ctx, Id offset, Id value) { if (ctx.profile.support_shared_int64_atomics && ctx.uses_explicit_workgroup_layout) { const Id shift_id{ctx.Const(3U)}; - const Id index{ctx.OpShiftRightArithmetic(ctx.U32[1], offset, shift_id)}; + const Id index{ + ctx.OpShiftRightArithmetic(ctx.U32[1], ctx.BoundSharedOffset(offset, 8), shift_id)}; const Id pointer{ ctx.OpAccessChain(ctx.shared_u64, ctx.shared_memory_u64, ctx.u32_zero_value, index)}; const auto [scope, semantics]{AtomicArgs(ctx)}; diff --git a/src/shader_recompiler/backend/spirv/emit_spirv_shared_memory.cpp b/src/shader_recompiler/backend/spirv/emit_spirv_shared_memory.cpp index dc398aa296..0af351948e 100644 --- a/src/shader_recompiler/backend/spirv/emit_spirv_shared_memory.cpp +++ b/src/shader_recompiler/backend/spirv/emit_spirv_shared_memory.cpp @@ -31,6 +31,7 @@ std::pair ExtractArgs(EmitContext& ctx, Id offset, u32 mask, u32 count) } // Anonymous namespace Id EmitLoadSharedU8(EmitContext& ctx, Id offset) { + offset = ctx.BoundSharedOffset(offset, 1); if (ctx.uses_explicit_workgroup_layout) { const Id pointer{ ctx.OpAccessChain(ctx.shared_u8, ctx.shared_memory_u8, ctx.u32_zero_value, offset)}; @@ -42,6 +43,7 @@ Id EmitLoadSharedU8(EmitContext& ctx, Id offset) { } Id EmitLoadSharedS8(EmitContext& ctx, Id offset) { + offset = ctx.BoundSharedOffset(offset, 1); if (ctx.uses_explicit_workgroup_layout) { const Id pointer{ ctx.OpAccessChain(ctx.shared_u8, ctx.shared_memory_u8, ctx.u32_zero_value, offset)}; @@ -53,6 +55,7 @@ Id EmitLoadSharedS8(EmitContext& ctx, Id offset) { } Id EmitLoadSharedU16(EmitContext& ctx, Id offset) { + offset = ctx.BoundSharedOffset(offset, 2); if (ctx.uses_explicit_workgroup_layout) { const Id pointer{Pointer(ctx, ctx.shared_u16, ctx.shared_memory_u16, offset, 1)}; return ctx.OpUConvert(ctx.U32[1], ctx.OpLoad(ctx.U16, pointer)); @@ -63,6 +66,7 @@ Id EmitLoadSharedU16(EmitContext& ctx, Id offset) { } Id EmitLoadSharedS16(EmitContext& ctx, Id offset) { + offset = ctx.BoundSharedOffset(offset, 2); if (ctx.uses_explicit_workgroup_layout) { const Id pointer{Pointer(ctx, ctx.shared_u16, ctx.shared_memory_u16, offset, 1)}; return ctx.OpSConvert(ctx.U32[1], ctx.OpLoad(ctx.U16, pointer)); @@ -73,6 +77,7 @@ Id EmitLoadSharedS16(EmitContext& ctx, Id offset) { } Id EmitLoadSharedU32(EmitContext& ctx, Id offset) { + offset = ctx.BoundSharedOffset(offset, 4); if (ctx.uses_explicit_workgroup_layout) { const Id pointer{Pointer(ctx, ctx.shared_u32, ctx.shared_memory_u32, offset, 2)}; return ctx.OpLoad(ctx.U32[1], pointer); @@ -82,6 +87,7 @@ Id EmitLoadSharedU32(EmitContext& ctx, Id offset) { } Id EmitLoadSharedU64(EmitContext& ctx, Id offset) { + offset = ctx.BoundSharedOffset(offset, 8); if (ctx.uses_explicit_workgroup_layout) { const Id pointer{Pointer(ctx, ctx.shared_u32x2, ctx.shared_memory_u32x2, offset, 3)}; return ctx.OpLoad(ctx.U32[2], pointer); @@ -97,6 +103,7 @@ Id EmitLoadSharedU64(EmitContext& ctx, Id offset) { } Id EmitLoadSharedU128(EmitContext& ctx, Id offset) { + offset = ctx.BoundSharedOffset(offset, 16); if (ctx.uses_explicit_workgroup_layout) { const Id pointer{Pointer(ctx, ctx.shared_u32x4, ctx.shared_memory_u32x4, offset, 4)}; return ctx.OpLoad(ctx.U32[4], pointer); @@ -113,6 +120,7 @@ Id EmitLoadSharedU128(EmitContext& ctx, Id offset) { } void EmitWriteSharedU8(EmitContext& ctx, Id offset, Id value) { + offset = ctx.BoundSharedOffset(offset, 1); if (ctx.uses_explicit_workgroup_layout) { const Id pointer{ ctx.OpAccessChain(ctx.shared_u8, ctx.shared_memory_u8, ctx.u32_zero_value, offset)}; @@ -123,6 +131,7 @@ void EmitWriteSharedU8(EmitContext& ctx, Id offset, Id value) { } void EmitWriteSharedU16(EmitContext& ctx, Id offset, Id value) { + offset = ctx.BoundSharedOffset(offset, 2); if (ctx.uses_explicit_workgroup_layout) { const Id pointer{Pointer(ctx, ctx.shared_u16, ctx.shared_memory_u16, offset, 1)}; ctx.OpStore(pointer, ctx.OpUConvert(ctx.U16, value)); @@ -132,6 +141,7 @@ void EmitWriteSharedU16(EmitContext& ctx, Id offset, Id value) { } void EmitWriteSharedU32(EmitContext& ctx, Id offset, Id value) { + offset = ctx.BoundSharedOffset(offset, 4); Id pointer{}; if (ctx.uses_explicit_workgroup_layout) { pointer = Pointer(ctx, ctx.shared_u32, ctx.shared_memory_u32, offset, 2); @@ -144,6 +154,7 @@ void EmitWriteSharedU32(EmitContext& ctx, Id offset, Id value) { } void EmitWriteSharedU64(EmitContext& ctx, Id offset, Id value) { + offset = ctx.BoundSharedOffset(offset, 8); if (ctx.uses_explicit_workgroup_layout) { const Id pointer{Pointer(ctx, ctx.shared_u32x2, ctx.shared_memory_u32x2, offset, 3)}; ctx.OpStore(pointer, value); @@ -159,6 +170,7 @@ void EmitWriteSharedU64(EmitContext& ctx, Id offset, Id value) { } void EmitWriteSharedU128(EmitContext& ctx, Id offset, Id value) { + offset = ctx.BoundSharedOffset(offset, 16); if (ctx.uses_explicit_workgroup_layout) { const Id pointer{Pointer(ctx, ctx.shared_u32x4, ctx.shared_memory_u32x4, offset, 4)}; ctx.OpStore(pointer, value); diff --git a/src/shader_recompiler/backend/spirv/spirv_emit_context.cpp b/src/shader_recompiler/backend/spirv/spirv_emit_context.cpp index b562e82983..94b878ed51 100644 --- a/src/shader_recompiler/backend/spirv/spirv_emit_context.cpp +++ b/src/shader_recompiler/backend/spirv/spirv_emit_context.cpp @@ -600,6 +600,16 @@ void EmitContext::DefineLocalMemory(const IR::Program& program) { } } +Id EmitContext::BoundSharedOffset(Id offset, u32 access_bytes) { + if (shared_memory_declared_bytes == 0) { + return offset; + } + const u32 last_valid{shared_memory_declared_bytes > access_bytes + ? shared_memory_declared_bytes - access_bytes + : 0U}; + return OpUMin(U32[1], offset, Const(last_valid)); +} + void EmitContext::DefineSharedMemory(const IR::Program& program) { uses_explicit_workgroup_layout = profile.support_explicit_workgroup_layout && @@ -608,8 +618,15 @@ void EmitContext::DefineSharedMemory(const IR::Program& program) { if (program.shared_memory_size == 0) { return; } + const u32 device_limit{profile.max_shared_memory_size}; + const u32 shared_memory_size{device_limit != 0 && program.shared_memory_size > device_limit + ? device_limit + : program.shared_memory_size}; + if (shared_memory_size != program.shared_memory_size) { + shared_memory_declared_bytes = shared_memory_size; + } const auto make{[&](Id element_type, u32 element_size) { - const u32 num_elements{Common::DivCeil(program.shared_memory_size, element_size)}; + const u32 num_elements{Common::DivCeil(shared_memory_size, element_size)}; const Id array_type{TypeArray(element_type, Const(num_elements))}; Decorate(array_type, spv::Decoration::ArrayStride, element_size); @@ -644,7 +661,7 @@ void EmitContext::DefineSharedMemory(const IR::Program& program) { std::tie(shared_memory_u32x4, shared_u32x4, std::ignore) = make(U32[4], 16); return; } - const u32 num_elements{Common::DivCeil(program.shared_memory_size, 4U)}; + const u32 num_elements{Common::DivCeil(shared_memory_size, 4U)}; const Id type{TypeArray(U32[1], Const(num_elements))}; shared_memory_u32_type = TypePointer(spv::StorageClass::Workgroup, type); diff --git a/src/shader_recompiler/backend/spirv/spirv_emit_context.h b/src/shader_recompiler/backend/spirv/spirv_emit_context.h index 7edc104708..e186fce4d1 100644 --- a/src/shader_recompiler/backend/spirv/spirv_emit_context.h +++ b/src/shader_recompiler/backend/spirv/spirv_emit_context.h @@ -312,6 +312,8 @@ public: Id local_memory{}; bool uses_explicit_workgroup_layout{}; + u32 shared_memory_declared_bytes{}; + [[nodiscard]] Id BoundSharedOffset(Id offset, u32 access_bytes); Id shared_memory_u8{}; Id shared_memory_u16{}; Id shared_memory_u32{}; diff --git a/src/shader_recompiler/profile.h b/src/shader_recompiler/profile.h index d2ac480ab8..9dedf556d6 100644 --- a/src/shader_recompiler/profile.h +++ b/src/shader_recompiler/profile.h @@ -105,6 +105,9 @@ struct Profile { u32 gl_max_compute_smem_size{}; + /// Largest workgroup shared memory allocation the device accepts, 0 when unconstrained + u32 max_shared_memory_size{}; + /// Maxwell and earlier nVidia architectures have broken robust support bool has_broken_robust{}; diff --git a/src/video_core/buffer_cache/buffer_cache.h b/src/video_core/buffer_cache/buffer_cache.h index 46ed87b776..63efeebdcf 100644 --- a/src/video_core/buffer_cache/buffer_cache.h +++ b/src/video_core/buffer_cache/buffer_cache.h @@ -1971,57 +1971,11 @@ bool BufferCache

::TryUnifiedDownloadMemory([[maybe_unused]] Buffer& buffer, } } -template -bool BufferCache

::TryUnifiedUploadMemory([[maybe_unused]] Buffer& buffer, - [[maybe_unused]] std::span copies) { - if constexpr (USE_UNIFIED_MEMORY) { - boost::container::small_vector window_ids; - UnifiedWindowGroups groups; - for (const BufferCopy& copy : copies) { - if (!ResolveUnifiedWindows(buffer.CpuAddr() + copy.dst_offset, copy.dst_offset, - copy.size, window_ids, groups)) { - return false; - } - } - for (const BufferCopy& copy : copies) { - buffer.MarkUsage(copy.dst_offset, copy.size); - } - runtime.PreCopyBarrier(); - boost::container::small_vector window_source_copies; - for (size_t i = 0; i < window_ids.size(); ++i) { - window_source_copies.clear(); - window_source_copies.reserve(groups[i].size()); - for (const BufferCopy& copy : groups[i]) { - window_source_copies.push_back(BufferCopy{ - .src_offset = copy.dst_offset, - .dst_offset = copy.src_offset, - .size = copy.size, - }); - } - const std::span group_span(window_source_copies.data(), - window_source_copies.size()); - runtime.CopyFromUnifiedMemory(window_ids[i], buffer, group_span); - } - runtime.FlushUnifiedMemoryCopies(); - runtime.PostCopyBarrier(); - return true; - } else { - return false; - } -} - template void BufferCache

::MappedUploadMemory([[maybe_unused]] Buffer& buffer, [[maybe_unused]] u64 total_size_bytes, [[maybe_unused]] std::span copies) { if constexpr (USE_MEMORY_MAPS) { - if constexpr (USE_UNIFIED_MEMORY) { - if (runtime.HasUnifiedMemory() && - !Settings::values.enable_gpu_buffer_readback.GetValue() && - TryUnifiedUploadMemory(buffer, copies)) { - return; - } - } auto upload_staging = runtime.UploadStagingBuffer(total_size_bytes); const std::span staging_pointer = upload_staging.mapped_span; for (BufferCopy& copy : copies) { diff --git a/src/video_core/buffer_cache/buffer_cache_base.h b/src/video_core/buffer_cache/buffer_cache_base.h index c1622baba1..b7ed422d19 100644 --- a/src/video_core/buffer_cache/buffer_cache_base.h +++ b/src/video_core/buffer_cache/buffer_cache_base.h @@ -465,8 +465,6 @@ private: bool TryUnifiedDownloadMemory(Buffer& buffer, std::span copies); - bool TryUnifiedUploadMemory(Buffer& buffer, std::span copies); - using UnifiedWindowGroups = boost::container::small_vector, 4>; diff --git a/src/video_core/renderer_opengl/gl_shader_cache.cpp b/src/video_core/renderer_opengl/gl_shader_cache.cpp index df69eb97f5..2fd158fd77 100644 --- a/src/video_core/renderer_opengl/gl_shader_cache.cpp +++ b/src/video_core/renderer_opengl/gl_shader_cache.cpp @@ -238,6 +238,7 @@ ShaderCache::ShaderCache(Tegra::MaxwellDeviceMemoryManager& device_memory_, .has_gl_bool_ref_bug = device.HasBoolRefBug(), .ignore_nan_fp_comparisons = true, .gl_max_compute_smem_size = device.GetMaxComputeSharedMemorySize(), + .max_shared_memory_size = device.GetMaxComputeSharedMemorySize(), .min_ssbo_alignment = device.GetShaderStorageBufferAlignment(), // Use the host limit, but never more than the guest can produce. Maxwell exposes 8 clip // distances and the SPIR-V output array is sized for at most 8, so clamping here keeps a diff --git a/src/video_core/renderer_vulkan/vk_buffer_cache.cpp b/src/video_core/renderer_vulkan/vk_buffer_cache.cpp index cdadce83cb..b27f43c86e 100644 --- a/src/video_core/renderer_vulkan/vk_buffer_cache.cpp +++ b/src/video_core/renderer_vulkan/vk_buffer_cache.cpp @@ -412,56 +412,33 @@ void BufferCacheRuntime::TryEnableUnifiedMemory(void* base, size_t size, } } -void BufferCacheRuntime::QueueUnifiedCopy(size_t window_index, VkBuffer buffer, - std::span copies, - bool reads_window) { - if (!unified_memory || buffer == VK_NULL_HANDLE || copies.empty() || +void BufferCacheRuntime::CopyToUnifiedMemory( + size_t window_index, VkBuffer src_buffer, + std::span copies) { + if (!unified_memory || src_buffer == VK_NULL_HANDLE || copies.empty() || window_index >= unified_memory->GetWindowCount() || unified_memory->GetWindowBuffer(window_index) == VK_NULL_HANDLE) { return; } PendingUnifiedCopy& pending = pending_unified_copies.emplace_back(); pending.window = window_index; - pending.buffer = buffer; - pending.reads_window = reads_window; + pending.buffer = src_buffer; pending.copies.resize(copies.size()); std::ranges::transform(copies, pending.copies.begin(), MakeBufferCopy); } -void BufferCacheRuntime::CopyToUnifiedMemory( - size_t window_index, VkBuffer src_buffer, - std::span copies) { - QueueUnifiedCopy(window_index, src_buffer, copies, false); -} - -void BufferCacheRuntime::CopyFromUnifiedMemory( - size_t window_index, VkBuffer dst_buffer, - std::span copies) { - QueueUnifiedCopy(window_index, dst_buffer, copies, true); -} - void BufferCacheRuntime::FlushUnifiedMemoryCopies() { if (pending_unified_copies.empty()) { return; } struct UnifiedCopyCommand { VkBuffer buffer; - bool reads_window; boost::container::small_vector copies; }; - static constexpr VkMemoryBarrier WINDOW_TRANSFER_BARRIER{ - .sType = VK_STRUCTURE_TYPE_MEMORY_BARRIER, - .pNext = nullptr, - .srcAccessMask = VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_TRANSFER_WRITE_BIT, - .dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_TRANSFER_WRITE_BIT, - }; std::stable_sort(pending_unified_copies.begin(), pending_unified_copies.end(), [](const PendingUnifiedCopy& lhs, const PendingUnifiedCopy& rhs) { - if (lhs.window != rhs.window) { return lhs.window < rhs.window; - } - return lhs.reads_window && !rhs.reads_window; }); const bool foreign = unified_memory->NeedsForeignOwnershipTransfer(); @@ -478,20 +455,9 @@ void BufferCacheRuntime::FlushUnifiedMemoryCopies() { const VkBuffer window_buffer = unified_memory->GetWindowBuffer(window); WindowRanges ranges; - VkAccessFlags window_access = 0; - size_t reads_in_group = 0; for (size_t index = group_begin; index < group_end; ++index) { - const PendingUnifiedCopy& pending = pending_unified_copies[index]; - if (pending.reads_window) { - window_access |= VK_ACCESS_TRANSFER_READ_BIT; - ++reads_in_group; - } else { - window_access |= VK_ACCESS_TRANSFER_WRITE_BIT; - } - for (const VkBufferCopy& copy : pending.copies) { - const VkDeviceSize offset = - pending.reads_window ? copy.srcOffset : copy.dstOffset; - ranges.emplace_back(offset, offset + copy.size); + for (const VkBufferCopy& copy : pending_unified_copies[index].copies) { + ranges.emplace_back(copy.dstOffset, copy.dstOffset + copy.size); } } CoalesceWindowRanges(ranges); @@ -504,7 +470,7 @@ void BufferCacheRuntime::FlushUnifiedMemoryCopies() { .sType = VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER, .pNext = nullptr, .srcAccessMask = 0, - .dstAccessMask = window_access, + .dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT, .srcQueueFamilyIndex = VK_QUEUE_FAMILY_FOREIGN_EXT, .dstQueueFamilyIndex = queue_family, .buffer = window_buffer, @@ -514,7 +480,7 @@ void BufferCacheRuntime::FlushUnifiedMemoryCopies() { release.push_back(VkBufferMemoryBarrier{ .sType = VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER, .pNext = nullptr, - .srcAccessMask = window_access, + .srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT, .dstAccessMask = 0, .srcQueueFamilyIndex = queue_family, .dstQueueFamilyIndex = VK_QUEUE_FAMILY_FOREIGN_EXT, @@ -529,37 +495,21 @@ void BufferCacheRuntime::FlushUnifiedMemoryCopies() { commands.reserve(group_end - group_begin); for (size_t index = group_begin; index < group_end; ++index) { PendingUnifiedCopy& pending = pending_unified_copies[index]; - commands.push_back(UnifiedCopyCommand{pending.buffer, pending.reads_window, - std::move(pending.copies)}); + commands.push_back(UnifiedCopyCommand{pending.buffer, std::move(pending.copies)}); } - const size_t barrier_before_writes = (reads_in_group > 0 && reads_in_group < commands.size()) - ? reads_in_group - : commands.size(); scheduler.RequestOutsideRenderPassOperationContext(); - scheduler.Record([window_buffer, barrier_before_writes, acquire = std::move(acquire), - release = std::move(release), + scheduler.Record([window_buffer, acquire = std::move(acquire), release = std::move(release), commands = std::move(commands)](vk::CommandBuffer cmdbuf) { if (!acquire.empty()) { cmdbuf.PipelineBarrier(VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, {}, VideoCommon::FixSmallVectorADL(acquire), {}); } - for (size_t index = 0; index < commands.size(); ++index) { - if (index == barrier_before_writes) { - cmdbuf.PipelineBarrier(VK_PIPELINE_STAGE_TRANSFER_BIT, - VK_PIPELINE_STAGE_TRANSFER_BIT, 0, - WINDOW_TRANSFER_BARRIER); - } - const UnifiedCopyCommand& command = commands[index]; - if (command.reads_window) { - cmdbuf.CopyBuffer(window_buffer, command.buffer, - VideoCommon::FixSmallVectorADL(command.copies)); - } else { + for (const UnifiedCopyCommand& command : commands) { cmdbuf.CopyBuffer(command.buffer, window_buffer, VideoCommon::FixSmallVectorADL(command.copies)); } - } if (!release.empty()) { cmdbuf.PipelineBarrier(VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, 0, {}, diff --git a/src/video_core/renderer_vulkan/vk_buffer_cache.h b/src/video_core/renderer_vulkan/vk_buffer_cache.h index d3fd89719b..d49325e51d 100644 --- a/src/video_core/renderer_vulkan/vk_buffer_cache.h +++ b/src/video_core/renderer_vulkan/vk_buffer_cache.h @@ -135,9 +135,6 @@ public: void CopyToUnifiedMemory(size_t window_index, VkBuffer src_buffer, std::span copies); - void CopyFromUnifiedMemory(size_t window_index, VkBuffer dst_buffer, - std::span copies); - void FlushUnifiedMemoryCopies(); void UnifiedMemoryHostBarrier(); @@ -268,13 +265,9 @@ private: struct PendingUnifiedCopy { size_t window; VkBuffer buffer; - bool reads_window; boost::container::small_vector copies; }; - void QueueUnifiedCopy(size_t window_index, VkBuffer buffer, - std::span copies, bool reads_window); - void BindBuffer(const Buffer& buffer, u32 offset, u32 size) { const VkBuffer handle = buffer.Handle(); if (handle == VK_NULL_HANDLE) { diff --git a/src/video_core/renderer_vulkan/vk_pipeline_cache.cpp b/src/video_core/renderer_vulkan/vk_pipeline_cache.cpp index 642b9fa223..68708e3597 100644 --- a/src/video_core/renderer_vulkan/vk_pipeline_cache.cpp +++ b/src/video_core/renderer_vulkan/vk_pipeline_cache.cpp @@ -451,6 +451,7 @@ PipelineCache::PipelineCache(Tegra::MaxwellDeviceMemoryManager& device_memory_, .has_broken_fp32_denorm_flush = driver_id == VK_DRIVER_ID_QUALCOMM_PROPRIETARY, .ignore_nan_fp_comparisons = false, .has_broken_spirv_subgroup_mask_vector_extract_dynamic = false, + .max_shared_memory_size = device.GetMaxComputeSharedMemorySize(), .has_broken_robust = device.IsNvidia() && device.GetNvidiaArch() <= NvidiaArchitecture::Arch_Pascal, .min_ssbo_alignment = device.GetStorageBufferAlignment(), @@ -969,19 +970,6 @@ std::unique_ptr PipelineCache::CreateComputePipeline( } auto program{TranslateProgram(pools.inst, pools.block, env, cfg, host_info)}; - const VkDriverIdKHR driver_id = device.GetDriverID(); - const bool needs_shared_mem_clamp = - driver_id == VK_DRIVER_ID_QUALCOMM_PROPRIETARY || - driver_id == VK_DRIVER_ID_ARM_PROPRIETARY; - const u32 max_shared_memory = device.GetMaxComputeSharedMemorySize(); - if (needs_shared_mem_clamp && program.shared_memory_size > max_shared_memory) { - LOG_WARNING(Render_Vulkan, - "Compute shader {:#016x} requests {}KB shared memory but device max is {}KB - clamping", - key.unique_hash, - program.shared_memory_size / 1024, - max_shared_memory / 1024); - program.shared_memory_size = max_shared_memory; - } const std::vector code{EmitSPIRV(profile, program)}; device.SaveShader(code); vk::ShaderModule spv_module{BuildShader(device, code)}; From 5caa0bd567ad3fa6f7ec31dc72f2c8d38d4e567a Mon Sep 17 00:00:00 2001 From: CamilleLaVey Date: Wed, 26 Aug 2026 03:12:06 -0400 Subject: [PATCH 09/27] Changes on the maps counts again --- src/common/heap_tracker.cpp | 23 ++------------- src/common/host_memory.cpp | 47 ++++++++++++++++++++++--------- src/common/memory_detect.cpp | 54 ++++++++---------------------------- src/common/memory_detect.h | 4 +-- 4 files changed, 49 insertions(+), 79 deletions(-) diff --git a/src/common/heap_tracker.cpp b/src/common/heap_tracker.cpp index 4475ab5f0e..4c71bd06da 100644 --- a/src/common/heap_tracker.cpp +++ b/src/common/heap_tracker.cpp @@ -4,36 +4,17 @@ // SPDX-FileCopyrightText: Copyright 2023 yuzu Emulator Project // SPDX-License-Identifier: GPL-2.0-or-later -#include #include "common/heap_tracker.h" #include "common/logging.h" +#include "common/memory_detect.h" #include "common/assert.h" namespace Common { -namespace { - -s64 GetMaxPermissibleResidentMapCount() { - // Default value. - s64 value = 65530; - - // Try to read how many mappings we can make. - std::ifstream s("/proc/sys/vm/max_map_count"); - s >> value; - - // Print, for debug. - LOG_INFO(HW_Memory, "Current maximum map count: {}", value); - - // Allow 20000 maps for other code and to account for split inaccuracy. - return std::max(value - 20000, 0); -} - -} // namespace - HeapTracker::HeapTracker(Common::HostMemory& buffer) : m_buffer(buffer), m_has_hardware_buffer_backing(!buffer.BackingHardwareBuffers().empty()), - m_max_resident_map_count(GetMaxPermissibleResidentMapCount()) {} + m_max_resident_map_count(static_cast(GetPermissibleMapCount())) {} HeapTracker::~HeapTracker() = default; void HeapTracker::Map(size_t virtual_offset, size_t host_offset, size_t length, diff --git a/src/common/host_memory.cpp b/src/common/host_memory.cpp index a318733cd5..a11c1c149b 100644 --- a/src/common/host_memory.cpp +++ b/src/common/host_memory.cpp @@ -65,7 +65,9 @@ #include "common/settings.h" #ifdef __ANDROID__ +#include #include +#include #include namespace { @@ -88,6 +90,24 @@ PFN_AHardwareBuffer_getNativeHandle ResolveGetNativeHandle() { dlsym(lib, "AHardwareBuffer_getNativeHandle")); } +struct DmaBufSync { + u64 flags; +}; + +constexpr u64 DmaBufSyncRead = 1ULL << 0; +constexpr u64 DmaBufSyncWrite = 1ULL << 1; +constexpr u64 DmaBufSyncStart = 0ULL << 2; +constexpr u64 DmaBufSyncEnd = 1ULL << 2; + +void SyncDmaBufCpuAccess(int fd, u64 phase) { + DmaBufSync sync{.flags = phase | DmaBufSyncRead | DmaBufSyncWrite}; + while (ioctl(fd, _IOW('b', 0, DmaBufSync), &sync) != 0) { + if (errno != EINTR) { + return; + } + } +} + } // namespace #endif @@ -657,7 +677,7 @@ public: } const int probe_fd = handle->data[0]; bool ok = true; - const auto try_map = [&](int prot, off_t offset, const char* what) { + const auto try_map = [&](int prot, off_t offset) { if (!ok) { return; } @@ -668,10 +688,10 @@ public: } munmap(ptr, PageAlignment); }; - try_map(PROT_READ | PROT_WRITE, 0, "shared mappings"); - try_map(PROT_READ | PROT_WRITE, static_cast(PageAlignment), "mappings at an offset"); + try_map(PROT_READ | PROT_WRITE, 0); + try_map(PROT_READ | PROT_WRITE, static_cast(PageAlignment)); #ifdef ARCHITECTURE_arm64 - try_map(PROT_READ | PROT_EXEC, 0, "executable mappings"); + try_map(PROT_READ | PROT_EXEC, 0); #endif AHardwareBuffer_release(buffer); return ok; @@ -683,19 +703,14 @@ public: if (total_physical <= BaselineFootprint) { return 0; } - const u64 max_map_count = Common::GetMaxMapCount(); - constexpr u64 ReservedMaps = 24576; - if (max_map_count == 0 || max_map_count <= ReservedMaps) { + const u64 permissible_maps = Common::GetPermissibleMapCount(); + if (permissible_maps == 0) { return 0; } u64 budget = (total_physical - BaselineFootprint) / 2; - constexpr u64 MapSlotsPerWindow = 4096; - const u64 affordable_windows = (max_map_count - ReservedMaps) / MapSlotsPerWindow; + constexpr u64 MapSlotsPerWindow = 64; + const u64 affordable_windows = permissible_maps / MapSlotsPerWindow; budget = (std::min)(budget, affordable_windows * window_size); - const u64 available = Common::GetAvailablePhysicalMemory(); - if (available != 0) { - budget = (std::min)(budget, available / 2); - } budget = (std::min)(budget, static_cast(backing_size)); budget = Common::AlignDown(budget, window_size); constexpr u64 MinimumBudget = 256ULL << 20; @@ -801,6 +816,9 @@ public: ahb_base = region_base; ahb_bytes = region_size; committed_backing_size.store(region_size, std::memory_order_relaxed); + for (const int window_fd : ahb_fds) { + SyncDmaBufCpuAccess(window_fd, DmaBufSyncStart); + } return true; } @@ -979,6 +997,9 @@ private: } #ifdef __ANDROID__ + for (const int window_fd : ahb_fds) { + SyncDmaBufCpuAccess(window_fd, DmaBufSyncEnd); + } for (AHardwareBuffer* buffer : ahb_windows) { AHardwareBuffer_release(buffer); } diff --git a/src/common/memory_detect.cpp b/src/common/memory_detect.cpp index 457168a6ca..e21e058486 100644 --- a/src/common/memory_detect.cpp +++ b/src/common/memory_detect.cpp @@ -22,7 +22,6 @@ #include #include -#include #include "common/memory_detect.h" @@ -76,55 +75,26 @@ const MemoryInfo& GetMemInfo() { return mem_info; } -u64 GetAvailablePhysicalMemory() { -#ifdef _WIN32 - MEMORYSTATUSEX memorystatus; - memorystatus.dwLength = sizeof(memorystatus); - if (GlobalMemoryStatusEx(&memorystatus)) { - return memorystatus.ullAvailPhys; - } - return 0; -#elif defined(__linux__) - if (std::FILE* const file = std::fopen("/proc/meminfo", "re")) { - char line[256]; - u64 available = 0; - while (std::fgets(line, sizeof(line), file) != nullptr) { - if (std::strncmp(line, "MemAvailable:", 13) == 0) { - available = std::strtoull(line + 13, nullptr, 10) * 1024ULL; - break; - } - } - std::fclose(file); - if (available != 0) { - return available; - } - } - struct sysinfo info; - if (sysinfo(&info) == 0) { - const u64 unit = info.mem_unit != 0 ? info.mem_unit : 1ULL; - return (static_cast(info.freeram) + static_cast(info.bufferram)) * unit; - } - return 0; -#else - return 0; -#endif -} - -u64 GetMaxMapCount() { +u64 GetPermissibleMapCount() { + constexpr u64 DefaultMapCount = 65530; + constexpr u64 ReservedMaps = 20000; + u64 count = DefaultMapCount; #ifdef __linux__ if (std::FILE* const file = std::fopen("/proc/sys/vm/max_map_count", "re")) { char line[32]; - u64 count = 0; if (std::fgets(line, sizeof(line), file) != nullptr) { - count = std::strtoull(line, nullptr, 10); + const u64 parsed = std::strtoull(line, nullptr, 10); + if (parsed != 0) { + count = parsed; + } } std::fclose(file); - return count; } - return 0; -#else - return 0; #endif + if (count <= ReservedMaps) { + return 0; + } + return count - ReservedMaps; } } // namespace Common diff --git a/src/common/memory_detect.h b/src/common/memory_detect.h index ce5d03788f..9a7ce7ab1c 100644 --- a/src/common/memory_detect.h +++ b/src/common/memory_detect.h @@ -21,8 +21,6 @@ struct MemoryInfo { */ [[nodiscard]] const MemoryInfo& GetMemInfo(); -[[nodiscard]] u64 GetAvailablePhysicalMemory(); - -[[nodiscard]] u64 GetMaxMapCount(); +[[nodiscard]] u64 GetPermissibleMapCount(); } // namespace Common From 50e59cf09d4341dded94815e3eb6796627dd3bd8 Mon Sep 17 00:00:00 2001 From: CamilleLaVey Date: Wed, 26 Aug 2026 04:06:25 -0400 Subject: [PATCH 10/27] Another intent on write/read on the fly --- src/video_core/buffer_cache/buffer_cache.h | 65 +++++++++++++++++++ .../buffer_cache/buffer_cache_base.h | 8 +++ .../renderer_vulkan/vk_buffer_cache.h | 23 +++++++ src/video_core/vulkan_common/vulkan_device.h | 6 +- .../vulkan_common/vulkan_memory_allocator.cpp | 41 +++++++++++- .../vulkan_common/vulkan_memory_allocator.h | 10 +++ 6 files changed, 150 insertions(+), 3 deletions(-) diff --git a/src/video_core/buffer_cache/buffer_cache.h b/src/video_core/buffer_cache/buffer_cache.h index 63efeebdcf..61a064f1a2 100644 --- a/src/video_core/buffer_cache/buffer_cache.h +++ b/src/video_core/buffer_cache/buffer_cache.h @@ -1166,6 +1166,20 @@ void BufferCache

::BindHostGraphicsStorageBuffers(size_t stage) { Buffer& buffer = slot_buffers[binding.buffer_id]; TouchBuffer(buffer, binding.buffer_id); const u32 size = binding.size; + + if constexpr (USE_UNIFIED_MEMORY) { + const auto window = TryResolveUnifiedRange(binding.device_addr, size); + if (window && runtime.IsUnifiedStorageRange(size, window->offset)) { + if (is_written) { + memory_tracker.MarkRegionAsCpuModified(binding.device_addr, size); + } + runtime.BindStorageBuffer(runtime.UnifiedWindowBuffer(window->window), + runtime.UnifiedWindowAddress(window->window), + static_cast(window->offset), size, is_written); + return; + } + } + SynchronizeBuffer(buffer, binding.device_addr, size); const u32 offset = buffer.Offset(binding.device_addr); @@ -1942,6 +1956,57 @@ bool BufferCache

::ResolveUnifiedWindows( } } +template +std::optional::UnifiedWindowRange> +BufferCache

::TryResolveUnifiedRange([[maybe_unused]] DAddr device_addr, + [[maybe_unused]] u64 size) { + if constexpr (USE_UNIFIED_MEMORY) { + if (size == 0 || !runtime.IsUnifiedMemoryBindable()) { + return std::nullopt; + } + const u64 window_size = runtime.UnifiedMemoryWindowSize(); + if (window_size == 0) { + return std::nullopt; + } + const u8* const first = device_memory.GetPointer(device_addr); + if (first == nullptr) { + return std::nullopt; + } + const u64 phys_offset = static_cast(first - device_memory.GetPhysicalBase()); + const u64 unified_base = runtime.UnifiedMemoryBase(); + if (phys_offset < unified_base) { + return std::nullopt; + } + const u64 relative = phys_offset - unified_base; + const u64 unified_size = runtime.UnifiedMemorySize(); + if (relative >= unified_size || unified_size - relative < size) { + return std::nullopt; + } + const u64 local_offset = relative % window_size; + if (window_size - local_offset < size) { + return std::nullopt; + } + if (memory_tracker.IsRegionGpuModified(device_addr, size) || + IsRegionGpuModified(device_addr, size)) { + return std::nullopt; + } + u64 walked = Core::DEVICE_PAGESIZE - (device_addr & Core::DEVICE_PAGEMASK); + while (walked < size) { + const u8* const next = device_memory.GetPointer(device_addr + walked); + if (next != first + walked) { + return std::nullopt; + } + walked += Core::DEVICE_PAGESIZE; + } + return UnifiedWindowRange{ + .window = static_cast(relative / window_size), + .offset = local_offset, + }; + } else { + return std::nullopt; + } +} + template bool BufferCache

::TryUnifiedDownloadMemory([[maybe_unused]] Buffer& buffer, [[maybe_unused]] std::span copies) { diff --git a/src/video_core/buffer_cache/buffer_cache_base.h b/src/video_core/buffer_cache/buffer_cache_base.h index b7ed422d19..6eb3daf3aa 100644 --- a/src/video_core/buffer_cache/buffer_cache_base.h +++ b/src/video_core/buffer_cache/buffer_cache_base.h @@ -12,6 +12,7 @@ #include #include #include +#include #include #include #include @@ -465,6 +466,13 @@ private: bool TryUnifiedDownloadMemory(Buffer& buffer, std::span copies); + struct UnifiedWindowRange { + size_t window; + u64 offset; + }; + + std::optional TryResolveUnifiedRange(DAddr device_addr, u64 size); + using UnifiedWindowGroups = boost::container::small_vector, 4>; diff --git a/src/video_core/renderer_vulkan/vk_buffer_cache.h b/src/video_core/renderer_vulkan/vk_buffer_cache.h index d49325e51d..9e391e6bb2 100644 --- a/src/video_core/renderer_vulkan/vk_buffer_cache.h +++ b/src/video_core/renderer_vulkan/vk_buffer_cache.h @@ -246,6 +246,29 @@ public: BindBuffer(buffer, offset, size); } + void BindStorageBuffer(VkBuffer buffer, VkDeviceAddress address, u32 offset, u32 size, + [[maybe_unused]] bool is_written) { + guest_descriptor_queue.AddBuffer(buffer, address, offset, size); + } + + [[nodiscard]] bool IsUnifiedMemoryBindable() const noexcept { + return unified_memory != nullptr && unified_memory->IsValid() && + unified_memory->IsBindable(); + } + + [[nodiscard]] VkBuffer UnifiedWindowBuffer(size_t index) const noexcept { + return unified_memory->GetWindowBuffer(index); + } + + [[nodiscard]] VkDeviceAddress UnifiedWindowAddress(size_t index) const noexcept { + return unified_memory->GetWindowAddress(index); + } + + [[nodiscard]] bool IsUnifiedStorageRange(u32 size, u64 offset) const { + return size <= device.GetMaxStorageBufferRange() && + (offset % device.GetStorageBufferAlignment()) == 0; + } + void BindTextureBuffer(Buffer& buffer, u32 offset, u32 size, VideoCore::Surface::PixelFormat format) { guest_descriptor_queue.AddTexelBuffer(buffer.View(offset, size, format), diff --git a/src/video_core/vulkan_common/vulkan_device.h b/src/video_core/vulkan_common/vulkan_device.h index cdd683f016..1fd939cfc6 100644 --- a/src/video_core/vulkan_common/vulkan_device.h +++ b/src/video_core/vulkan_common/vulkan_device.h @@ -350,7 +350,11 @@ public: return properties.properties.limits.minUniformBufferOffsetAlignment; } - /// Returns storage alignment requirement. + /// Returns max storage buffer range requirement. + u32 GetMaxStorageBufferRange() const { + return properties.properties.limits.maxStorageBufferRange; + } + VkDeviceSize GetStorageBufferAlignment() const { return properties.properties.limits.minStorageBufferOffsetAlignment; } diff --git a/src/video_core/vulkan_common/vulkan_memory_allocator.cpp b/src/video_core/vulkan_common/vulkan_memory_allocator.cpp index 0209834045..82a09b9ef2 100644 --- a/src/video_core/vulkan_common/vulkan_memory_allocator.cpp +++ b/src/video_core/vulkan_common/vulkan_memory_allocator.cpp @@ -360,6 +360,8 @@ bool HostMemoryImport::ImportHardwareBuffers( const auto memory_props = device.GetPhysical().GetMemoryProperties().memoryProperties; window_size = hardware_buffer_window; base_offset = hardware_buffer_base; + + const auto import_all = [&](VkBufferUsageFlags usage, bool want_address) { for (size_t i = 0; i < hardware_buffers.size(); ++i) { const size_t offset = hardware_buffer_base + i * hardware_buffer_window; if (offset >= size) { @@ -390,7 +392,7 @@ bool HostMemoryImport::ImportHardwareBuffers( .pNext = &external_info, .flags = 0, .size = window_len, - .usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT, + .usage = usage, .sharingMode = VK_SHARING_MODE_EXCLUSIVE, .queueFamilyIndexCount = 0, .pQueueFamilyIndices = nullptr, @@ -422,9 +424,19 @@ bool HostMemoryImport::ImportHardwareBuffers( .image = VK_NULL_HANDLE, .buffer = new_buffer, }; + const VkMemoryAllocateFlagsInfo flags_info{ + .sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_FLAGS_INFO, + .pNext = &dedicated_info, + .flags = VK_MEMORY_ALLOCATE_DEVICE_ADDRESS_BIT, + .deviceMask = 0, + }; + const void *alloc_next = &dedicated_info; + if (want_address) { + alloc_next = &flags_info; + } const VkMemoryAllocateInfo alloc_info{ .sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO, - .pNext = &dedicated_info, + .pNext = alloc_next, .allocationSize = ahb_props.allocationSize, .memoryTypeIndex = *type_index, }; @@ -437,12 +449,37 @@ bool HostMemoryImport::ImportHardwareBuffers( logical.DestroyBufferRaw(new_buffer); break; } + VkDeviceAddress address = 0; + if (want_address) { + address = logical.GetBufferDeviceAddress(new_buffer); + } windows.push_back(Window{ .memory = std::move(memory), .buffer = new_buffer, + .address = address, }); imported_size += static_cast(window_len); } + return !windows.empty(); + }; + + constexpr VkBufferUsageFlags TransferUsage = + VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT; + VkBufferUsageFlags shader_usage = TransferUsage | + VK_BUFFER_USAGE_UNIFORM_TEXEL_BUFFER_BIT | + VK_BUFFER_USAGE_STORAGE_TEXEL_BUFFER_BIT | VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT | + VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_INDEX_BUFFER_BIT | + VK_BUFFER_USAGE_VERTEX_BUFFER_BIT | VK_BUFFER_USAGE_INDIRECT_BUFFER_BIT; + const bool want_address = device.IsBufferDeviceAddressSupported(); + if (want_address) { + shader_usage |= VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT; + } + + bindable = import_all(shader_usage, want_address); + if (!bindable) { + imported_size = 0; + import_all(TransferUsage, false); + } if (windows.empty()) { window_size = 0; base_offset = 0; diff --git a/src/video_core/vulkan_common/vulkan_memory_allocator.h b/src/video_core/vulkan_common/vulkan_memory_allocator.h index bbcb7288df..d397242a5f 100644 --- a/src/video_core/vulkan_common/vulkan_memory_allocator.h +++ b/src/video_core/vulkan_common/vulkan_memory_allocator.h @@ -122,14 +122,23 @@ namespace Vulkan { return windows[index].buffer; } + [[nodiscard]] VkDeviceAddress GetWindowAddress(size_t index) const noexcept { + return windows[index].address; + } + [[nodiscard]] size_t GetWindowCount() const noexcept { return windows.size(); } + [[nodiscard]] bool IsBindable() const noexcept { + return bindable; + } + private: struct Window { vk::DeviceMemory memory; VkBuffer buffer{}; + VkDeviceAddress address{}; }; bool ImportHostPointer(void *base, size_t size); @@ -144,6 +153,7 @@ namespace Vulkan { size_t imported_size{}; size_t base_offset{}; bool foreign_ownership{}; + bool bindable{}; }; /// Memory allocator container. From ce8c754eb31d9c593064110eac8e6c0560985776 Mon Sep 17 00:00:00 2001 From: CamilleLaVey Date: Wed, 26 Aug 2026 04:11:59 -0400 Subject: [PATCH 11/27] Meowly The Build Destroyer --- src/video_core/vulkan_common/vulkan_device.h | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/src/video_core/vulkan_common/vulkan_device.h b/src/video_core/vulkan_common/vulkan_device.h index 1fd939cfc6..cdd683f016 100644 --- a/src/video_core/vulkan_common/vulkan_device.h +++ b/src/video_core/vulkan_common/vulkan_device.h @@ -350,11 +350,7 @@ public: return properties.properties.limits.minUniformBufferOffsetAlignment; } - /// Returns max storage buffer range requirement. - u32 GetMaxStorageBufferRange() const { - return properties.properties.limits.maxStorageBufferRange; - } - + /// Returns storage alignment requirement. VkDeviceSize GetStorageBufferAlignment() const { return properties.properties.limits.minStorageBufferOffsetAlignment; } From 1f2aa7e40b841282fc3f3e7b08cd14871727884d Mon Sep 17 00:00:00 2001 From: CamilleLaVey Date: Wed, 26 Aug 2026 04:52:52 -0400 Subject: [PATCH 12/27] Added vertex, uniform and indexes on the upload path --- src/video_core/buffer_cache/buffer_cache.h | 95 ++++++++++++++++--- .../buffer_cache/buffer_cache_base.h | 5 + .../renderer_vulkan/vk_buffer_cache.cpp | 58 ++++++++++- .../renderer_vulkan/vk_buffer_cache.h | 12 +++ src/video_core/vulkan_common/vulkan_device.h | 4 + 5 files changed, 158 insertions(+), 16 deletions(-) diff --git a/src/video_core/buffer_cache/buffer_cache.h b/src/video_core/buffer_cache/buffer_cache.h index 61a064f1a2..95e032d3c1 100644 --- a/src/video_core/buffer_cache/buffer_cache.h +++ b/src/video_core/buffer_cache/buffer_cache.h @@ -828,6 +828,20 @@ void BufferCache

::BindHostIndexBuffer() { const u32 size = channel_state->index_buffer.size; const auto& draw_state = maxwell3d->draw_manager.draw_state; if (draw_state.inline_index_draw_indexes.empty()) { + if constexpr (USE_UNIFIED_MEMORY && !HAS_FULL_INDEX_AND_PRIMITIVE_SUPPORT) { + const auto window = + TryResolveUnifiedRange(channel_state->index_buffer.device_addr, size); + if (window && runtime.IsUnifiedIndexRange(draw_state.topology, + draw_state.index_buffer.format, + window->offset)) { + runtime.BindIndexBuffer(draw_state.topology, draw_state.index_buffer.format, + draw_state.index_buffer.first, + draw_state.index_buffer.count, + runtime.UnifiedWindowBuffer(window->window), + static_cast(window->offset), size); + return; + } + } SynchronizeBuffer(buffer, channel_state->index_buffer.device_addr, size); } else { if constexpr (USE_MEMORY_MAPS_FOR_UPLOADS) { @@ -881,6 +895,7 @@ void BufferCache

::UpdateVertexBufferSlot(u32 index, const Binding& binding) { enabled_vertex_buffers_mask |= (1u << index); } else { enabled_vertex_buffers_mask &= ~(1u << index); + unified_vertex_buffers_mask &= ~(1u << index); } } @@ -913,15 +928,39 @@ void BufferCache

::BindHostVertexBuffers() { const Binding& binding = VertexBufferSlot(index); Buffer& buffer = slot_buffers[binding.buffer_id]; TouchBuffer(buffer, binding.buffer_id); + bool needs_bind = flags[Dirty::VertexBuffer0 + index]; + u32 unified_window = NO_UNIFIED_WINDOW; + u64 unified_offset = 0; + if constexpr (USE_UNIFIED_MEMORY) { + const bool was_unified = ((unified_vertex_buffers_mask >> index) & 1) != 0; + if (needs_bind || was_unified) { + const auto window = TryResolveUnifiedRange(binding.device_addr, binding.size); + if (window) { + unified_window = static_cast(window->window); + unified_offset = window->offset; + } + } + if (was_unified && unified_window == NO_UNIFIED_WINDOW) { + needs_bind = true; + } + } + if (unified_window == NO_UNIFIED_WINDOW) { SynchronizeBuffer(buffer, binding.device_addr, binding.size); - if (!flags[Dirty::VertexBuffer0 + index]) { + } + if (!needs_bind) { flush_bindings(); continue; } flags[Dirty::VertexBuffer0 + index] = false; const u32 stride = maxwell3d->regs.vertex_streams[index].stride; - const u32 offset = buffer.Offset(binding.device_addr); + u32 offset = static_cast(unified_offset); + if (unified_window == NO_UNIFIED_WINDOW) { + offset = buffer.Offset(binding.device_addr); buffer.MarkUsage(offset, binding.size); + unified_vertex_buffers_mask &= ~(1u << index); + } else { + unified_vertex_buffers_mask |= 1u << index; + } if (!bindings.buffers.empty() && index != last_index + 1) { flush_bindings(); } @@ -932,6 +971,7 @@ void BufferCache

::BindHostVertexBuffers() { bindings.offsets.push_back(offset); bindings.sizes.push_back(binding.size); bindings.strides.push_back(stride); + bindings.unified_windows.push_back(unified_window); last_index = index; } flush_bindings(); @@ -939,12 +979,31 @@ void BufferCache

::BindHostVertexBuffers() { HostBindings host_bindings; bool any_valid{false}; auto& flags = maxwell3d->dirty.flags; + std::array unified_windows; + std::array unified_offsets{}; + unified_windows.fill(NO_UNIFIED_WINDOW); for (u32 index = 0; index < NUM_VERTEX_BUFFERS; ++index) { const Binding& binding = channel_state->vertex_buffers[index]; Buffer& buffer = slot_buffers[binding.buffer_id]; TouchBuffer(buffer, binding.buffer_id); + bool needs_bind = flags[Dirty::VertexBuffer0 + index]; + if constexpr (USE_UNIFIED_MEMORY) { + const bool was_unified = ((unified_vertex_buffers_mask >> index) & 1) != 0; + if (needs_bind || was_unified) { + const auto window = TryResolveUnifiedRange(binding.device_addr, binding.size); + if (window) { + unified_windows[index] = static_cast(window->window); + unified_offsets[index] = window->offset; + } + } + if (was_unified && unified_windows[index] == NO_UNIFIED_WINDOW) { + needs_bind = true; + } + } + if (unified_windows[index] == NO_UNIFIED_WINDOW) { SynchronizeBuffer(buffer, binding.device_addr, binding.size); - if (!flags[Dirty::VertexBuffer0 + index]) { + } + if (!needs_bind) { continue; } flags[Dirty::VertexBuffer0 + index] = false; @@ -963,13 +1022,20 @@ void BufferCache

::BindHostVertexBuffers() { Buffer& buffer = slot_buffers[binding.buffer_id]; const u32 stride = maxwell3d->regs.vertex_streams[index].stride; - const u32 offset = buffer.Offset(binding.device_addr); + u32 offset = static_cast(unified_offsets[index]); + if (unified_windows[index] == NO_UNIFIED_WINDOW) { + offset = buffer.Offset(binding.device_addr); buffer.MarkUsage(offset, binding.size); + unified_vertex_buffers_mask &= ~(1u << index); + } else { + unified_vertex_buffers_mask |= 1u << index; + } host_bindings.buffers.push_back(&buffer); host_bindings.offsets.push_back(offset); host_bindings.sizes.push_back(binding.size); host_bindings.strides.push_back(stride); + host_bindings.unified_windows.push_back(unified_windows[index]); } runtime.BindVertexBuffers(host_bindings); } @@ -1013,6 +1079,17 @@ void BufferCache

::BindHostGraphicsUniformBuffer(size_t stage, u32 index, u32 const u32 size = (std::min)(binding.size, (*channel_state->uniform_buffer_sizes)[stage][index]); Buffer& buffer = slot_buffers[binding.buffer_id]; TouchBuffer(buffer, binding.buffer_id); + if constexpr (USE_UNIFIED_MEMORY) { + const auto window = TryResolveUnifiedRange(device_addr, size); + if (window && runtime.IsUnifiedUniformRange(size, window->offset)) { + channel_state->fast_bound_uniform_buffers[stage] &= ~(1u << binding_index); + channel_state->uniform_buffer_binding_sizes[stage][binding_index] = size; + runtime.BindUniformBuffer(runtime.UnifiedWindowBuffer(window->window), + runtime.UnifiedWindowAddress(window->window), + static_cast(window->offset), size); + return; + } + } const bool has_host_buffer = binding.buffer_id != NULL_BUFFER_ID; const u32 offset = has_host_buffer ? buffer.Offset(device_addr) : 0; const bool needs_alignment_stream = [&]() { @@ -1968,7 +2045,7 @@ BufferCache

::TryResolveUnifiedRange([[maybe_unused]] DAddr device_addr, if (window_size == 0) { return std::nullopt; } - const u8* const first = device_memory.GetPointer(device_addr); + const u8* const first = device_memory.GetSpan(device_addr, size); if (first == nullptr) { return std::nullopt; } @@ -1990,14 +2067,6 @@ BufferCache

::TryResolveUnifiedRange([[maybe_unused]] DAddr device_addr, IsRegionGpuModified(device_addr, size)) { return std::nullopt; } - u64 walked = Core::DEVICE_PAGESIZE - (device_addr & Core::DEVICE_PAGEMASK); - while (walked < size) { - const u8* const next = device_memory.GetPointer(device_addr + walked); - if (next != first + walked) { - return std::nullopt; - } - walked += Core::DEVICE_PAGESIZE; - } return UnifiedWindowRange{ .window = static_cast(relative / window_size), .offset = local_offset, diff --git a/src/video_core/buffer_cache/buffer_cache_base.h b/src/video_core/buffer_cache/buffer_cache_base.h index 6eb3daf3aa..80088dc6d4 100644 --- a/src/video_core/buffer_cache/buffer_cache_base.h +++ b/src/video_core/buffer_cache/buffer_cache_base.h @@ -10,6 +10,7 @@ #include #include #include +#include #include #include #include @@ -106,12 +107,15 @@ static constexpr Binding NULL_BINDING{ .buffer_id = NULL_BUFFER_ID, }; +static constexpr u32 NO_UNIFIED_WINDOW = (std::numeric_limits::max)(); + template struct HostBindings { boost::container::static_vector buffers; boost::container::static_vector offsets; boost::container::static_vector sizes; boost::container::static_vector strides; + boost::container::static_vector unified_windows; u32 min_index{NUM_VERTEX_BUFFERS}; u32 max_index{0}; }; @@ -524,6 +528,7 @@ private: u32 last_index_count = 0; u32 enabled_vertex_buffers_mask = 0; + u32 unified_vertex_buffers_mask = 0; u64 vertex_buffers_serial = 0; std::array v_buffer{}; diff --git a/src/video_core/renderer_vulkan/vk_buffer_cache.cpp b/src/video_core/renderer_vulkan/vk_buffer_cache.cpp index b27f43c86e..791a0d8a4f 100644 --- a/src/video_core/renderer_vulkan/vk_buffer_cache.cpp +++ b/src/video_core/renderer_vulkan/vk_buffer_cache.cpp @@ -7,6 +7,7 @@ #include #include #include +#include #include #include #include @@ -69,6 +70,16 @@ VkIndexType IndexTypeFromNumElements(const Device& device, u32 num_elements) { return VK_INDEX_TYPE_UINT32; } +u32 GrowIndexCount(u32 current, u32 requested) { + constexpr u32 MinimumIndices = 4096; + constexpr u32 GrowthLimit = (std::numeric_limits::max)() / 2; + u32 grown = (std::max)(requested, MinimumIndices); + if (current <= GrowthLimit) { + grown = (std::max)(grown, current * 2); + } + return grown; +} + size_t BytesPerIndex(VkIndexType index_type) { switch (index_type) { case VK_INDEX_TYPE_UINT8_EXT: @@ -193,13 +204,12 @@ public: virtual ~QuadIndexBuffer() = default; void UpdateBuffer(u32 num_indices_) { + ReleaseRetiredBuffers(); if (num_indices_ <= num_indices) { return; } - scheduler.Finish(); - - num_indices = num_indices_; + num_indices = GrowIndexCount(num_indices, num_indices_); index_type = IndexTypeFromNumElements(device, num_indices); const u32 num_quads = GetQuadsNum(num_indices); @@ -217,6 +227,12 @@ public: .queueFamilyIndexCount = 0, .pQueueFamilyIndices = nullptr, }; + if (buffer) { + retired_buffers.push_back(RetiredBuffer{ + .buffer = std::move(buffer), + .tick = scheduler.CurrentTick(), + }); + } buffer = memory_allocator.CreateBuffer(buffer_ci, MemoryUsage::DeviceLocal); if (device.HasDebuggingToolAttached()) { buffer.SetObjectNameEXT("Quad LUT"); @@ -284,6 +300,17 @@ protected: virtual void MakeAndUpdateIndices(u8* staging_data, size_t quad_size, u32 quad, u32 first) = 0; + struct RetiredBuffer { + vk::Buffer buffer; + u64 tick; + }; + + void ReleaseRetiredBuffers() { + std::erase_if(retired_buffers, [this](const RetiredBuffer& entry) { + return scheduler.IsFree(entry.tick); + }); + } + const Device& device; MemoryAllocator& memory_allocator; Scheduler& scheduler; @@ -291,6 +318,7 @@ protected: vk::Buffer buffer{}; MemoryCommit memory_commit{}; + std::vector retired_buffers; VkIndexType index_type{}; u32 num_indices = 0; }; @@ -739,6 +767,25 @@ bool BufferCacheRuntime::BindMultiRangeStorageBuffer(u64 key, bool is_written) { return true; } +bool BufferCacheRuntime::IsUnifiedIndexRange(PrimitiveTopology topology, IndexFormat index_format, + u64 offset) const { + const VkIndexType vk_index_type = MaxwellToVK::IndexFormat(index_format); + const bool needs_uint8_pass = + vk_index_type == VK_INDEX_TYPE_UINT8_EXT && !device.IsExtIndexTypeUint8Supported(); + if (topology == PrimitiveTopology::Quads || topology == PrimitiveTopology::QuadStrip || + needs_uint8_pass) { + return (offset % device.GetStorageBufferAlignment()) == 0; + } + switch (vk_index_type) { + case VK_INDEX_TYPE_UINT32: + return (offset % 4) == 0; + case VK_INDEX_TYPE_UINT16: + return (offset % 2) == 0; + default: + return true; + } +} + void BufferCacheRuntime::BindIndexBuffer(PrimitiveTopology topology, IndexFormat index_format, u32 base_vertex, u32 num_indices, VkBuffer buffer, u32 offset, [[maybe_unused]] u32 size) { @@ -814,6 +861,11 @@ void BufferCacheRuntime::BindVertexBuffer(u32 index, VkBuffer buffer, u32 offset void BufferCacheRuntime::BindVertexBuffers(VideoCommon::HostBindings& bindings) { boost::container::static_vector buffer_handles(bindings.buffers.size()); for (u32 i = 0; i < bindings.buffers.size(); ++i) { + if (i < bindings.unified_windows.size() && + bindings.unified_windows[i] != VideoCommon::NO_UNIFIED_WINDOW) { + buffer_handles[i] = unified_memory->GetWindowBuffer(bindings.unified_windows[i]); + continue; + } auto handle = bindings.buffers[i]->Handle(); if (handle == VK_NULL_HANDLE) { bindings.offsets[i] = 0; diff --git a/src/video_core/renderer_vulkan/vk_buffer_cache.h b/src/video_core/renderer_vulkan/vk_buffer_cache.h index 9e391e6bb2..06c1e3ae66 100644 --- a/src/video_core/renderer_vulkan/vk_buffer_cache.h +++ b/src/video_core/renderer_vulkan/vk_buffer_cache.h @@ -241,6 +241,10 @@ public: BindBuffer(buffer, offset, size); } + void BindUniformBuffer(VkBuffer buffer, VkDeviceAddress address, u32 offset, u32 size) { + guest_descriptor_queue.AddBuffer(buffer, address, offset, size); + } + void BindStorageBuffer(const Buffer& buffer, u32 offset, u32 size, [[maybe_unused]] bool is_written) { BindBuffer(buffer, offset, size); @@ -269,6 +273,14 @@ public: (offset % device.GetStorageBufferAlignment()) == 0; } + [[nodiscard]] bool IsUnifiedUniformRange(u32 size, u64 offset) const { + return size <= device.GetMaxUniformBufferRange() && + (offset % device.GetUniformBufferAlignment()) == 0; + } + + [[nodiscard]] bool IsUnifiedIndexRange(PrimitiveTopology topology, IndexFormat index_format, + u64 offset) const; + void BindTextureBuffer(Buffer& buffer, u32 offset, u32 size, VideoCore::Surface::PixelFormat format) { guest_descriptor_queue.AddTexelBuffer(buffer.View(offset, size, format), diff --git a/src/video_core/vulkan_common/vulkan_device.h b/src/video_core/vulkan_common/vulkan_device.h index cdd683f016..a41baa743d 100644 --- a/src/video_core/vulkan_common/vulkan_device.h +++ b/src/video_core/vulkan_common/vulkan_device.h @@ -360,6 +360,10 @@ public: return properties.properties.limits.maxStorageBufferRange; } + VkDeviceSize GetMaxUniformBufferRange() const { + return properties.properties.limits.maxUniformBufferRange; + } + std::array GetMaxComputeWorkGroupCount() const { const auto& count = properties.properties.limits.maxComputeWorkGroupCount; return {count[0], count[1], count[2]}; From a4864176f5a7ec31591502ac6cafd2dd2a3cc4a8 Mon Sep 17 00:00:00 2001 From: CamilleLaVey Date: Wed, 26 Aug 2026 05:09:12 -0400 Subject: [PATCH 13/27] Just a quick test --- src/video_core/buffer_cache/buffer_cache.h | 11 ----------- src/video_core/renderer_vulkan/vk_buffer_cache.h | 9 --------- src/video_core/vulkan_common/vulkan_device.h | 4 ---- 3 files changed, 24 deletions(-) diff --git a/src/video_core/buffer_cache/buffer_cache.h b/src/video_core/buffer_cache/buffer_cache.h index 95e032d3c1..00d29cc8a4 100644 --- a/src/video_core/buffer_cache/buffer_cache.h +++ b/src/video_core/buffer_cache/buffer_cache.h @@ -1079,17 +1079,6 @@ void BufferCache

::BindHostGraphicsUniformBuffer(size_t stage, u32 index, u32 const u32 size = (std::min)(binding.size, (*channel_state->uniform_buffer_sizes)[stage][index]); Buffer& buffer = slot_buffers[binding.buffer_id]; TouchBuffer(buffer, binding.buffer_id); - if constexpr (USE_UNIFIED_MEMORY) { - const auto window = TryResolveUnifiedRange(device_addr, size); - if (window && runtime.IsUnifiedUniformRange(size, window->offset)) { - channel_state->fast_bound_uniform_buffers[stage] &= ~(1u << binding_index); - channel_state->uniform_buffer_binding_sizes[stage][binding_index] = size; - runtime.BindUniformBuffer(runtime.UnifiedWindowBuffer(window->window), - runtime.UnifiedWindowAddress(window->window), - static_cast(window->offset), size); - return; - } - } const bool has_host_buffer = binding.buffer_id != NULL_BUFFER_ID; const u32 offset = has_host_buffer ? buffer.Offset(device_addr) : 0; const bool needs_alignment_stream = [&]() { diff --git a/src/video_core/renderer_vulkan/vk_buffer_cache.h b/src/video_core/renderer_vulkan/vk_buffer_cache.h index 06c1e3ae66..9f42c21496 100644 --- a/src/video_core/renderer_vulkan/vk_buffer_cache.h +++ b/src/video_core/renderer_vulkan/vk_buffer_cache.h @@ -241,10 +241,6 @@ public: BindBuffer(buffer, offset, size); } - void BindUniformBuffer(VkBuffer buffer, VkDeviceAddress address, u32 offset, u32 size) { - guest_descriptor_queue.AddBuffer(buffer, address, offset, size); - } - void BindStorageBuffer(const Buffer& buffer, u32 offset, u32 size, [[maybe_unused]] bool is_written) { BindBuffer(buffer, offset, size); @@ -273,11 +269,6 @@ public: (offset % device.GetStorageBufferAlignment()) == 0; } - [[nodiscard]] bool IsUnifiedUniformRange(u32 size, u64 offset) const { - return size <= device.GetMaxUniformBufferRange() && - (offset % device.GetUniformBufferAlignment()) == 0; - } - [[nodiscard]] bool IsUnifiedIndexRange(PrimitiveTopology topology, IndexFormat index_format, u64 offset) const; diff --git a/src/video_core/vulkan_common/vulkan_device.h b/src/video_core/vulkan_common/vulkan_device.h index a41baa743d..cdd683f016 100644 --- a/src/video_core/vulkan_common/vulkan_device.h +++ b/src/video_core/vulkan_common/vulkan_device.h @@ -360,10 +360,6 @@ public: return properties.properties.limits.maxStorageBufferRange; } - VkDeviceSize GetMaxUniformBufferRange() const { - return properties.properties.limits.maxUniformBufferRange; - } - std::array GetMaxComputeWorkGroupCount() const { const auto& count = properties.properties.limits.maxComputeWorkGroupCount; return {count[0], count[1], count[2]}; From bce8e0aa6da479200184b88af6f98c1952929909 Mon Sep 17 00:00:00 2001 From: CamilleLaVey Date: Wed, 26 Aug 2026 14:49:01 -0400 Subject: [PATCH 14/27] [TEST] Bring the unswizzle work from tiled-gpu-v2 x2 + revert of vertex, indexes from AHB path --- src/video_core/buffer_cache/buffer_cache.h | 74 +-- .../buffer_cache/buffer_cache_base.h | 5 - src/video_core/host_shaders/CMakeLists.txt | 2 + .../block_linear_unswizzle_2d_buffer.comp | 104 ++++ .../block_linear_unswizzle_3d_buffer.comp | 105 ++++ .../renderer_vulkan/vk_buffer_cache.cpp | 24 - .../renderer_vulkan/vk_buffer_cache.h | 3 - .../renderer_vulkan/vk_compute_pass.cpp | 478 ++++++++++++++++++ .../renderer_vulkan/vk_compute_pass.h | 39 ++ .../renderer_vulkan/vk_texture_cache.cpp | 21 + .../renderer_vulkan/vk_texture_cache.h | 2 + 11 files changed, 755 insertions(+), 102 deletions(-) create mode 100644 src/video_core/host_shaders/block_linear_unswizzle_2d_buffer.comp create mode 100644 src/video_core/host_shaders/block_linear_unswizzle_3d_buffer.comp diff --git a/src/video_core/buffer_cache/buffer_cache.h b/src/video_core/buffer_cache/buffer_cache.h index 00d29cc8a4..7ddfb5202c 100644 --- a/src/video_core/buffer_cache/buffer_cache.h +++ b/src/video_core/buffer_cache/buffer_cache.h @@ -828,20 +828,6 @@ void BufferCache

::BindHostIndexBuffer() { const u32 size = channel_state->index_buffer.size; const auto& draw_state = maxwell3d->draw_manager.draw_state; if (draw_state.inline_index_draw_indexes.empty()) { - if constexpr (USE_UNIFIED_MEMORY && !HAS_FULL_INDEX_AND_PRIMITIVE_SUPPORT) { - const auto window = - TryResolveUnifiedRange(channel_state->index_buffer.device_addr, size); - if (window && runtime.IsUnifiedIndexRange(draw_state.topology, - draw_state.index_buffer.format, - window->offset)) { - runtime.BindIndexBuffer(draw_state.topology, draw_state.index_buffer.format, - draw_state.index_buffer.first, - draw_state.index_buffer.count, - runtime.UnifiedWindowBuffer(window->window), - static_cast(window->offset), size); - return; - } - } SynchronizeBuffer(buffer, channel_state->index_buffer.device_addr, size); } else { if constexpr (USE_MEMORY_MAPS_FOR_UPLOADS) { @@ -895,7 +881,6 @@ void BufferCache

::UpdateVertexBufferSlot(u32 index, const Binding& binding) { enabled_vertex_buffers_mask |= (1u << index); } else { enabled_vertex_buffers_mask &= ~(1u << index); - unified_vertex_buffers_mask &= ~(1u << index); } } @@ -928,39 +913,15 @@ void BufferCache

::BindHostVertexBuffers() { const Binding& binding = VertexBufferSlot(index); Buffer& buffer = slot_buffers[binding.buffer_id]; TouchBuffer(buffer, binding.buffer_id); - bool needs_bind = flags[Dirty::VertexBuffer0 + index]; - u32 unified_window = NO_UNIFIED_WINDOW; - u64 unified_offset = 0; - if constexpr (USE_UNIFIED_MEMORY) { - const bool was_unified = ((unified_vertex_buffers_mask >> index) & 1) != 0; - if (needs_bind || was_unified) { - const auto window = TryResolveUnifiedRange(binding.device_addr, binding.size); - if (window) { - unified_window = static_cast(window->window); - unified_offset = window->offset; - } - } - if (was_unified && unified_window == NO_UNIFIED_WINDOW) { - needs_bind = true; - } - } - if (unified_window == NO_UNIFIED_WINDOW) { SynchronizeBuffer(buffer, binding.device_addr, binding.size); - } - if (!needs_bind) { + if (!flags[Dirty::VertexBuffer0 + index]) { flush_bindings(); continue; } flags[Dirty::VertexBuffer0 + index] = false; const u32 stride = maxwell3d->regs.vertex_streams[index].stride; - u32 offset = static_cast(unified_offset); - if (unified_window == NO_UNIFIED_WINDOW) { - offset = buffer.Offset(binding.device_addr); + const u32 offset = buffer.Offset(binding.device_addr); buffer.MarkUsage(offset, binding.size); - unified_vertex_buffers_mask &= ~(1u << index); - } else { - unified_vertex_buffers_mask |= 1u << index; - } if (!bindings.buffers.empty() && index != last_index + 1) { flush_bindings(); } @@ -971,7 +932,6 @@ void BufferCache

::BindHostVertexBuffers() { bindings.offsets.push_back(offset); bindings.sizes.push_back(binding.size); bindings.strides.push_back(stride); - bindings.unified_windows.push_back(unified_window); last_index = index; } flush_bindings(); @@ -979,31 +939,12 @@ void BufferCache

::BindHostVertexBuffers() { HostBindings host_bindings; bool any_valid{false}; auto& flags = maxwell3d->dirty.flags; - std::array unified_windows; - std::array unified_offsets{}; - unified_windows.fill(NO_UNIFIED_WINDOW); for (u32 index = 0; index < NUM_VERTEX_BUFFERS; ++index) { const Binding& binding = channel_state->vertex_buffers[index]; Buffer& buffer = slot_buffers[binding.buffer_id]; TouchBuffer(buffer, binding.buffer_id); - bool needs_bind = flags[Dirty::VertexBuffer0 + index]; - if constexpr (USE_UNIFIED_MEMORY) { - const bool was_unified = ((unified_vertex_buffers_mask >> index) & 1) != 0; - if (needs_bind || was_unified) { - const auto window = TryResolveUnifiedRange(binding.device_addr, binding.size); - if (window) { - unified_windows[index] = static_cast(window->window); - unified_offsets[index] = window->offset; - } - } - if (was_unified && unified_windows[index] == NO_UNIFIED_WINDOW) { - needs_bind = true; - } - } - if (unified_windows[index] == NO_UNIFIED_WINDOW) { SynchronizeBuffer(buffer, binding.device_addr, binding.size); - } - if (!needs_bind) { + if (!flags[Dirty::VertexBuffer0 + index]) { continue; } flags[Dirty::VertexBuffer0 + index] = false; @@ -1022,20 +963,13 @@ void BufferCache

::BindHostVertexBuffers() { Buffer& buffer = slot_buffers[binding.buffer_id]; const u32 stride = maxwell3d->regs.vertex_streams[index].stride; - u32 offset = static_cast(unified_offsets[index]); - if (unified_windows[index] == NO_UNIFIED_WINDOW) { - offset = buffer.Offset(binding.device_addr); + const u32 offset = buffer.Offset(binding.device_addr); buffer.MarkUsage(offset, binding.size); - unified_vertex_buffers_mask &= ~(1u << index); - } else { - unified_vertex_buffers_mask |= 1u << index; - } host_bindings.buffers.push_back(&buffer); host_bindings.offsets.push_back(offset); host_bindings.sizes.push_back(binding.size); host_bindings.strides.push_back(stride); - host_bindings.unified_windows.push_back(unified_windows[index]); } runtime.BindVertexBuffers(host_bindings); } diff --git a/src/video_core/buffer_cache/buffer_cache_base.h b/src/video_core/buffer_cache/buffer_cache_base.h index 80088dc6d4..6eb3daf3aa 100644 --- a/src/video_core/buffer_cache/buffer_cache_base.h +++ b/src/video_core/buffer_cache/buffer_cache_base.h @@ -10,7 +10,6 @@ #include #include #include -#include #include #include #include @@ -107,15 +106,12 @@ static constexpr Binding NULL_BINDING{ .buffer_id = NULL_BUFFER_ID, }; -static constexpr u32 NO_UNIFIED_WINDOW = (std::numeric_limits::max)(); - template struct HostBindings { boost::container::static_vector buffers; boost::container::static_vector offsets; boost::container::static_vector sizes; boost::container::static_vector strides; - boost::container::static_vector unified_windows; u32 min_index{NUM_VERTEX_BUFFERS}; u32 max_index{0}; }; @@ -528,7 +524,6 @@ private: u32 last_index_count = 0; u32 enabled_vertex_buffers_mask = 0; - u32 unified_vertex_buffers_mask = 0; u64 vertex_buffers_serial = 0; std::array v_buffer{}; diff --git a/src/video_core/host_shaders/CMakeLists.txt b/src/video_core/host_shaders/CMakeLists.txt index c4e7ac3f6f..f8b64c57e8 100644 --- a/src/video_core/host_shaders/CMakeLists.txt +++ b/src/video_core/host_shaders/CMakeLists.txt @@ -17,12 +17,14 @@ set(SHADER_FILES ${CMAKE_CURRENT_SOURCE_DIR}/astc_decoder.comp ${CMAKE_CURRENT_SOURCE_DIR}/blit_color_float.frag ${CMAKE_CURRENT_SOURCE_DIR}/block_linear_unswizzle_2d.comp + ${CMAKE_CURRENT_SOURCE_DIR}/block_linear_unswizzle_2d_buffer.comp ${CMAKE_CURRENT_SOURCE_DIR}/blit_color_msaa.frag ${CMAKE_CURRENT_SOURCE_DIR}/blit_depth.frag ${CMAKE_CURRENT_SOURCE_DIR}/blit_depth_msaa.frag ${CMAKE_CURRENT_SOURCE_DIR}/blit_depth_stencil_msaa.frag ${CMAKE_CURRENT_SOURCE_DIR}/block_linear_unswizzle_3d.comp ${CMAKE_CURRENT_SOURCE_DIR}/block_linear_unswizzle_3d_bcn.comp + ${CMAKE_CURRENT_SOURCE_DIR}/block_linear_unswizzle_3d_buffer.comp ${CMAKE_CURRENT_SOURCE_DIR}/convert_abgr8_to_d24s8.frag ${CMAKE_CURRENT_SOURCE_DIR}/convert_abgr8_to_d32f.frag ${CMAKE_CURRENT_SOURCE_DIR}/convert_d32f_to_abgr8.frag diff --git a/src/video_core/host_shaders/block_linear_unswizzle_2d_buffer.comp b/src/video_core/host_shaders/block_linear_unswizzle_2d_buffer.comp new file mode 100644 index 0000000000..3fc71e05b6 --- /dev/null +++ b/src/video_core/host_shaders/block_linear_unswizzle_2d_buffer.comp @@ -0,0 +1,104 @@ +// SPDX-FileCopyrightText: Copyright 2026 Eden Emulator Project +// SPDX-License-Identifier: GPL-3.0-or-later + +#version 430 + +#extension GL_EXT_shader_16bit_storage : require +#extension GL_EXT_shader_8bit_storage : require + +#define BINDING_INPUT_BUFFER 0 +#define BINDING_OUTPUT_BUFFER 1 + +layout(push_constant) uniform PushConstants { + uvec3 dim; + uint bytes_per_block_log2; + + uvec3 origin; + uint layer_stride; + + uint block_size; + uint x_shift; + uint block_height; + uint block_height_mask; +} pc; + +layout(binding = BINDING_INPUT_BUFFER, std430) buffer InputBufferU32 { uint u32data[]; }; +layout(binding = BINDING_INPUT_BUFFER, std430) buffer InputBufferU64 { uvec2 u64data[]; }; +layout(binding = BINDING_INPUT_BUFFER, std430) buffer InputBufferU128 { uvec4 u128data[]; }; + +layout(binding = BINDING_OUTPUT_BUFFER, std430) writeonly buffer OutputBuffer { + uint out_u32[]; +}; + +layout(local_size_x = 16, local_size_y = 8, local_size_z = 1) in; + +const uint GOB_SIZE_X = 64; +const uint GOB_SIZE_Y = 8; + +const uint GOB_SIZE_X_SHIFT = 6; +const uint GOB_SIZE_Y_SHIFT = 3; +const uint GOB_SIZE_SHIFT = GOB_SIZE_X_SHIFT + GOB_SIZE_Y_SHIFT; + +const uvec2 SWIZZLE_MASK = uvec2(GOB_SIZE_X - 1u, GOB_SIZE_Y - 1u); + +uint SwizzleTable(uint pos) { + const uint t[8] = uint[]( + 0x12100200, 0x13110301, 0x16140604, 0x17150705, + 0x1a180a08, 0x1b190b09, 0x1e1c0e0c, 0x1f1d0f0d + ); + const uint i = pos >> 4; + const uint h = (t[i / 4] >> ((i % 4) * 8)) & 0xff; + return (h << 4) | (pos & 0xf); +} + +uint SwizzleOffset(uvec2 pos) { + pos = pos & SWIZZLE_MASK; + return SwizzleTable(pos.y * 64u + pos.x); +} + +uvec4 ReadTexel(uint offset) { + switch (pc.bytes_per_block_log2) { + case 2u: + return uvec4(u32data[offset / 4u], 0u, 0u, 0u); + case 3u: + return uvec4(u64data[offset / 8u], 0u, 0u); + case 4u: + return u128data[offset / 16u]; + } + return uvec4(0u); +} + +void main() { + uvec3 coord = gl_GlobalInvocationID; + if (coord.x >= pc.dim.x || coord.y >= pc.dim.y || coord.z >= pc.dim.z) { + return; + } + + uvec3 pos = coord + pc.origin; + pos.x <<= pc.bytes_per_block_log2; + + uint swizzle = SwizzleOffset(pos.xy); + uint block_y = pos.y >> GOB_SIZE_Y_SHIFT; + + uint offset = 0u; + offset += pos.z * pc.layer_stride; + offset += (block_y >> pc.block_height) * pc.block_size; + offset += (block_y & pc.block_height_mask) << GOB_SIZE_SHIFT; + offset += (pos.x >> GOB_SIZE_X_SHIFT) << pc.x_shift; + offset += swizzle; + + uvec4 texel = ReadTexel(offset); + + uint words = 1u << (pc.bytes_per_block_log2 - 2u); + uint linear_index = coord.x + coord.y * pc.dim.x + coord.z * pc.dim.x * pc.dim.y; + uint out_idx = linear_index * words; + + out_u32[out_idx] = texel.x; + if (words > 1u) { + out_u32[out_idx + 1u] = texel.y; + } + if (words > 2u) { + out_u32[out_idx + 2u] = texel.z; + out_u32[out_idx + 3u] = texel.w; + } +} diff --git a/src/video_core/host_shaders/block_linear_unswizzle_3d_buffer.comp b/src/video_core/host_shaders/block_linear_unswizzle_3d_buffer.comp new file mode 100644 index 0000000000..7333568eb7 --- /dev/null +++ b/src/video_core/host_shaders/block_linear_unswizzle_3d_buffer.comp @@ -0,0 +1,105 @@ +// SPDX-FileCopyrightText: Copyright 2026 Eden Emulator Project +// SPDX-License-Identifier: GPL-3.0-or-later + +#version 430 + +#define BINDING_INPUT_BUFFER 0 +#define BINDING_OUTPUT_BUFFER 1 + +layout(push_constant) uniform PushConstants { + uvec3 dim; + uint bytes_per_block_log2; + + uvec3 origin; + uint slice_size; + + uint block_size; + uint x_shift; + uint block_height; + uint block_height_mask; + + uint block_depth; + uint block_depth_mask; +} pc; + +layout(binding = BINDING_INPUT_BUFFER, std430) buffer InputBufferU32 { uint u32data[]; }; +layout(binding = BINDING_INPUT_BUFFER, std430) buffer InputBufferU64 { uvec2 u64data[]; }; +layout(binding = BINDING_INPUT_BUFFER, std430) buffer InputBufferU128 { uvec4 u128data[]; }; + +layout(binding = BINDING_OUTPUT_BUFFER, std430) writeonly buffer OutputBuffer { + uint out_u32[]; +}; + +layout(local_size_x = 8, local_size_y = 8, local_size_z = 4) in; + +const uint GOB_SIZE_X = 64; +const uint GOB_SIZE_Y = 8; + +const uint GOB_SIZE_X_SHIFT = 6; +const uint GOB_SIZE_Y_SHIFT = 3; +const uint GOB_SIZE_SHIFT = GOB_SIZE_X_SHIFT + GOB_SIZE_Y_SHIFT; + +const uvec2 SWIZZLE_MASK = uvec2(GOB_SIZE_X - 1u, GOB_SIZE_Y - 1u); + +uint SwizzleTable(uint pos) { + const uint t[8] = uint[]( + 0x12100200, 0x13110301, 0x16140604, 0x17150705, + 0x1a180a08, 0x1b190b09, 0x1e1c0e0c, 0x1f1d0f0d + ); + const uint i = pos >> 4; + const uint h = (t[i / 4] >> ((i % 4) * 8)) & 0xff; + return (h << 4) | (pos & 0xf); +} + +uint SwizzleOffset(uvec2 pos) { + pos = pos & SWIZZLE_MASK; + return SwizzleTable(pos.y * 64u + pos.x); +} + +uvec4 ReadTexel(uint offset) { + switch (pc.bytes_per_block_log2) { + case 2u: + return uvec4(u32data[offset / 4u], 0u, 0u, 0u); + case 3u: + return uvec4(u64data[offset / 8u], 0u, 0u); + case 4u: + return u128data[offset / 16u]; + } + return uvec4(0u); +} + +void main() { + uvec3 coord = gl_GlobalInvocationID; + if (coord.x >= pc.dim.x || coord.y >= pc.dim.y || coord.z >= pc.dim.z) { + return; + } + + uvec3 pos = coord + pc.origin; + pos.x <<= pc.bytes_per_block_log2; + + uint swizzle = SwizzleOffset(pos.xy); + uint block_y = pos.y >> GOB_SIZE_Y_SHIFT; + + uint offset = 0u; + offset += (pos.z >> pc.block_depth) * pc.slice_size; + offset += (pos.z & pc.block_depth_mask) << (GOB_SIZE_SHIFT + pc.block_height); + offset += (block_y >> pc.block_height) * pc.block_size; + offset += (block_y & pc.block_height_mask) << GOB_SIZE_SHIFT; + offset += (pos.x >> GOB_SIZE_X_SHIFT) << pc.x_shift; + offset += swizzle; + + uvec4 texel = ReadTexel(offset); + + uint words = 1u << (pc.bytes_per_block_log2 - 2u); + uint linear_index = coord.x + coord.y * pc.dim.x + coord.z * pc.dim.x * pc.dim.y; + uint out_idx = linear_index * words; + + out_u32[out_idx] = texel.x; + if (words > 1u) { + out_u32[out_idx + 1u] = texel.y; + } + if (words > 2u) { + out_u32[out_idx + 2u] = texel.z; + out_u32[out_idx + 3u] = texel.w; + } +} diff --git a/src/video_core/renderer_vulkan/vk_buffer_cache.cpp b/src/video_core/renderer_vulkan/vk_buffer_cache.cpp index 791a0d8a4f..00ad235513 100644 --- a/src/video_core/renderer_vulkan/vk_buffer_cache.cpp +++ b/src/video_core/renderer_vulkan/vk_buffer_cache.cpp @@ -767,25 +767,6 @@ bool BufferCacheRuntime::BindMultiRangeStorageBuffer(u64 key, bool is_written) { return true; } -bool BufferCacheRuntime::IsUnifiedIndexRange(PrimitiveTopology topology, IndexFormat index_format, - u64 offset) const { - const VkIndexType vk_index_type = MaxwellToVK::IndexFormat(index_format); - const bool needs_uint8_pass = - vk_index_type == VK_INDEX_TYPE_UINT8_EXT && !device.IsExtIndexTypeUint8Supported(); - if (topology == PrimitiveTopology::Quads || topology == PrimitiveTopology::QuadStrip || - needs_uint8_pass) { - return (offset % device.GetStorageBufferAlignment()) == 0; - } - switch (vk_index_type) { - case VK_INDEX_TYPE_UINT32: - return (offset % 4) == 0; - case VK_INDEX_TYPE_UINT16: - return (offset % 2) == 0; - default: - return true; - } -} - void BufferCacheRuntime::BindIndexBuffer(PrimitiveTopology topology, IndexFormat index_format, u32 base_vertex, u32 num_indices, VkBuffer buffer, u32 offset, [[maybe_unused]] u32 size) { @@ -861,11 +842,6 @@ void BufferCacheRuntime::BindVertexBuffer(u32 index, VkBuffer buffer, u32 offset void BufferCacheRuntime::BindVertexBuffers(VideoCommon::HostBindings& bindings) { boost::container::static_vector buffer_handles(bindings.buffers.size()); for (u32 i = 0; i < bindings.buffers.size(); ++i) { - if (i < bindings.unified_windows.size() && - bindings.unified_windows[i] != VideoCommon::NO_UNIFIED_WINDOW) { - buffer_handles[i] = unified_memory->GetWindowBuffer(bindings.unified_windows[i]); - continue; - } auto handle = bindings.buffers[i]->Handle(); if (handle == VK_NULL_HANDLE) { bindings.offsets[i] = 0; diff --git a/src/video_core/renderer_vulkan/vk_buffer_cache.h b/src/video_core/renderer_vulkan/vk_buffer_cache.h index 9f42c21496..9e391e6bb2 100644 --- a/src/video_core/renderer_vulkan/vk_buffer_cache.h +++ b/src/video_core/renderer_vulkan/vk_buffer_cache.h @@ -269,9 +269,6 @@ public: (offset % device.GetStorageBufferAlignment()) == 0; } - [[nodiscard]] bool IsUnifiedIndexRange(PrimitiveTopology topology, IndexFormat index_format, - u64 offset) const; - void BindTextureBuffer(Buffer& buffer, u32 offset, u32 size, VideoCore::Surface::PixelFormat format) { guest_descriptor_queue.AddTexelBuffer(buffer.View(offset, size, format), diff --git a/src/video_core/renderer_vulkan/vk_compute_pass.cpp b/src/video_core/renderer_vulkan/vk_compute_pass.cpp index ab58560170..2d3d4a2ee0 100644 --- a/src/video_core/renderer_vulkan/vk_compute_pass.cpp +++ b/src/video_core/renderer_vulkan/vk_compute_pass.cpp @@ -22,7 +22,9 @@ #include "video_core/host_shaders/resolve_conditional_render_comp_spv.h" #include "video_core/host_shaders/vulkan_quad_indexed_comp_spv.h" #include "video_core/host_shaders/vulkan_uint8_comp_spv.h" +#include "video_core/host_shaders/block_linear_unswizzle_2d_buffer_comp_spv.h" #include "video_core/host_shaders/block_linear_unswizzle_3d_bcn_comp_spv.h" +#include "video_core/host_shaders/block_linear_unswizzle_3d_buffer_comp_spv.h" #include "video_core/renderer_vulkan/vk_compute_pass.h" #include "video_core/surface.h" #include "video_core/renderer_vulkan/vk_descriptor_pool.h" @@ -872,4 +874,480 @@ void BlockLinearUnswizzle3DPass::UnswizzleChunk( }); } +namespace { +constexpr u32 BL2D_BINDING_INPUT_BUFFER = 0; +constexpr u32 BL2D_BINDING_OUTPUT_BUFFER = 1; + +struct alignas(16) BlockLinearUnswizzle2DPushConstants { + std::array dim; + u32 bytes_per_block_log2; + std::array origin; + u32 layer_stride; + u32 block_size; + u32 x_shift; + u32 block_height; + u32 block_height_mask; +}; +static_assert(sizeof(BlockLinearUnswizzle2DPushConstants) <= 128); + +constexpr std::array BL2D_BINDINGS{{ + { + .binding = BL2D_BINDING_INPUT_BUFFER, + .descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, + .descriptorCount = 1, + .stageFlags = VK_SHADER_STAGE_COMPUTE_BIT, + .pImmutableSamplers = nullptr, + }, + { + .binding = BL2D_BINDING_OUTPUT_BUFFER, + .descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, + .descriptorCount = 1, + .stageFlags = VK_SHADER_STAGE_COMPUTE_BIT, + .pImmutableSamplers = nullptr, + }, +}}; + +constexpr std::array BL2D_TEMPLATE{{ + { + .dstBinding = BL2D_BINDING_INPUT_BUFFER, + .dstArrayElement = 0, + .descriptorCount = 1, + .descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, + .offset = BL2D_BINDING_INPUT_BUFFER * sizeof(DescriptorUpdateEntry), + .stride = sizeof(DescriptorUpdateEntry), + }, + { + .dstBinding = BL2D_BINDING_OUTPUT_BUFFER, + .dstArrayElement = 0, + .descriptorCount = 1, + .descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, + .offset = BL2D_BINDING_OUTPUT_BUFFER * sizeof(DescriptorUpdateEntry), + .stride = sizeof(DescriptorUpdateEntry), + }, +}}; + +constexpr DescriptorBankInfo BL2D_BANK_INFO{ + .uniform_buffers = 0, + .storage_buffers = 2, + .texture_buffers = 0, + .image_buffers = 0, + .textures = 0, + .images = 0, + .score = 2, +}; +} // Anonymous namespace + +BlockLinearUnswizzle2DPass::BlockLinearUnswizzle2DPass( + const Device& device_, Scheduler& scheduler_, DescriptorPool& descriptor_pool_, + StagingBufferPool& staging_buffer_pool_, + ComputePassDescriptorQueue& compute_pass_descriptor_queue_) + : ComputePass(device_, scheduler_, descriptor_pool_, BL2D_BINDINGS, BL2D_TEMPLATE, + BL2D_BANK_INFO, + COMPUTE_PUSH_CONSTANT_RANGE, + BLOCK_LINEAR_UNSWIZZLE_2D_BUFFER_COMP_SPV), + scheduler{scheduler_}, staging_buffer_pool{staging_buffer_pool_}, + compute_pass_descriptor_queue{compute_pass_descriptor_queue_} {} + +BlockLinearUnswizzle2DPass::~BlockLinearUnswizzle2DPass() = default; + +bool BlockLinearUnswizzle2DPass::IsSupported(const Device& device, + const VideoCommon::ImageInfo& info) { + if (info.type != VideoCommon::ImageType::e2D) { + return false; + } + if (info.resources.levels != 1 || info.resources.layers != 1) { + return false; + } + if (info.num_samples > 1) { + return false; + } + if (VideoCore::Surface::IsPixelFormatASTC(info.format) && !device.IsOptimalAstcSupported()) { + return false; + } + if (VideoCore::Surface::IsPixelFormatBCn(info.format) && !device.IsOptimalBcnSupported()) { + return false; + } + const u32 bytes_per_block = VideoCore::Surface::BytesPerBlock(info.format); + return bytes_per_block == 4 || bytes_per_block == 8 || bytes_per_block == 16; +} + +void BlockLinearUnswizzle2DPass::Unswizzle( + Image& image, const StagingBufferRef& swizzled, + std::span swizzles) { + if (swizzles.empty()) { + return; + } + const VideoCommon::SwizzleParameters& sw = swizzles.front(); + const auto params = VideoCommon::Accelerated::MakeBlockLinearSwizzle2DParams(sw, image.info); + + const u32 width = sw.num_tiles.width; + const u32 height = sw.num_tiles.height; + const u32 texel_width = image.info.size.width; + const u32 texel_height = image.info.size.height; + const u32 depth = image.info.resources.layers; + const u32 bytes_per_block = 1u << params.bytes_per_block_log2; + const VkDeviceSize output_size = + static_cast(width) * height * depth * bytes_per_block; + + const StagingBufferRef output = + staging_buffer_pool.Request(static_cast(output_size), MemoryUsage::DeviceLocal); + + BlockLinearUnswizzle2DPushConstants pc{}; + pc.dim = {width, height, depth}; + pc.bytes_per_block_log2 = params.bytes_per_block_log2; + pc.origin = params.origin; + pc.layer_stride = params.layer_stride; + pc.block_size = params.block_size; + pc.x_shift = params.x_shift; + pc.block_height = params.block_height; + pc.block_height_mask = params.block_height_mask; + + scheduler.RequestOutsideRenderPassOperationContext(); + + compute_pass_descriptor_queue.Acquire(scheduler, 2); + compute_pass_descriptor_queue.AddBuffer(swizzled.buffer, sw.buffer_offset + swizzled.offset, + image.guest_size_bytes - sw.buffer_offset); + compute_pass_descriptor_queue.AddBuffer(output.buffer, output.offset, output_size); + + const void* descriptor_data = compute_pass_descriptor_queue.UpdateData(); + const VkDescriptorSet set = descriptor_allocator.Commit(); + + const u32 gx = Common::DivCeil(width, 16u); + const u32 gy = Common::DivCeil(height, 8u); + const bool is_initialized = image.ExchangeInitialization(); + + const VkBuffer out_buffer = output.buffer; + const VkDeviceSize out_offset = output.offset; + const VkImage dst_image = image.Handle(); + const VkImageAspectFlags aspect = image.AspectMask(); + + scheduler.Record([this, set, descriptor_data, pc, gx, gy, depth, output_size, out_buffer, + out_offset, dst_image, aspect, width, height, + is_initialized](vk::CommandBuffer cmdbuf) { + if (dst_image == VK_NULL_HANDLE || out_buffer == VK_NULL_HANDLE) { + return; + } + device.GetLogical().UpdateDescriptorSet(set, *descriptor_template, descriptor_data); + cmdbuf.BindPipeline(VK_PIPELINE_BIND_POINT_COMPUTE, *pipeline); + cmdbuf.BindDescriptorSets(VK_PIPELINE_BIND_POINT_COMPUTE, *layout, 0, set, {}); + cmdbuf.PushConstants(*layout, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(pc), &pc); + cmdbuf.Dispatch(gx, gy, depth); + + const VkBufferMemoryBarrier buffer_barrier{ + .sType = VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER, + .pNext = nullptr, + .srcAccessMask = VK_ACCESS_SHADER_WRITE_BIT, + .dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT, + .srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, + .dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, + .buffer = out_buffer, + .offset = out_offset, + .size = output_size, + }; + const VkImageMemoryBarrier pre_copy{ + .sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, + .pNext = nullptr, + .srcAccessMask = static_cast(is_initialized ? VK_ACCESS_SHADER_READ_BIT + : VK_ACCESS_NONE), + .dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT, + .oldLayout = is_initialized ? VK_IMAGE_LAYOUT_GENERAL : VK_IMAGE_LAYOUT_UNDEFINED, + .newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, + .srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, + .dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, + .image = dst_image, + .subresourceRange{ + .aspectMask = aspect, + .baseMipLevel = 0, + .levelCount = VK_REMAINING_MIP_LEVELS, + .baseArrayLayer = 0, + .layerCount = VK_REMAINING_ARRAY_LAYERS, + }, + }; + cmdbuf.PipelineBarrier(VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT | + (is_initialized ? vk::PIPELINE_STAGE_GRAPHICS_COMPUTE + : VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT), + VK_PIPELINE_STAGE_TRANSFER_BIT, 0, {}, buffer_barrier, pre_copy); + + const VkBufferImageCopy copy{ + .bufferOffset = out_offset, + .bufferRowLength = 0, + .bufferImageHeight = 0, + .imageSubresource{ + .aspectMask = aspect, + .mipLevel = 0, + .baseArrayLayer = 0, + .layerCount = depth, + }, + .imageOffset = {0, 0, 0}, + .imageExtent = {texel_width, texel_height, 1}, + }; + cmdbuf.CopyBufferToImage(out_buffer, dst_image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, copy); + + const VkImageMemoryBarrier post_copy{ + .sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, + .pNext = nullptr, + .srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT, + .dstAccessMask = VK_ACCESS_SHADER_READ_BIT, + .oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, + .newLayout = VK_IMAGE_LAYOUT_GENERAL, + .srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, + .dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, + .image = dst_image, + .subresourceRange{ + .aspectMask = aspect, + .baseMipLevel = 0, + .levelCount = VK_REMAINING_MIP_LEVELS, + .baseArrayLayer = 0, + .layerCount = VK_REMAINING_ARRAY_LAYERS, + }, + }; + cmdbuf.PipelineBarrier(VK_PIPELINE_STAGE_TRANSFER_BIT, vk::PIPELINE_STAGE_GRAPHICS_COMPUTE, + 0, {}, {}, post_copy); + }); +} + +namespace { +constexpr u32 BL3DB_BINDING_INPUT_BUFFER = 0; +constexpr u32 BL3DB_BINDING_OUTPUT_BUFFER = 1; + +struct alignas(16) BlockLinearUnswizzle3DBufferPushConstants { + std::array dim; + u32 bytes_per_block_log2; + std::array origin; + u32 slice_size; + u32 block_size; + u32 x_shift; + u32 block_height; + u32 block_height_mask; + u32 block_depth; + u32 block_depth_mask; +}; +static_assert(sizeof(BlockLinearUnswizzle3DBufferPushConstants) <= 128); + +constexpr std::array BL3DB_BINDINGS{{ + { + .binding = BL3DB_BINDING_INPUT_BUFFER, + .descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, + .descriptorCount = 1, + .stageFlags = VK_SHADER_STAGE_COMPUTE_BIT, + .pImmutableSamplers = nullptr, + }, + { + .binding = BL3DB_BINDING_OUTPUT_BUFFER, + .descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, + .descriptorCount = 1, + .stageFlags = VK_SHADER_STAGE_COMPUTE_BIT, + .pImmutableSamplers = nullptr, + }, +}}; + +constexpr std::array BL3DB_TEMPLATE{{ + { + .dstBinding = BL3DB_BINDING_INPUT_BUFFER, + .dstArrayElement = 0, + .descriptorCount = 1, + .descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, + .offset = BL3DB_BINDING_INPUT_BUFFER * sizeof(DescriptorUpdateEntry), + .stride = sizeof(DescriptorUpdateEntry), + }, + { + .dstBinding = BL3DB_BINDING_OUTPUT_BUFFER, + .dstArrayElement = 0, + .descriptorCount = 1, + .descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, + .offset = BL3DB_BINDING_OUTPUT_BUFFER * sizeof(DescriptorUpdateEntry), + .stride = sizeof(DescriptorUpdateEntry), + }, +}}; + +constexpr DescriptorBankInfo BL3DB_BANK_INFO{ + .uniform_buffers = 0, + .storage_buffers = 2, + .texture_buffers = 0, + .image_buffers = 0, + .textures = 0, + .images = 0, + .score = 2, +}; +} // Anonymous namespace + +BlockLinearUnswizzle3DBufferPass::BlockLinearUnswizzle3DBufferPass( + const Device& device_, Scheduler& scheduler_, DescriptorPool& descriptor_pool_, + StagingBufferPool& staging_buffer_pool_, + ComputePassDescriptorQueue& compute_pass_descriptor_queue_) + : ComputePass(device_, scheduler_, descriptor_pool_, BL3DB_BINDINGS, BL3DB_TEMPLATE, + BL3DB_BANK_INFO, + COMPUTE_PUSH_CONSTANT_RANGE, + BLOCK_LINEAR_UNSWIZZLE_3D_BUFFER_COMP_SPV), + scheduler{scheduler_}, staging_buffer_pool{staging_buffer_pool_}, + compute_pass_descriptor_queue{compute_pass_descriptor_queue_} {} + +BlockLinearUnswizzle3DBufferPass::~BlockLinearUnswizzle3DBufferPass() = default; + +bool BlockLinearUnswizzle3DBufferPass::IsSupported(const Device& device, + const VideoCommon::ImageInfo& info) { + if (info.type != VideoCommon::ImageType::e3D) { + return false; + } + if (info.resources.levels != 1 || info.resources.layers != 1) { + return false; + } + if (info.num_samples > 1) { + return false; + } + if (info.size.depth <= 1) { + return false; + } + if (VideoCore::Surface::IsPixelFormatASTC(info.format)) { + return false; + } + if (VideoCore::Surface::IsPixelFormatBCn(info.format) && !device.IsOptimalBcnSupported()) { + return false; + } + const u32 bytes_per_block = VideoCore::Surface::BytesPerBlock(info.format); + return bytes_per_block == 4 || bytes_per_block == 8 || bytes_per_block == 16; +} + +void BlockLinearUnswizzle3DBufferPass::Unswizzle( + Image& image, const StagingBufferRef& swizzled, + std::span swizzles) { + if (swizzles.empty()) { + return; + } + + const VideoCommon::SwizzleParameters& sw = swizzles.front(); + const auto params = VideoCommon::Accelerated::MakeBlockLinearSwizzle3DParams(sw, image.info); + + const u32 blocks_x = sw.num_tiles.width; + const u32 blocks_y = sw.num_tiles.height; + const u32 blocks_z = sw.num_tiles.depth; + const u32 bytes_per_block = 1u << params.bytes_per_block_log2; + const VkDeviceSize output_size = + static_cast(blocks_x) * blocks_y * blocks_z * bytes_per_block; + + const StagingBufferRef output = + staging_buffer_pool.Request(static_cast(output_size), MemoryUsage::DeviceLocal); + + BlockLinearUnswizzle3DBufferPushConstants pc{}; + pc.dim = {blocks_x, blocks_y, blocks_z}; + pc.bytes_per_block_log2 = params.bytes_per_block_log2; + pc.origin = params.origin; + pc.slice_size = params.slice_size; + pc.block_size = params.block_size; + pc.x_shift = params.x_shift; + pc.block_height = params.block_height; + pc.block_height_mask = params.block_height_mask; + pc.block_depth = params.block_depth; + pc.block_depth_mask = params.block_depth_mask; + + scheduler.RequestOutsideRenderPassOperationContext(); + + compute_pass_descriptor_queue.Acquire(scheduler, 2); + compute_pass_descriptor_queue.AddBuffer(swizzled.buffer, sw.buffer_offset + swizzled.offset, + image.guest_size_bytes - sw.buffer_offset); + compute_pass_descriptor_queue.AddBuffer(output.buffer, output.offset, output_size); + + const void* descriptor_data = compute_pass_descriptor_queue.UpdateData(); + const VkDescriptorSet set = descriptor_allocator.Commit(); + + const u32 gx = Common::DivCeil(blocks_x, 8u); + const u32 gy = Common::DivCeil(blocks_y, 8u); + const u32 gz = Common::DivCeil(blocks_z, 4u); + const bool is_initialized = image.ExchangeInitialization(); + + const VkBuffer out_buffer = output.buffer; + const VkDeviceSize out_offset = output.offset; + const VkImage dst_image = image.Handle(); + const VkImageAspectFlags aspect = image.AspectMask(); + const VkExtent3D extent{ + .width = image.info.size.width, + .height = image.info.size.height, + .depth = image.info.size.depth, + }; + + scheduler.Record([this, set, descriptor_data, pc, gx, gy, gz, output_size, out_buffer, + out_offset, dst_image, aspect, extent, + is_initialized](vk::CommandBuffer cmdbuf) { + if (dst_image == VK_NULL_HANDLE || out_buffer == VK_NULL_HANDLE) { + return; + } + device.GetLogical().UpdateDescriptorSet(set, *descriptor_template, descriptor_data); + cmdbuf.BindPipeline(VK_PIPELINE_BIND_POINT_COMPUTE, *pipeline); + cmdbuf.BindDescriptorSets(VK_PIPELINE_BIND_POINT_COMPUTE, *layout, 0, set, {}); + cmdbuf.PushConstants(*layout, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(pc), &pc); + cmdbuf.Dispatch(gx, gy, gz); + + const VkBufferMemoryBarrier buffer_barrier{ + .sType = VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER, + .pNext = nullptr, + .srcAccessMask = VK_ACCESS_SHADER_WRITE_BIT, + .dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT, + .srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, + .dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, + .buffer = out_buffer, + .offset = out_offset, + .size = output_size, + }; + const VkImageMemoryBarrier pre_copy{ + .sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, + .pNext = nullptr, + .srcAccessMask = static_cast(is_initialized ? VK_ACCESS_SHADER_READ_BIT + : VK_ACCESS_NONE), + .dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT, + .oldLayout = is_initialized ? VK_IMAGE_LAYOUT_GENERAL : VK_IMAGE_LAYOUT_UNDEFINED, + .newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, + .srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, + .dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, + .image = dst_image, + .subresourceRange{ + .aspectMask = aspect, + .baseMipLevel = 0, + .levelCount = VK_REMAINING_MIP_LEVELS, + .baseArrayLayer = 0, + .layerCount = VK_REMAINING_ARRAY_LAYERS, + }, + }; + cmdbuf.PipelineBarrier(VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT | + (is_initialized ? vk::PIPELINE_STAGE_GRAPHICS_COMPUTE + : VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT), + VK_PIPELINE_STAGE_TRANSFER_BIT, 0, {}, buffer_barrier, pre_copy); + + const VkBufferImageCopy copy{ + .bufferOffset = out_offset, + .bufferRowLength = 0, + .bufferImageHeight = 0, + .imageSubresource{ + .aspectMask = aspect, + .mipLevel = 0, + .baseArrayLayer = 0, + .layerCount = 1, + }, + .imageOffset = {0, 0, 0}, + .imageExtent = extent, + }; + cmdbuf.CopyBufferToImage(out_buffer, dst_image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, copy); + + const VkImageMemoryBarrier post_copy{ + .sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, + .pNext = nullptr, + .srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT, + .dstAccessMask = VK_ACCESS_SHADER_READ_BIT, + .oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, + .newLayout = VK_IMAGE_LAYOUT_GENERAL, + .srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, + .dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, + .image = dst_image, + .subresourceRange{ + .aspectMask = aspect, + .baseMipLevel = 0, + .levelCount = VK_REMAINING_MIP_LEVELS, + .baseArrayLayer = 0, + .layerCount = VK_REMAINING_ARRAY_LAYERS, + }, + }; + cmdbuf.PipelineBarrier(VK_PIPELINE_STAGE_TRANSFER_BIT, vk::PIPELINE_STAGE_GRAPHICS_COMPUTE, + 0, {}, {}, post_copy); + }); +} + } // namespace Vulkan diff --git a/src/video_core/renderer_vulkan/vk_compute_pass.h b/src/video_core/renderer_vulkan/vk_compute_pass.h index 3d30aa6bdc..c08d8724f6 100644 --- a/src/video_core/renderer_vulkan/vk_compute_pass.h +++ b/src/video_core/renderer_vulkan/vk_compute_pass.h @@ -164,4 +164,43 @@ private: ComputePassDescriptorQueue& compute_pass_descriptor_queue; }; +class BlockLinearUnswizzle2DPass final : public ComputePass { +public: + explicit BlockLinearUnswizzle2DPass(const Device& device_, Scheduler& scheduler_, + DescriptorPool& descriptor_pool_, + StagingBufferPool& staging_buffer_pool_, + ComputePassDescriptorQueue& compute_pass_descriptor_queue_); + ~BlockLinearUnswizzle2DPass(); + + [[nodiscard]] static bool IsSupported(const Device& device, + const VideoCommon::ImageInfo& info); + + void Unswizzle(Image& image, const StagingBufferRef& swizzled, + std::span swizzles); + +private: + Scheduler& scheduler; + StagingBufferPool& staging_buffer_pool; + ComputePassDescriptorQueue& compute_pass_descriptor_queue; +}; + +class BlockLinearUnswizzle3DBufferPass final : public ComputePass { +public: + explicit BlockLinearUnswizzle3DBufferPass( + const Device& device_, Scheduler& scheduler_, DescriptorPool& descriptor_pool_, + StagingBufferPool& staging_buffer_pool_, + ComputePassDescriptorQueue& compute_pass_descriptor_queue_); + ~BlockLinearUnswizzle3DBufferPass(); + + [[nodiscard]] static bool IsSupported(const Device& device, const VideoCommon::ImageInfo& info); + + void Unswizzle(Image& image, const StagingBufferRef& swizzled, + std::span swizzles); + +private: + Scheduler& scheduler; + StagingBufferPool& staging_buffer_pool; + ComputePassDescriptorQueue& compute_pass_descriptor_queue; +}; + } // namespace Vulkan diff --git a/src/video_core/renderer_vulkan/vk_texture_cache.cpp b/src/video_core/renderer_vulkan/vk_texture_cache.cpp index c3f56408b5..5d3bad180c 100644 --- a/src/video_core/renderer_vulkan/vk_texture_cache.cpp +++ b/src/video_core/renderer_vulkan/vk_texture_cache.cpp @@ -968,6 +968,10 @@ TextureCacheRuntime::TextureCacheRuntime(const Device& device_, Scheduler& sched bl3d_unswizzle_pass.emplace(device, scheduler, descriptor_pool, staging_buffer_pool, compute_pass_descriptor_queue); } + bl2d_unswizzle_pass.emplace(device, scheduler, descriptor_pool, staging_buffer_pool, + compute_pass_descriptor_queue); + bl3db_unswizzle_pass.emplace(device, scheduler, descriptor_pool, staging_buffer_pool, + compute_pass_descriptor_queue); } void TextureCacheRuntime::Finish() { @@ -1894,6 +1898,14 @@ Image::Image(TextureCacheRuntime& runtime_, const ImageInfo& info_, GPUVAddr gpu } flags |= VideoCommon::ImageFlagBits::Converted; flags |= VideoCommon::ImageFlagBits::CostlyLoad; + } else if (runtime->bl2d_unswizzle_pass && + BlockLinearUnswizzle2DPass::IsSupported(runtime->device, info)) { + flags |= VideoCommon::ImageFlagBits::AcceleratedUpload; + flags |= VideoCommon::ImageFlagBits::CostlyLoad; + } else if (runtime->bl3db_unswizzle_pass && + BlockLinearUnswizzle3DBufferPass::IsSupported(runtime->device, info)) { + flags |= VideoCommon::ImageFlagBits::AcceleratedUpload; + flags |= VideoCommon::ImageFlagBits::CostlyLoad; } if (IsPixelFormatBCn(info.format) && !runtime->device.IsOptimalBcnSupported()) { flags |= VideoCommon::ImageFlagBits::Converted; @@ -3141,6 +3153,15 @@ void TextureCacheRuntime::AccelerateImageUpload( return astc_decoder_pass->Assemble(image, map, swizzles); } + if (bl2d_unswizzle_pass && BlockLinearUnswizzle2DPass::IsSupported(device, image.info)) { + return bl2d_unswizzle_pass->Unswizzle(image, map, swizzles); + } + + if (bl3db_unswizzle_pass && + BlockLinearUnswizzle3DBufferPass::IsSupported(device, image.info)) { + return bl3db_unswizzle_pass->Unswizzle(image, map, swizzles); + } + if (!Settings::values.gpu_unswizzle_enabled.GetValue() || !bl3d_unswizzle_pass) { if (IsPixelFormatBCn(image.info.format) && image.info.type == ImageType::e3D) { ASSERT(false && "GPU unswizzle is disabled for BCn 3D texture"); diff --git a/src/video_core/renderer_vulkan/vk_texture_cache.h b/src/video_core/renderer_vulkan/vk_texture_cache.h index 68bf2af991..1cd786edcf 100644 --- a/src/video_core/renderer_vulkan/vk_texture_cache.h +++ b/src/video_core/renderer_vulkan/vk_texture_cache.h @@ -159,6 +159,8 @@ public: std::optional astc_decoder_pass; std::optional bl3d_unswizzle_pass; + std::optional bl2d_unswizzle_pass; + std::optional bl3db_unswizzle_pass; const Settings::ResolutionScalingInfo& resolution; std::array, VideoCore::Surface::MaxPixelFormat> view_formats; From 32c76f1e0a9013658f9985468a8d303ff111dd91 Mon Sep 17 00:00:00 2001 From: CamilleLaVey Date: Wed, 26 Aug 2026 14:50:42 -0400 Subject: [PATCH 15/27] Fix msvc build --- src/video_core/vulkan_common/vulkan_device.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/video_core/vulkan_common/vulkan_device.cpp b/src/video_core/vulkan_common/vulkan_device.cpp index d36c6b85e1..c02da355d5 100644 --- a/src/video_core/vulkan_common/vulkan_device.cpp +++ b/src/video_core/vulkan_common/vulkan_device.cpp @@ -1683,8 +1683,8 @@ void Device::CollectPhysicalMemoryInfo() { if (committed_backing != 0) { LOG_INFO(Render_Vulkan, "Discounting {} MiB of guest memory committed by the host", committed_backing >> 20); - local_memory -= std::min(local_memory, committed_backing); - device_access_memory -= std::min(device_access_memory, committed_backing); + local_memory -= (std::min)(local_memory, committed_backing); + device_access_memory -= (std::min)(device_access_memory, committed_backing); } if (is_integrated) { const s64 available_memory = static_cast(device_access_memory - device_initial_usage); From ea3de6ee81bf273f2b46b0738fc6e06cb48cab44 Mon Sep 17 00:00:00 2001 From: CamilleLaVey Date: Wed, 26 Aug 2026 15:04:18 -0400 Subject: [PATCH 16/27] Fix build --- src/video_core/renderer_vulkan/vk_compute_pass.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/video_core/renderer_vulkan/vk_compute_pass.cpp b/src/video_core/renderer_vulkan/vk_compute_pass.cpp index 2d3d4a2ee0..7b128a9234 100644 --- a/src/video_core/renderer_vulkan/vk_compute_pass.cpp +++ b/src/video_core/renderer_vulkan/vk_compute_pass.cpp @@ -1022,7 +1022,7 @@ void BlockLinearUnswizzle2DPass::Unswizzle( const VkImageAspectFlags aspect = image.AspectMask(); scheduler.Record([this, set, descriptor_data, pc, gx, gy, depth, output_size, out_buffer, - out_offset, dst_image, aspect, width, height, + out_offset, dst_image, aspect, texel_width, texel_height, is_initialized](vk::CommandBuffer cmdbuf) { if (dst_image == VK_NULL_HANDLE || out_buffer == VK_NULL_HANDLE) { return; From 122afb04f7549760d9b7b8508132fb507e3187d1 Mon Sep 17 00:00:00 2001 From: CamilleLaVey Date: Wed, 26 Aug 2026 17:00:18 -0400 Subject: [PATCH 17/27] Adjustments on upload for textures --- .../renderer_opengl/gl_texture_cache.h | 1 + .../renderer_vulkan/vk_buffer_cache.cpp | 7 +- .../renderer_vulkan/vk_buffer_cache.h | 2 +- .../renderer_vulkan/vk_compute_pass.cpp | 201 ++++++++++-------- .../renderer_vulkan/vk_compute_pass.h | 3 + .../renderer_vulkan/vk_texture_cache.cpp | 62 +++++- .../renderer_vulkan/vk_texture_cache.h | 16 ++ src/video_core/texture_cache/image_base.h | 2 + src/video_core/texture_cache/texture_cache.h | 52 +++++ .../texture_cache/texture_cache_base.h | 3 + .../vulkan_common/vulkan_memory_allocator.cpp | 11 + .../vulkan_common/vulkan_memory_allocator.h | 10 + 12 files changed, 277 insertions(+), 93 deletions(-) diff --git a/src/video_core/renderer_opengl/gl_texture_cache.h b/src/video_core/renderer_opengl/gl_texture_cache.h index 8a830fa0c9..b0731f3381 100644 --- a/src/video_core/renderer_opengl/gl_texture_cache.h +++ b/src/video_core/renderer_opengl/gl_texture_cache.h @@ -373,6 +373,7 @@ struct TextureCacheParams { static constexpr bool HAS_DEVICE_MEMORY_INFO = true; static constexpr bool IMPLEMENTS_ASYNC_DOWNLOADS = true; static constexpr bool HAS_MSAA_DOWNLOADS = false; + static constexpr bool USE_UNIFIED_MEMORY = false; using Runtime = OpenGL::TextureCacheRuntime; using Image = OpenGL::Image; diff --git a/src/video_core/renderer_vulkan/vk_buffer_cache.cpp b/src/video_core/renderer_vulkan/vk_buffer_cache.cpp index 00ad235513..595acab8da 100644 --- a/src/video_core/renderer_vulkan/vk_buffer_cache.cpp +++ b/src/video_core/renderer_vulkan/vk_buffer_cache.cpp @@ -433,11 +433,8 @@ void BufferCacheRuntime::TryEnableUnifiedMemory(void* base, size_t size, std::span hardware_buffers, size_t hardware_buffer_window, size_t hardware_buffer_base) { - unified_memory = std::make_unique( - device, base, size, hardware_buffers, hardware_buffer_window, hardware_buffer_base); - if (!unified_memory->IsValid()) { - unified_memory.reset(); - } + unified_memory = memory_allocator.CreateHostMemoryImport( + base, size, hardware_buffers, hardware_buffer_window, hardware_buffer_base); } void BufferCacheRuntime::CopyToUnifiedMemory( diff --git a/src/video_core/renderer_vulkan/vk_buffer_cache.h b/src/video_core/renderer_vulkan/vk_buffer_cache.h index 9e391e6bb2..2cbbcca140 100644 --- a/src/video_core/renderer_vulkan/vk_buffer_cache.h +++ b/src/video_core/renderer_vulkan/vk_buffer_cache.h @@ -315,7 +315,7 @@ private: std::shared_ptr quad_strip_index_buffer; vk::Buffer null_buffer; - std::unique_ptr unified_memory; + HostMemoryImport* unified_memory{}; boost::container::small_vector pending_unified_copies; std::unique_ptr uint8_pass; diff --git a/src/video_core/renderer_vulkan/vk_compute_pass.cpp b/src/video_core/renderer_vulkan/vk_compute_pass.cpp index 7b128a9234..8bbc280d9c 100644 --- a/src/video_core/renderer_vulkan/vk_compute_pass.cpp +++ b/src/video_core/renderer_vulkan/vk_compute_pass.cpp @@ -4,6 +4,7 @@ // SPDX-FileCopyrightText: Copyright 2019 yuzu Emulator Project // SPDX-License-Identifier: GPL-2.0-or-later +#include #include #include #include @@ -955,10 +956,10 @@ bool BlockLinearUnswizzle2DPass::IsSupported(const Device& device, if (info.type != VideoCommon::ImageType::e2D) { return false; } - if (info.resources.levels != 1 || info.resources.layers != 1) { + if (info.num_samples > 1) { return false; } - if (info.num_samples > 1) { + if (device.GetStorageBufferAlignment() > Tegra::Texture::GOB_SIZE) { return false; } if (VideoCore::Surface::IsPixelFormatASTC(info.format) && !device.IsOptimalAstcSupported()) { @@ -974,83 +975,37 @@ bool BlockLinearUnswizzle2DPass::IsSupported(const Device& device, void BlockLinearUnswizzle2DPass::Unswizzle( Image& image, const StagingBufferRef& swizzled, std::span swizzles) { - if (swizzles.empty()) { + UnswizzleFrom(image, swizzled.buffer, swizzled.offset, swizzles); +} + +void BlockLinearUnswizzle2DPass::UnswizzleFrom( + Image& image, VkBuffer source_buffer, VkDeviceSize source_offset, + std::span swizzles) { + const VkImage dst_image = image.Handle(); + if (swizzles.empty() || source_buffer == VK_NULL_HANDLE || dst_image == VK_NULL_HANDLE) { return; } - const VideoCommon::SwizzleParameters& sw = swizzles.front(); - const auto params = VideoCommon::Accelerated::MakeBlockLinearSwizzle2DParams(sw, image.info); - - const u32 width = sw.num_tiles.width; - const u32 height = sw.num_tiles.height; - const u32 texel_width = image.info.size.width; - const u32 texel_height = image.info.size.height; - const u32 depth = image.info.resources.layers; - const u32 bytes_per_block = 1u << params.bytes_per_block_log2; - const VkDeviceSize output_size = - static_cast(width) * height * depth * bytes_per_block; - - const StagingBufferRef output = - staging_buffer_pool.Request(static_cast(output_size), MemoryUsage::DeviceLocal); - - BlockLinearUnswizzle2DPushConstants pc{}; - pc.dim = {width, height, depth}; - pc.bytes_per_block_log2 = params.bytes_per_block_log2; - pc.origin = params.origin; - pc.layer_stride = params.layer_stride; - pc.block_size = params.block_size; - pc.x_shift = params.x_shift; - pc.block_height = params.block_height; - pc.block_height_mask = params.block_height_mask; + const u32 layers = image.info.resources.layers; + const VkImageAspectFlags aspect = image.AspectMask(); scheduler.RequestOutsideRenderPassOperationContext(); - compute_pass_descriptor_queue.Acquire(scheduler, 2); - compute_pass_descriptor_queue.AddBuffer(swizzled.buffer, sw.buffer_offset + swizzled.offset, - image.guest_size_bytes - sw.buffer_offset); - compute_pass_descriptor_queue.AddBuffer(output.buffer, output.offset, output_size); - - const void* descriptor_data = compute_pass_descriptor_queue.UpdateData(); - const VkDescriptorSet set = descriptor_allocator.Commit(); - - const u32 gx = Common::DivCeil(width, 16u); - const u32 gy = Common::DivCeil(height, 8u); - const bool is_initialized = image.ExchangeInitialization(); - - const VkBuffer out_buffer = output.buffer; - const VkDeviceSize out_offset = output.offset; - const VkImage dst_image = image.Handle(); - const VkImageAspectFlags aspect = image.AspectMask(); - - scheduler.Record([this, set, descriptor_data, pc, gx, gy, depth, output_size, out_buffer, - out_offset, dst_image, aspect, texel_width, texel_height, - is_initialized](vk::CommandBuffer cmdbuf) { - if (dst_image == VK_NULL_HANDLE || out_buffer == VK_NULL_HANDLE) { - return; + VkAccessFlags pre_access = VK_ACCESS_NONE; + VkImageLayout pre_layout = VK_IMAGE_LAYOUT_UNDEFINED; + VkPipelineStageFlags pre_stage = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT; + if (image.ExchangeInitialization()) { + pre_access = VK_ACCESS_SHADER_READ_BIT; + pre_layout = VK_IMAGE_LAYOUT_GENERAL; + pre_stage = vk::PIPELINE_STAGE_GRAPHICS_COMPUTE; } - device.GetLogical().UpdateDescriptorSet(set, *descriptor_template, descriptor_data); - cmdbuf.BindPipeline(VK_PIPELINE_BIND_POINT_COMPUTE, *pipeline); - cmdbuf.BindDescriptorSets(VK_PIPELINE_BIND_POINT_COMPUTE, *layout, 0, set, {}); - cmdbuf.PushConstants(*layout, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(pc), &pc); - cmdbuf.Dispatch(gx, gy, depth); - - const VkBufferMemoryBarrier buffer_barrier{ - .sType = VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER, - .pNext = nullptr, - .srcAccessMask = VK_ACCESS_SHADER_WRITE_BIT, - .dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT, - .srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, - .dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, - .buffer = out_buffer, - .offset = out_offset, - .size = output_size, - }; - const VkImageMemoryBarrier pre_copy{ + scheduler.Record([dst_image, aspect, pre_access, pre_layout, + pre_stage](vk::CommandBuffer cmdbuf) { + const VkImageMemoryBarrier barrier{ .sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .pNext = nullptr, - .srcAccessMask = static_cast(is_initialized ? VK_ACCESS_SHADER_READ_BIT - : VK_ACCESS_NONE), + .srcAccessMask = pre_access, .dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT, - .oldLayout = is_initialized ? VK_IMAGE_LAYOUT_GENERAL : VK_IMAGE_LAYOUT_UNDEFINED, + .oldLayout = pre_layout, .newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, .srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, .dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, @@ -1063,10 +1018,75 @@ void BlockLinearUnswizzle2DPass::Unswizzle( .layerCount = VK_REMAINING_ARRAY_LAYERS, }, }; - cmdbuf.PipelineBarrier(VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT | - (is_initialized ? vk::PIPELINE_STAGE_GRAPHICS_COMPUTE - : VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT), - VK_PIPELINE_STAGE_TRANSFER_BIT, 0, {}, buffer_barrier, pre_copy); + cmdbuf.PipelineBarrier(pre_stage, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, {}, {}, barrier); + }); + + for (const VideoCommon::SwizzleParameters& sw : swizzles) { + const auto params = + VideoCommon::Accelerated::MakeBlockLinearSwizzle2DParams(sw, image.info); + const u32 width = sw.num_tiles.width; + const u32 height = sw.num_tiles.height; + const u32 bytes_per_block = 1u << params.bytes_per_block_log2; + const VkDeviceSize output_size = + static_cast(width) * height * layers * bytes_per_block; + if (output_size == 0) { + continue; + } + const u32 level = static_cast(sw.level); + const u32 texel_width = (std::max)(1u, image.info.size.width >> level); + const u32 texel_height = (std::max)(1u, image.info.size.height >> level); + + const StagingBufferRef output = + staging_buffer_pool.Request(static_cast(output_size), MemoryUsage::DeviceLocal); + + BlockLinearUnswizzle2DPushConstants pc{}; + pc.dim = {width, height, layers}; + pc.bytes_per_block_log2 = params.bytes_per_block_log2; + pc.origin = params.origin; + pc.layer_stride = params.layer_stride; + pc.block_size = params.block_size; + pc.x_shift = params.x_shift; + pc.block_height = params.block_height; + pc.block_height_mask = params.block_height_mask; + + compute_pass_descriptor_queue.Acquire(scheduler, 2); + compute_pass_descriptor_queue.AddBuffer(source_buffer, sw.buffer_offset + source_offset, + image.guest_size_bytes - sw.buffer_offset); + compute_pass_descriptor_queue.AddBuffer(output.buffer, output.offset, output_size); + + const void* descriptor_data = compute_pass_descriptor_queue.UpdateData(); + const VkDescriptorSet set = descriptor_allocator.Commit(); + + const u32 gx = Common::DivCeil(width, 16u); + const u32 gy = Common::DivCeil(height, 8u); + const VkBuffer out_buffer = output.buffer; + const VkDeviceSize out_offset = output.offset; + + scheduler.Record([this, set, descriptor_data, pc, gx, gy, layers, output_size, out_buffer, + out_offset, dst_image, aspect, texel_width, texel_height, + level](vk::CommandBuffer cmdbuf) { + if (out_buffer == VK_NULL_HANDLE) { + return; + } + device.GetLogical().UpdateDescriptorSet(set, *descriptor_template, descriptor_data); + cmdbuf.BindPipeline(VK_PIPELINE_BIND_POINT_COMPUTE, *pipeline); + cmdbuf.BindDescriptorSets(VK_PIPELINE_BIND_POINT_COMPUTE, *layout, 0, set, {}); + cmdbuf.PushConstants(*layout, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(pc), &pc); + cmdbuf.Dispatch(gx, gy, layers); + + const VkBufferMemoryBarrier buffer_barrier{ + .sType = VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER, + .pNext = nullptr, + .srcAccessMask = VK_ACCESS_SHADER_WRITE_BIT, + .dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT, + .srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, + .dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, + .buffer = out_buffer, + .offset = out_offset, + .size = output_size, + }; + cmdbuf.PipelineBarrier(VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, + VK_PIPELINE_STAGE_TRANSFER_BIT, 0, {}, buffer_barrier, {}); const VkBufferImageCopy copy{ .bufferOffset = out_offset, @@ -1074,16 +1094,20 @@ void BlockLinearUnswizzle2DPass::Unswizzle( .bufferImageHeight = 0, .imageSubresource{ .aspectMask = aspect, - .mipLevel = 0, + .mipLevel = level, .baseArrayLayer = 0, - .layerCount = depth, + .layerCount = layers, }, .imageOffset = {0, 0, 0}, .imageExtent = {texel_width, texel_height, 1}, }; - cmdbuf.CopyBufferToImage(out_buffer, dst_image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, copy); + cmdbuf.CopyBufferToImage(out_buffer, dst_image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, + copy); + }); + } - const VkImageMemoryBarrier post_copy{ + scheduler.Record([dst_image, aspect](vk::CommandBuffer cmdbuf) { + const VkImageMemoryBarrier barrier{ .sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .pNext = nullptr, .srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT, @@ -1101,8 +1125,8 @@ void BlockLinearUnswizzle2DPass::Unswizzle( .layerCount = VK_REMAINING_ARRAY_LAYERS, }, }; - cmdbuf.PipelineBarrier(VK_PIPELINE_STAGE_TRANSFER_BIT, vk::PIPELINE_STAGE_GRAPHICS_COMPUTE, - 0, {}, {}, post_copy); + cmdbuf.PipelineBarrier(VK_PIPELINE_STAGE_TRANSFER_BIT, + vk::PIPELINE_STAGE_GRAPHICS_COMPUTE, 0, {}, {}, barrier); }); } @@ -1288,13 +1312,20 @@ void BlockLinearUnswizzle3DBufferPass::Unswizzle( .offset = out_offset, .size = output_size, }; + VkAccessFlags pre_copy_access = VK_ACCESS_NONE; + VkImageLayout pre_copy_layout = VK_IMAGE_LAYOUT_UNDEFINED; + VkPipelineStageFlags pre_copy_stage = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT; + if (is_initialized) { + pre_copy_access = VK_ACCESS_SHADER_READ_BIT; + pre_copy_layout = VK_IMAGE_LAYOUT_GENERAL; + pre_copy_stage = vk::PIPELINE_STAGE_GRAPHICS_COMPUTE; + } const VkImageMemoryBarrier pre_copy{ .sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .pNext = nullptr, - .srcAccessMask = static_cast(is_initialized ? VK_ACCESS_SHADER_READ_BIT - : VK_ACCESS_NONE), + .srcAccessMask = pre_copy_access, .dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT, - .oldLayout = is_initialized ? VK_IMAGE_LAYOUT_GENERAL : VK_IMAGE_LAYOUT_UNDEFINED, + .oldLayout = pre_copy_layout, .newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, .srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, .dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, @@ -1307,9 +1338,7 @@ void BlockLinearUnswizzle3DBufferPass::Unswizzle( .layerCount = VK_REMAINING_ARRAY_LAYERS, }, }; - cmdbuf.PipelineBarrier(VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT | - (is_initialized ? vk::PIPELINE_STAGE_GRAPHICS_COMPUTE - : VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT), + cmdbuf.PipelineBarrier(VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT | pre_copy_stage, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, {}, buffer_barrier, pre_copy); const VkBufferImageCopy copy{ diff --git a/src/video_core/renderer_vulkan/vk_compute_pass.h b/src/video_core/renderer_vulkan/vk_compute_pass.h index c08d8724f6..d303161292 100644 --- a/src/video_core/renderer_vulkan/vk_compute_pass.h +++ b/src/video_core/renderer_vulkan/vk_compute_pass.h @@ -178,6 +178,9 @@ public: void Unswizzle(Image& image, const StagingBufferRef& swizzled, std::span swizzles); + void UnswizzleFrom(Image& image, VkBuffer source_buffer, VkDeviceSize source_offset, + std::span swizzles); + private: Scheduler& scheduler; StagingBufferPool& staging_buffer_pool; diff --git a/src/video_core/renderer_vulkan/vk_texture_cache.cpp b/src/video_core/renderer_vulkan/vk_texture_cache.cpp index 5d3bad180c..162f323457 100644 --- a/src/video_core/renderer_vulkan/vk_texture_cache.cpp +++ b/src/video_core/renderer_vulkan/vk_texture_cache.cpp @@ -3157,7 +3157,7 @@ void TextureCacheRuntime::AccelerateImageUpload( return bl2d_unswizzle_pass->Unswizzle(image, map, swizzles); } - if (bl3db_unswizzle_pass && + if (bl3db_unswizzle_pass && z_count == 0 && BlockLinearUnswizzle3DBufferPass::IsSupported(device, image.info)) { return bl3db_unswizzle_pass->Unswizzle(image, map, swizzles); } @@ -3177,6 +3177,66 @@ void TextureCacheRuntime::AccelerateImageUpload( ASSERT(false); } +bool TextureCacheRuntime::IsUnifiedMemoryBindable() const noexcept { + const HostMemoryImport* const import = memory_allocator.GetHostMemoryImport(); + return import != nullptr && import->IsValid() && import->IsBindable(); +} + +u64 TextureCacheRuntime::UnifiedMemoryBase() const noexcept { + const HostMemoryImport* const import = memory_allocator.GetHostMemoryImport(); + if (import == nullptr) { + return 0; + } + return import->GetBaseOffset(); +} + +u64 TextureCacheRuntime::UnifiedMemorySize() const noexcept { + const HostMemoryImport* const import = memory_allocator.GetHostMemoryImport(); + if (import == nullptr) { + return 0; + } + return import->GetSize(); +} + +u64 TextureCacheRuntime::UnifiedMemoryWindowSize() const noexcept { + const HostMemoryImport* const import = memory_allocator.GetHostMemoryImport(); + if (import == nullptr) { + return 0; + } + return import->GetWindowSize(); +} + +bool TextureCacheRuntime::CanUploadImageDirectly(const VideoCommon::ImageInfo& info) const { + return bl2d_unswizzle_pass.has_value() && + BlockLinearUnswizzle2DPass::IsSupported(device, info); +} + +bool TextureCacheRuntime::UploadImageDirectly( + Image& image, size_t window_index, u64 window_offset, + std::span swizzles) { + if ((window_offset % device.GetStorageBufferAlignment()) != 0) { + return false; + } + if (image.guest_size_bytes > device.GetMaxStorageBufferRange()) { + return false; + } + const HostMemoryImport* const import = memory_allocator.GetHostMemoryImport(); + if (import == nullptr || window_index >= import->GetWindowCount()) { + return false; + } + const VkBuffer window_buffer = import->GetWindowBuffer(window_index); + if (window_buffer == VK_NULL_HANDLE) { + return false; + } + bl2d_unswizzle_pass->UnswizzleFrom(image, window_buffer, + static_cast(window_offset), swizzles); + return true; +} + +u64 TextureCacheRuntime::CurrentTick() const noexcept { + return scheduler.CurrentTick(); +} + void TextureCacheRuntime::TransitionImageLayout(Image& image) { if (!image.ExchangeInitialization()) { VkImageMemoryBarrier barrier{ diff --git a/src/video_core/renderer_vulkan/vk_texture_cache.h b/src/video_core/renderer_vulkan/vk_texture_cache.h index 1cd786edcf..59eb99543d 100644 --- a/src/video_core/renderer_vulkan/vk_texture_cache.h +++ b/src/video_core/renderer_vulkan/vk_texture_cache.h @@ -101,6 +101,21 @@ public: std::span, u32 z_start, u32 z_count); + [[nodiscard]] bool IsUnifiedMemoryBindable() const noexcept; + + [[nodiscard]] u64 UnifiedMemoryBase() const noexcept; + + [[nodiscard]] u64 UnifiedMemorySize() const noexcept; + + [[nodiscard]] u64 UnifiedMemoryWindowSize() const noexcept; + + [[nodiscard]] bool CanUploadImageDirectly(const VideoCommon::ImageInfo& info) const; + + bool UploadImageDirectly(Image& image, size_t window_index, u64 window_offset, + std::span swizzles); + + [[nodiscard]] u64 CurrentTick() const noexcept; + void InsertUploadMemoryBarrier() {} void TransitionImageLayout(Image& image); @@ -588,6 +603,7 @@ struct TextureCacheParams { static constexpr bool HAS_DEVICE_MEMORY_INFO = true; static constexpr bool IMPLEMENTS_ASYNC_DOWNLOADS = true; static constexpr bool HAS_MSAA_DOWNLOADS = true; + static constexpr bool USE_UNIFIED_MEMORY = true; using Runtime = Vulkan::TextureCacheRuntime; using Image = Vulkan::Image; diff --git a/src/video_core/texture_cache/image_base.h b/src/video_core/texture_cache/image_base.h index 79fc8505d6..4fd7eafe7d 100644 --- a/src/video_core/texture_cache/image_base.h +++ b/src/video_core/texture_cache/image_base.h @@ -95,6 +95,8 @@ struct ImageBase { u32 scale_rating = 0; u64 scale_tick = 0; bool has_scaled = false; + bool direct_upload_used = false; + bool direct_upload_blocked = false; size_t channel = 0; diff --git a/src/video_core/texture_cache/texture_cache.h b/src/video_core/texture_cache/texture_cache.h index 640bd38407..34b520e059 100644 --- a/src/video_core/texture_cache/texture_cache.h +++ b/src/video_core/texture_cache/texture_cache.h @@ -585,6 +585,10 @@ FramebufferId TextureCache

::GetFramebufferId(const RenderTargets& key) { template void TextureCache

::WriteMemory(DAddr cpu_addr, size_t size) { ForEachImageInRegion(cpu_addr, size, [this](ImageId image_id, Image& image) { + if (image.direct_upload_used) { + image.direct_upload_used = false; + image.direct_upload_blocked = true; + } if (True(image.flags & ImageFlagBits::CpuModified)) { return; } @@ -1145,11 +1149,59 @@ void TextureCache

::RefreshContents(Image& image, ImageId image_id) { QueueAsyncUnswizzle(image, image_id); return; } + if (True(image.flags & ImageFlagBits::AcceleratedUpload) && + TryUploadFromUnifiedMemory(image)) { + runtime.InsertUploadMemoryBarrier(); + return; + } auto staging = runtime.UploadStagingBuffer(MapSizeBytes(image)); UploadImageContents(image, staging); runtime.InsertUploadMemoryBarrier(); } +template +bool TextureCache

::TryUploadFromUnifiedMemory([[maybe_unused]] Image& image) { + if constexpr (USE_UNIFIED_MEMORY) { + if (image.direct_upload_blocked || image.guest_size_bytes == 0) { + return false; + } + if (!runtime.IsUnifiedMemoryBindable() || !runtime.CanUploadImageDirectly(image.info)) { + return false; + } + const u64 window_size = runtime.UnifiedMemoryWindowSize(); + if (window_size == 0) { + return false; + } + const u8* const first = gpu_memory->GetSpan(image.gpu_addr, image.guest_size_bytes); + if (first == nullptr) { + return false; + } + const u64 phys_offset = static_cast(first - device_memory.GetPhysicalBase()); + const u64 unified_base = runtime.UnifiedMemoryBase(); + if (phys_offset < unified_base) { + return false; + } + const u64 relative = phys_offset - unified_base; + const u64 unified_size = runtime.UnifiedMemorySize(); + if (relative >= unified_size || unified_size - relative < image.guest_size_bytes) { + return false; + } + const u64 local_offset = relative % window_size; + if (window_size - local_offset < image.guest_size_bytes) { + return false; + } + const auto swizzles = FullUploadSwizzles(image.info); + if (!runtime.UploadImageDirectly(image, static_cast(relative / window_size), + local_offset, FixSmallVectorADL(swizzles))) { + return false; + } + image.direct_upload_used = true; + return true; + } else { + return false; + } +} + template template void TextureCache

::UploadImageContents(Image& image, StagingBuffer& staging) { diff --git a/src/video_core/texture_cache/texture_cache_base.h b/src/video_core/texture_cache/texture_cache_base.h index 8a2318cc72..d4a56aab19 100644 --- a/src/video_core/texture_cache/texture_cache_base.h +++ b/src/video_core/texture_cache/texture_cache_base.h @@ -109,6 +109,7 @@ class TextureCache : public VideoCommon::ChannelSetupCaches::max)()}; @@ -308,6 +309,8 @@ private: void RefreshContents(Image& image, ImageId image_id); + bool TryUploadFromUnifiedMemory(Image& image); + /// Upload data from guest to an image template void UploadImageContents(Image& image, StagingBuffer& staging_buffer); diff --git a/src/video_core/vulkan_common/vulkan_memory_allocator.cpp b/src/video_core/vulkan_common/vulkan_memory_allocator.cpp index 82a09b9ef2..13fbd69221 100644 --- a/src/video_core/vulkan_common/vulkan_memory_allocator.cpp +++ b/src/video_core/vulkan_common/vulkan_memory_allocator.cpp @@ -686,6 +686,17 @@ MemoryCommit MemoryAllocator::Commit(const VkMemoryRequirements &reqs, MemoryUsa return MemoryCommit(allocator, a, info); } +HostMemoryImport *MemoryAllocator::CreateHostMemoryImport( + void *base, size_t size, std::span hardware_buffers, + size_t hardware_buffer_window, size_t hardware_buffer_base) { + unified_memory = std::make_unique( + device, base, size, hardware_buffers, hardware_buffer_window, hardware_buffer_base); + if (!unified_memory->IsValid()) { + unified_memory.reset(); + } + return unified_memory.get(); +} + MemoryCommit MemoryAllocator::Commit(const vk::Buffer &buffer, MemoryUsage usage) { // Allocate memory appropriate for this buffer automatically const auto vma_usage = MemoryUsageVma(usage); diff --git a/src/video_core/vulkan_common/vulkan_memory_allocator.h b/src/video_core/vulkan_common/vulkan_memory_allocator.h index d397242a5f..39bf26d40e 100644 --- a/src/video_core/vulkan_common/vulkan_memory_allocator.h +++ b/src/video_core/vulkan_common/vulkan_memory_allocator.h @@ -195,6 +195,15 @@ namespace Vulkan { /// Commits memory required by the buffer and binds it (for buffers created outside VMA). MemoryCommit Commit(const vk::Buffer &buffer, MemoryUsage usage); + HostMemoryImport *CreateHostMemoryImport(void *base, size_t size, + std::span hardware_buffers, + size_t hardware_buffer_window, + size_t hardware_buffer_base); + + [[nodiscard]] HostMemoryImport *GetHostMemoryImport() const noexcept { + return unified_memory.get(); + } + private: static bool IsAutoUsage(VmaMemoryUsage u) noexcept { switch (u) { @@ -212,6 +221,7 @@ namespace Vulkan { const VkPhysicalDeviceMemoryProperties properties; ///< Physical device memory properties. VkDeviceSize buffer_image_granularity; ///< Adjacent buffer/image granularity u32 valid_memory_types{~0u}; + std::unique_ptr unified_memory; }; } // namespace Vulkan From a4276b598b668f3fe7d7102aa6e4d13366ab9402 Mon Sep 17 00:00:00 2001 From: CamilleLaVey Date: Wed, 26 Aug 2026 17:47:12 -0400 Subject: [PATCH 18/27] Meow. --- src/video_core/renderer_vulkan/vk_texture_cache.cpp | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/video_core/renderer_vulkan/vk_texture_cache.cpp b/src/video_core/renderer_vulkan/vk_texture_cache.cpp index 162f323457..fd901db22e 100644 --- a/src/video_core/renderer_vulkan/vk_texture_cache.cpp +++ b/src/video_core/renderer_vulkan/vk_texture_cache.cpp @@ -1901,11 +1901,9 @@ Image::Image(TextureCacheRuntime& runtime_, const ImageInfo& info_, GPUVAddr gpu } else if (runtime->bl2d_unswizzle_pass && BlockLinearUnswizzle2DPass::IsSupported(runtime->device, info)) { flags |= VideoCommon::ImageFlagBits::AcceleratedUpload; - flags |= VideoCommon::ImageFlagBits::CostlyLoad; } else if (runtime->bl3db_unswizzle_pass && BlockLinearUnswizzle3DBufferPass::IsSupported(runtime->device, info)) { flags |= VideoCommon::ImageFlagBits::AcceleratedUpload; - flags |= VideoCommon::ImageFlagBits::CostlyLoad; } if (IsPixelFormatBCn(info.format) && !runtime->device.IsOptimalBcnSupported()) { flags |= VideoCommon::ImageFlagBits::Converted; From 7be3fc3ad56c407c66ea10889c371d02c5b6b1d5 Mon Sep 17 00:00:00 2001 From: CamilleLaVey Date: Wed, 26 Aug 2026 18:05:03 -0400 Subject: [PATCH 19/27] Just cries internally --- src/common/host_memory.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/common/host_memory.cpp b/src/common/host_memory.cpp index a11c1c149b..7d7354632b 100644 --- a/src/common/host_memory.cpp +++ b/src/common/host_memory.cpp @@ -711,7 +711,7 @@ public: constexpr u64 MapSlotsPerWindow = 64; const u64 affordable_windows = permissible_maps / MapSlotsPerWindow; budget = (std::min)(budget, affordable_windows * window_size); - budget = (std::min)(budget, static_cast(backing_size)); + budget = (std::min)(budget, static_cast(backing_size) / 2); budget = Common::AlignDown(budget, window_size); constexpr u64 MinimumBudget = 256ULL << 20; if (budget < MinimumBudget) { From 04952558675e094701e1d5970687d83221ac1b77 Mon Sep 17 00:00:00 2001 From: CamilleLaVey Date: Wed, 26 Aug 2026 18:40:10 -0400 Subject: [PATCH 20/27] Another intent --- src/video_core/renderer_vulkan/vk_compute_pass.cpp | 8 ++++++++ src/video_core/renderer_vulkan/vk_texture_cache.cpp | 2 +- 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/src/video_core/renderer_vulkan/vk_compute_pass.cpp b/src/video_core/renderer_vulkan/vk_compute_pass.cpp index 8bbc280d9c..450547b987 100644 --- a/src/video_core/renderer_vulkan/vk_compute_pass.cpp +++ b/src/video_core/renderer_vulkan/vk_compute_pass.cpp @@ -962,6 +962,10 @@ bool BlockLinearUnswizzle2DPass::IsSupported(const Device& device, if (device.GetStorageBufferAlignment() > Tegra::Texture::GOB_SIZE) { return false; } + if (VideoCore::Surface::GetFormatType(info.format) != + VideoCore::Surface::SurfaceType::ColorTexture) { + return false; + } if (VideoCore::Surface::IsPixelFormatASTC(info.format) && !device.IsOptimalAstcSupported()) { return false; } @@ -1222,6 +1226,10 @@ bool BlockLinearUnswizzle3DBufferPass::IsSupported(const Device& device, if (info.size.depth <= 1) { return false; } + if (VideoCore::Surface::GetFormatType(info.format) != + VideoCore::Surface::SurfaceType::ColorTexture) { + return false; + } if (VideoCore::Surface::IsPixelFormatASTC(info.format)) { return false; } diff --git a/src/video_core/renderer_vulkan/vk_texture_cache.cpp b/src/video_core/renderer_vulkan/vk_texture_cache.cpp index fd901db22e..a2a04379cd 100644 --- a/src/video_core/renderer_vulkan/vk_texture_cache.cpp +++ b/src/video_core/renderer_vulkan/vk_texture_cache.cpp @@ -3147,7 +3147,7 @@ void TextureCacheRuntime::AccelerateImageUpload( std::span swizzles, u32 z_start, u32 z_count) { - if (IsPixelFormatASTC(image.info.format)) { + if (astc_decoder_pass && WillUseAcceleratedAstcDecode(device, image.info)) { return astc_decoder_pass->Assemble(image, map, swizzles); } From 8ebbdc9bee4713845b35d40b47132262d6b957e7 Mon Sep 17 00:00:00 2001 From: CamilleLaVey Date: Wed, 26 Aug 2026 19:06:23 -0400 Subject: [PATCH 21/27] What if we just rely entirely on SGSR common than using EdgeDir? --- .../host_shaders/sgsr1_shader_mobile.frag | 103 ++++++++++-------- 1 file changed, 59 insertions(+), 44 deletions(-) diff --git a/src/video_core/host_shaders/sgsr1_shader_mobile.frag b/src/video_core/host_shaders/sgsr1_shader_mobile.frag index 3453ca2cae..7fed788afe 100644 --- a/src/video_core/host_shaders/sgsr1_shader_mobile.frag +++ b/src/video_core/host_shaders/sgsr1_shader_mobile.frag @@ -6,9 +6,9 @@ precision highp float; precision highp int; -// Operation modes: RGBA -> 1, RGBY -> 3, LERP -> 4 -#define OPERATION_MODE 1 #define EDGE_THRESHOLD (8.0 / 255.0) +#define DIRECTION_EPSILON 6.5e-05 +#define DEVIATION_FLOOR 6.0e-02 layout(push_constant) uniform constants { vec2 scale; @@ -21,20 +21,37 @@ layout(set = 0, binding = 0) uniform sampler2D sampler0; layout(location=0) in vec2 texcoord; layout(location=0) out vec4 frag_color; -vec4 weightY(vec4 dx, vec4 dy, vec4 std) { - vec4 x = ((dx * dx) + (dy * dy)) * 0.55f + std; - return (x - 1.f) * (x - 4.f) * 3.8125f; // approx. of (x - 1) * (x - 4)^3 +mediump vec4 fastLanczos2(mediump vec4 x) { + mediump vec4 wA = x - 4.0f; + mediump vec4 wB = x * wA - wA; + wA *= wA; + return wB * wA; +} + +mediump vec2 edgeDirection(mediump vec4 left, mediump vec4 right) { + mediump float RxLz = right.x - left.z; + mediump float RwLy = right.w - left.y; + mediump vec2 delta = vec2(RxLz + RwLy, RxLz - RwLy); + mediump float length_inv = + inversesqrt((delta.x * delta.x + DIRECTION_EPSILON) + delta.y * delta.y); + return delta * length_inv; +} + +mediump vec4 weightY(mediump vec4 dx, mediump vec4 dy, mediump vec4 c, mediump float std, + mediump vec2 dir) { + mediump vec4 edge_dis = dx * dir.y + dy * dir.x; + mediump vec4 x = (dx * dx + dy * dy) + + (edge_dis * edge_dis) * (clamp((c * c) * std, 0.0f, 1.0f) * 0.7f - 1.0f); + return fastLanczos2(x); } void main() { - vec4 color = textureLod(sampler0, texcoord.xy, 0.0f); - // image coord - vec2 icoord = (texcoord * size + vec2(-0.5f, 0.5f)); - vec2 icoord_pixel = floor(icoord); - vec2 coord = icoord_pixel * scale; - vec2 pl = icoord - icoord_pixel; - // left: 0, right: 1, upDown: 2 - mat3x4 dg = mat3x4( + mediump vec4 color = textureLod(sampler0, texcoord.xy, 0.0f); + highp vec2 icoord = (texcoord * size + vec2(-0.5f, 0.5f)); + highp vec2 icoord_pixel = floor(icoord); + highp vec2 coord = icoord_pixel * scale; + mediump vec2 pl = icoord - icoord_pixel; + mediump mat3x4 dg = mat3x4( textureGather(sampler0, coord, 1), textureGather(sampler0, coord + vec2(2.f * scale.x, 0.0f), 1), vec4( @@ -42,42 +59,40 @@ void main() { textureGather(sampler0, coord + vec2(scale.x, +scale.y), 1).yx ) ); - float edgeVote = abs(dg[0].z - dg[0].y) + abs(color.y - dg[0].y) + abs(color.y - dg[0].z); + mediump float edgeVote = + abs(dg[0].z - dg[0].y) + abs(color.y - dg[0].y) + abs(color.y - dg[0].z); if (edgeVote > EDGE_THRESHOLD) { - float mean = (dg[0].y + dg[0].z + dg[1].x + dg[1].w) * 0.25f; + mediump float mean = (dg[0].y + dg[0].z + dg[1].x + dg[1].w) * 0.25f; dg = dg - mean; - vec4 sum = abs(dg[0]) + abs(dg[1]) + abs(dg[2]); - float std = 2.181818f / (sum.x + sum.y + sum.z + sum.w); - mat2x4 w = mat2x4( - weightY( - pl.xxxx + vec4(+1.0f, +0.0f, +0.0f, +1.0f), - pl.yyyy + vec4(-1.0f, -1.0f, +0.0f, +0.0f), - clamp(abs(dg[0]) * std, 0.0f, 1.0f) - ) + weightY( - pl.xxxx + vec4(-1.0f, -2.0f, -2.0f, -1.0f), - pl.yyyy + vec4(-1.0f, -1.0f, +0.0f, +0.0f), - clamp(abs(dg[1]) * std, 0.0f, 1.0f) - ) + weightY( - pl.xxxx + vec4(+0.0f, -1.0f, -1.0f, +0.0f), - pl.yyyy + vec4(+1.0f, +1.0f, -2.0f, -2.0f), - clamp(abs(dg[2]) * std, 0.0f, 1.0f) - ), - dg[0] + dg[1] + dg[2] + mediump float sum = dot(abs(dg[0]) + abs(dg[1]) + abs(dg[2]), vec4(1.0f)); + mediump float sum_mean = 1.014185e+01f / max(sum, DEVIATION_FLOOR); + mediump float std = sum_mean * sum_mean; + mediump vec2 dir = edgeDirection(dg[0], dg[1]); + mediump vec4 w0 = weightY( + pl.xxxx + vec4(+1.0f, +0.0f, +0.0f, +1.0f), + pl.yyyy + vec4(-1.0f, -1.0f, +0.0f, +0.0f), + dg[0], std, dir ); - // compute final y with bounds - vec2 yb = vec2( - min(min(dg[0].y, dg[0].z), min(dg[1].x, dg[1].w)), // min - max(max(dg[0].y, dg[0].z), max(dg[1].x, dg[1].w)) // max + mediump vec4 w1 = weightY( + pl.xxxx + vec4(-1.0f, -2.0f, -2.0f, -1.0f), + pl.yyyy + vec4(-1.0f, -1.0f, +0.0f, +0.0f), + dg[1], std, dir ); - vec2 fvy = vec2( - w[0].x + w[0].y + w[0].z + w[0].w, - w[1].x + w[1].y + w[1].z + w[1].w + mediump vec4 w2 = weightY( + pl.xxxx + vec4(+0.0f, -1.0f, -1.0f, +0.0f), + pl.yyyy + vec4(+1.0f, +1.0f, -2.0f, -2.0f), + dg[2], std, dir ); - float fy = clamp((fvy.y / fvy.x) * edge_sharpness, yb[0], yb[1]); - // Smooth high contrast input - float dy = clamp(fy - color.y + mean, -23.0f / 255.0f, 23.0f / 255.0f); + mediump float sum_w = dot(w0 + w1 + w2, vec4(1.0f)); + mediump float sum_wc = dot(w0 * dg[0] + w1 * dg[1] + w2 * dg[2], vec4(1.0f)); + mediump vec2 yb = vec2( + min(min(dg[0].y, dg[0].z), min(dg[1].x, dg[1].w)), + max(max(dg[0].y, dg[0].z), max(dg[1].x, dg[1].w)) + ); + mediump float fy = clamp((sum_wc / sum_w) * edge_sharpness, yb[0], yb[1]); + mediump float dy = clamp(fy - color.y + mean, -23.0f / 255.0f, 23.0f / 255.0f); color = clamp(color + dy, 0.0f, 1.0f); } - color.w = 1.0f; //assume alpha channel is not used + color.w = 1.0f; frag_color.xyzw = color; -} \ No newline at end of file +} From ebedba1f2ce810a459a896e00312bb1de922f189 Mon Sep 17 00:00:00 2001 From: CamilleLaVey Date: Wed, 26 Aug 2026 22:10:00 -0400 Subject: [PATCH 22/27] Extended the impact on AHB fallback --- src/common/host_memory.cpp | 6 ++- src/common/memory_detect.cpp | 36 ++++++++++++++++++ src/common/memory_detect.h | 2 + .../renderer_vulkan/vk_compute_pass.cpp | 38 +++++++++++++++---- .../vulkan_common/vulkan_memory_allocator.cpp | 18 ++++++++- 5 files changed, 90 insertions(+), 10 deletions(-) diff --git a/src/common/host_memory.cpp b/src/common/host_memory.cpp index 7d7354632b..9f29f8e897 100644 --- a/src/common/host_memory.cpp +++ b/src/common/host_memory.cpp @@ -711,7 +711,11 @@ public: constexpr u64 MapSlotsPerWindow = 64; const u64 affordable_windows = permissible_maps / MapSlotsPerWindow; budget = (std::min)(budget, affordable_windows * window_size); - budget = (std::min)(budget, static_cast(backing_size) / 2); + const u64 available = Common::GetAvailablePhysicalMemory(); + if (available != 0) { + budget = (std::min)(budget, available / 2); + } + budget = (std::min)(budget, static_cast(backing_size)); budget = Common::AlignDown(budget, window_size); constexpr u64 MinimumBudget = 256ULL << 20; if (budget < MinimumBudget) { diff --git a/src/common/memory_detect.cpp b/src/common/memory_detect.cpp index e21e058486..ae303a4f1a 100644 --- a/src/common/memory_detect.cpp +++ b/src/common/memory_detect.cpp @@ -22,6 +22,7 @@ #include #include +#include #include "common/memory_detect.h" @@ -97,4 +98,39 @@ u64 GetPermissibleMapCount() { return count - ReservedMaps; } +u64 GetAvailablePhysicalMemory() { +#ifdef _WIN32 + MEMORYSTATUSEX memorystatus; + memorystatus.dwLength = sizeof(memorystatus); + if (GlobalMemoryStatusEx(&memorystatus) == 0) { + return 0; + } + return memorystatus.ullAvailPhys; +#elif defined(__linux__) + static constexpr char AvailableKey[] = "MemAvailable:"; + if (std::FILE* const file = std::fopen("/proc/meminfo", "re")) { + char line[256]; + u64 available = 0; + while (std::fgets(line, sizeof(line), file) != nullptr) { + if (std::strncmp(line, AvailableKey, sizeof(AvailableKey) - 1) != 0) { + continue; + } + available = std::strtoull(line + sizeof(AvailableKey) - 1, nullptr, 10) * 1024; + break; + } + std::fclose(file); + if (available != 0) { + return available; + } + } + struct sysinfo meminfo; + if (sysinfo(&meminfo) != 0) { + return 0; + } + return static_cast(meminfo.freeram) * static_cast(meminfo.mem_unit); +#else + return 0; +#endif +} + } // namespace Common diff --git a/src/common/memory_detect.h b/src/common/memory_detect.h index 9a7ce7ab1c..367e3f754d 100644 --- a/src/common/memory_detect.h +++ b/src/common/memory_detect.h @@ -23,4 +23,6 @@ struct MemoryInfo { [[nodiscard]] u64 GetPermissibleMapCount(); +[[nodiscard]] u64 GetAvailablePhysicalMemory(); + } // namespace Common diff --git a/src/video_core/renderer_vulkan/vk_compute_pass.cpp b/src/video_core/renderer_vulkan/vk_compute_pass.cpp index 450547b987..fe0a93a94f 100644 --- a/src/video_core/renderer_vulkan/vk_compute_pass.cpp +++ b/src/video_core/renderer_vulkan/vk_compute_pass.cpp @@ -13,6 +13,7 @@ #include "video_core/renderer_vulkan/vk_texture_cache.h" +#include "common/alignment.h" #include "common/assert.h" #include "common/common_types.h" #include "common/div_ceil.h" @@ -992,6 +993,31 @@ void BlockLinearUnswizzle2DPass::UnswizzleFrom( const u32 layers = image.info.resources.layers; const VkImageAspectFlags aspect = image.AspectMask(); + const VkDeviceSize output_alignment = + (std::max)(device.GetStorageBufferAlignment(), VkDeviceSize{16}); + VkDeviceSize total_output = 0; + for (const VideoCommon::SwizzleParameters& sw : swizzles) { + const auto params = + VideoCommon::Accelerated::MakeBlockLinearSwizzle2DParams(sw, image.info); + const VkDeviceSize level_size = static_cast(sw.num_tiles.width) * + sw.num_tiles.height * layers * + (1ULL << params.bytes_per_block_log2); + if (level_size == 0) { + continue; + } + total_output = Common::AlignUp(total_output, output_alignment) + level_size; + } + if (total_output == 0) { + return; + } + const StagingBufferRef output = + staging_buffer_pool.Request(static_cast(total_output), MemoryUsage::DeviceLocal); + const VkBuffer out_buffer = output.buffer; + if (out_buffer == VK_NULL_HANDLE) { + return; + } + VkDeviceSize level_offset = 0; + scheduler.RequestOutsideRenderPassOperationContext(); VkAccessFlags pre_access = VK_ACCESS_NONE; @@ -1040,8 +1066,9 @@ void BlockLinearUnswizzle2DPass::UnswizzleFrom( const u32 texel_width = (std::max)(1u, image.info.size.width >> level); const u32 texel_height = (std::max)(1u, image.info.size.height >> level); - const StagingBufferRef output = - staging_buffer_pool.Request(static_cast(output_size), MemoryUsage::DeviceLocal); + level_offset = Common::AlignUp(level_offset, output_alignment); + const VkDeviceSize out_offset = output.offset + level_offset; + level_offset += output_size; BlockLinearUnswizzle2DPushConstants pc{}; pc.dim = {width, height, layers}; @@ -1056,22 +1083,17 @@ void BlockLinearUnswizzle2DPass::UnswizzleFrom( compute_pass_descriptor_queue.Acquire(scheduler, 2); compute_pass_descriptor_queue.AddBuffer(source_buffer, sw.buffer_offset + source_offset, image.guest_size_bytes - sw.buffer_offset); - compute_pass_descriptor_queue.AddBuffer(output.buffer, output.offset, output_size); + compute_pass_descriptor_queue.AddBuffer(out_buffer, out_offset, output_size); const void* descriptor_data = compute_pass_descriptor_queue.UpdateData(); const VkDescriptorSet set = descriptor_allocator.Commit(); const u32 gx = Common::DivCeil(width, 16u); const u32 gy = Common::DivCeil(height, 8u); - const VkBuffer out_buffer = output.buffer; - const VkDeviceSize out_offset = output.offset; scheduler.Record([this, set, descriptor_data, pc, gx, gy, layers, output_size, out_buffer, out_offset, dst_image, aspect, texel_width, texel_height, level](vk::CommandBuffer cmdbuf) { - if (out_buffer == VK_NULL_HANDLE) { - return; - } device.GetLogical().UpdateDescriptorSet(set, *descriptor_template, descriptor_data); cmdbuf.BindPipeline(VK_PIPELINE_BIND_POINT_COMPUTE, *pipeline); cmdbuf.BindDescriptorSets(VK_PIPELINE_BIND_POINT_COMPUTE, *layout, 0, set, {}); diff --git a/src/video_core/vulkan_common/vulkan_memory_allocator.cpp b/src/video_core/vulkan_common/vulkan_memory_allocator.cpp index 13fbd69221..96690a19c6 100644 --- a/src/video_core/vulkan_common/vulkan_memory_allocator.cpp +++ b/src/video_core/vulkan_common/vulkan_memory_allocator.cpp @@ -471,13 +471,29 @@ bool HostMemoryImport::ImportHardwareBuffers( VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_INDEX_BUFFER_BIT | VK_BUFFER_USAGE_VERTEX_BUFFER_BIT | VK_BUFFER_USAGE_INDIRECT_BUFFER_BIT; const bool want_address = device.IsBufferDeviceAddressSupported(); + VkBufferUsageFlags minimal_usage = TransferUsage | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT; if (want_address) { shader_usage |= VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT; + minimal_usage |= VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT; } + const auto reset_windows = [&] { + for (Window &window : windows) { + if (window.buffer != VK_NULL_HANDLE) { + logical.DestroyBufferRaw(window.buffer); + } + } + windows.clear(); + imported_size = 0; + }; + bindable = import_all(shader_usage, want_address); if (!bindable) { - imported_size = 0; + reset_windows(); + bindable = import_all(minimal_usage, want_address); + } + if (!bindable) { + reset_windows(); import_all(TransferUsage, false); } if (windows.empty()) { From 8ec648d663add84f4a29ca9e32eae6badf6d5031 Mon Sep 17 00:00:00 2001 From: CamilleLaVey Date: Thu, 27 Aug 2026 01:21:10 -0400 Subject: [PATCH 23/27] Let's try this on memory reclamations --- src/video_core/renderer_vulkan/vk_scheduler.h | 4 ++++ .../renderer_vulkan/vk_texture_cache.cpp | 8 ++++++++ .../renderer_vulkan/vk_texture_cache.h | 2 ++ src/video_core/texture_cache/image_base.h | 2 +- src/video_core/texture_cache/texture_cache.h | 20 +++++++++++++++---- .../texture_cache/texture_cache_base.h | 1 + .../vulkan_common/vulkan_device.cpp | 4 ++++ 7 files changed, 36 insertions(+), 5 deletions(-) diff --git a/src/video_core/renderer_vulkan/vk_scheduler.h b/src/video_core/renderer_vulkan/vk_scheduler.h index d4bc8d0ec5..7ef28929da 100644 --- a/src/video_core/renderer_vulkan/vk_scheduler.h +++ b/src/video_core/renderer_vulkan/vk_scheduler.h @@ -129,6 +129,10 @@ public: return master_semaphore->IsFree(tick); } + void RefreshTick() { + master_semaphore->Refresh(); + } + /// Waits for the given GPU tick, optionally pacing frames. void Wait(u64 tick, double target_fps = 0.0) { if (tick > 0) { diff --git a/src/video_core/renderer_vulkan/vk_texture_cache.cpp b/src/video_core/renderer_vulkan/vk_texture_cache.cpp index a2a04379cd..549eedfe14 100644 --- a/src/video_core/renderer_vulkan/vk_texture_cache.cpp +++ b/src/video_core/renderer_vulkan/vk_texture_cache.cpp @@ -3235,6 +3235,14 @@ u64 TextureCacheRuntime::CurrentTick() const noexcept { return scheduler.CurrentTick(); } +bool TextureCacheRuntime::IsDirectUploadRetired(u64 tick) { + if (scheduler.IsFree(tick)) { + return true; + } + scheduler.RefreshTick(); + return scheduler.IsFree(tick); +} + void TextureCacheRuntime::TransitionImageLayout(Image& image) { if (!image.ExchangeInitialization()) { VkImageMemoryBarrier barrier{ diff --git a/src/video_core/renderer_vulkan/vk_texture_cache.h b/src/video_core/renderer_vulkan/vk_texture_cache.h index 59eb99543d..f5f498879c 100644 --- a/src/video_core/renderer_vulkan/vk_texture_cache.h +++ b/src/video_core/renderer_vulkan/vk_texture_cache.h @@ -116,6 +116,8 @@ public: [[nodiscard]] u64 CurrentTick() const noexcept; + [[nodiscard]] bool IsDirectUploadRetired(u64 tick); + void InsertUploadMemoryBarrier() {} void TransitionImageLayout(Image& image); diff --git a/src/video_core/texture_cache/image_base.h b/src/video_core/texture_cache/image_base.h index 4fd7eafe7d..6915a4d9af 100644 --- a/src/video_core/texture_cache/image_base.h +++ b/src/video_core/texture_cache/image_base.h @@ -95,7 +95,7 @@ struct ImageBase { u32 scale_rating = 0; u64 scale_tick = 0; bool has_scaled = false; - bool direct_upload_used = false; + u64 direct_upload_tick = 0; bool direct_upload_blocked = false; size_t channel = 0; diff --git a/src/video_core/texture_cache/texture_cache.h b/src/video_core/texture_cache/texture_cache.h index 34b520e059..a0d01e5de6 100644 --- a/src/video_core/texture_cache/texture_cache.h +++ b/src/video_core/texture_cache/texture_cache.h @@ -119,13 +119,16 @@ void TextureCache

::RunGarbageCollector() { bool aggressive_mode = false; u64 ticks_to_destroy = 0; size_t num_iterations = 0; + size_t num_downloads = 0; const auto Configure = [&](bool allow_aggressive) { high_priority_mode = total_used_memory >= expected_memory; aggressive_mode = allow_aggressive && total_used_memory >= critical_memory; ticks_to_destroy = aggressive_mode ? 10ULL : high_priority_mode ? 25ULL : 50ULL; num_iterations = aggressive_mode ? 40 : (high_priority_mode ? 20 : 10); + num_downloads = MAX_GC_DOWNLOADS_PER_PASS; }; - const auto Cleanup = [this, &num_iterations, &high_priority_mode, &aggressive_mode](ImageId image_id) { + const auto Cleanup = [this, &num_iterations, &num_downloads, &high_priority_mode, + &aggressive_mode](ImageId image_id) { if (num_iterations == 0) { return true; } @@ -139,6 +142,10 @@ void TextureCache

::RunGarbageCollector() { return false; } if (must_download) { + if (num_downloads == 0) { + return false; + } + --num_downloads; auto map = runtime.DownloadStagingBuffer(image.unswizzled_size_bytes); const auto copies = FixSmallVectorADL(FullDownloadCopies(image.info)); image.DownloadMemory(map, copies); @@ -585,9 +592,14 @@ FramebufferId TextureCache

::GetFramebufferId(const RenderTargets& key) { template void TextureCache

::WriteMemory(DAddr cpu_addr, size_t size) { ForEachImageInRegion(cpu_addr, size, [this](ImageId image_id, Image& image) { - if (image.direct_upload_used) { - image.direct_upload_used = false; + if constexpr (USE_UNIFIED_MEMORY) { + if (image.direct_upload_tick != 0) { + const u64 upload_tick = image.direct_upload_tick; + image.direct_upload_tick = 0; + if (!runtime.IsDirectUploadRetired(upload_tick)) { image.direct_upload_blocked = true; + } + } } if (True(image.flags & ImageFlagBits::CpuModified)) { return; @@ -1195,7 +1207,7 @@ bool TextureCache

::TryUploadFromUnifiedMemory([[maybe_unused]] Image& image) local_offset, FixSmallVectorADL(swizzles))) { return false; } - image.direct_upload_used = true; + image.direct_upload_tick = runtime.CurrentTick(); return true; } else { return false; diff --git a/src/video_core/texture_cache/texture_cache_base.h b/src/video_core/texture_cache/texture_cache_base.h index d4a56aab19..96cd2cdd42 100644 --- a/src/video_core/texture_cache/texture_cache_base.h +++ b/src/video_core/texture_cache/texture_cache_base.h @@ -122,6 +122,7 @@ class TextureCache : public VideoCommon::ChannelSetupCaches Date: Thu, 27 Aug 2026 02:30:35 -0400 Subject: [PATCH 24/27] Pure and simply meow --- src/video_core/vulkan_common/vulkan_device.cpp | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/src/video_core/vulkan_common/vulkan_device.cpp b/src/video_core/vulkan_common/vulkan_device.cpp index 3cbd8614b3..aea0d127cc 100644 --- a/src/video_core/vulkan_common/vulkan_device.cpp +++ b/src/video_core/vulkan_common/vulkan_device.cpp @@ -1633,11 +1633,7 @@ u64 Device::GetDeviceMemoryUsage() const { for (const size_t heap : valid_heap_memory) { result += budget.heapUsage[heap]; } - const u64 committed_backing = Common::GetCommittedBackingSize(); - if (result <= committed_backing) { return result; - } - return result - committed_backing; } void Device::CollectPhysicalMemoryInfo() { @@ -1688,7 +1684,6 @@ void Device::CollectPhysicalMemoryInfo() { LOG_INFO(Render_Vulkan, "Discounting {} MiB of guest memory committed by the host", committed_backing >> 20); local_memory -= (std::min)(local_memory, committed_backing); - device_access_memory -= (std::min)(device_access_memory, committed_backing); } if (is_integrated) { const s64 available_memory = static_cast(device_access_memory - device_initial_usage); @@ -1704,6 +1699,7 @@ void Device::CollectPhysicalMemoryInfo() { device_access_memory = std::min(device_access_memory, normal_memory + scaler_memory); } } + device_access_memory -= (std::min)(device_access_memory, committed_backing); } void Device::CollectToolingInfo() { From 08ba001529394dfbfee55d4bec2de3ee88860a0a Mon Sep 17 00:00:00 2001 From: CamilleLaVey Date: Mon, 14 Sep 2026 22:04:56 -0400 Subject: [PATCH 25/27] another try to add compute shaders to the uma path --- src/video_core/buffer_cache/buffer_cache.h | 81 ++++++++--- .../buffer_cache/buffer_cache_base.h | 8 + src/video_core/host_shaders/CMakeLists.txt | 1 + .../block_linear_swizzle_2d_buffer.comp | 83 +++++++++++ .../renderer_vulkan/vk_compute_pass.cpp | 137 ++++++++++++++++++ .../renderer_vulkan/vk_compute_pass.h | 17 +++ .../renderer_vulkan/vk_texture_cache.cpp | 41 +++++- .../renderer_vulkan/vk_texture_cache.h | 8 + src/video_core/texture_cache/texture_cache.h | 90 +++++++++--- .../texture_cache/texture_cache_base.h | 6 + 10 files changed, 429 insertions(+), 43 deletions(-) create mode 100644 src/video_core/host_shaders/block_linear_swizzle_2d_buffer.comp diff --git a/src/video_core/buffer_cache/buffer_cache.h b/src/video_core/buffer_cache/buffer_cache.h index 7ddfb5202c..be85cd63de 100644 --- a/src/video_core/buffer_cache/buffer_cache.h +++ b/src/video_core/buffer_cache/buffer_cache.h @@ -78,6 +78,11 @@ void BufferCache

::TickFrame() { return; } runtime.TickFrame(slot_buffers); + if constexpr (USE_UNIFIED_MEMORY) { + if (!unified_written_ranges.Empty() && runtime.KnownGpuTick() >= unified_write_tick) { + unified_written_ranges.Clear(); + } + } // Calculate hits and shots and move hit bits to the right const u32 hits = std::reduce(channel_state->uniform_cache_hits.begin(), @@ -565,7 +570,8 @@ void BufferCache

::FlushCachedWrites() { template bool BufferCache

::HasUncommittedFlushes() const noexcept { - return !uncommitted_gpu_modified_ranges.Empty() || !committed_gpu_modified_ranges.empty(); + return !uncommitted_gpu_modified_ranges.Empty() || !committed_gpu_modified_ranges.empty() || + uncommitted_unified_writes; } template @@ -582,15 +588,18 @@ bool BufferCache

::ShouldWaitAsyncFlushes() const noexcept { return false; } return async_buffers.front().has_value() || - !pending_downloads.front().unified_copies.empty(); + !pending_downloads.front().unified_copies.empty() || + pending_downloads.front().unified_writes; } template void BufferCache

::CommitAsyncFlushesHigh() { AccumulateFlushes(); + const bool unified_writes = uncommitted_unified_writes; + uncommitted_unified_writes = false; if (committed_gpu_modified_ranges.empty()) { - pending_downloads.emplace_back(); + pending_downloads.emplace_back(AsyncDownloadBatch{.unified_writes = unified_writes}); async_buffers.emplace_back(std::optional{}); return; } @@ -650,7 +659,7 @@ void BufferCache

::CommitAsyncFlushesHigh() { } committed_gpu_modified_ranges.clear(); if (downloads.empty()) { - pending_downloads.emplace_back(); + pending_downloads.emplace_back(AsyncDownloadBatch{.unified_writes = unified_writes}); async_buffers.emplace_back(std::optional{}); return; } @@ -726,6 +735,7 @@ void BufferCache

::CommitAsyncFlushesHigh() { } } runtime.PostCopyBarrier(); + batch.unified_writes = unified_writes; pending_downloads.emplace_back(std::move(batch)); async_buffers.emplace_back(std::move(download_staging)); } @@ -1030,6 +1040,7 @@ void BufferCache

::BindHostGraphicsUniformBuffer(size_t stage, u32 index, u32 || (has_host_buffer && size <= channel_state->uniform_buffer_skip_cache_size && !memory_tracker.IsRegionGpuModified(device_addr, size)); if (use_fast_buffer) { + WaitForUnifiedWrites(device_addr, size); if constexpr (IS_OPENGL) { if (runtime.HasFastBufferSubData()) { // Fast path for Nvidia @@ -1154,6 +1165,47 @@ bool BufferCache

::BindMultiRangeStorage(const Binding& binding, bool is_writt } } +template +void BufferCache

::WaitForUnifiedWrites([[maybe_unused]] DAddr device_addr, + [[maybe_unused]] u64 size) { + if constexpr (USE_UNIFIED_MEMORY) { + if (unified_written_ranges.Empty()) { + return; + } + bool overlaps = false; + unified_written_ranges.ForEachInRange(device_addr, size, + [&overlaps](DAddr, DAddr) { overlaps = true; }); + if (!overlaps) { + return; + } + runtime.Wait(unified_write_tick); + unified_written_ranges.Clear(); + } +} + +template +bool BufferCache

::BindUnifiedStorage([[maybe_unused]] const Binding& binding, + [[maybe_unused]] bool is_written) { + if constexpr (USE_UNIFIED_MEMORY) { + const auto window = TryResolveUnifiedRange(binding.device_addr, binding.size); + if (!window || !runtime.IsUnifiedStorageRange(binding.size, window->offset)) { + return false; + } + if (is_written) { + memory_tracker.MarkRegionAsCpuModified(binding.device_addr, binding.size); + unified_written_ranges.Add(binding.device_addr, binding.size); + unified_write_tick = runtime.CurrentTick(); + uncommitted_unified_writes = true; + } + runtime.BindStorageBuffer(runtime.UnifiedWindowBuffer(window->window), + runtime.UnifiedWindowAddress(window->window), + static_cast(window->offset), binding.size, is_written); + return true; + } else { + return false; + } +} + template void BufferCache

::BindHostGraphicsStorageBuffers(size_t stage) { u32 binding_index = 0; @@ -1165,20 +1217,10 @@ void BufferCache

::BindHostGraphicsStorageBuffers(size_t stage) { } Buffer& buffer = slot_buffers[binding.buffer_id]; TouchBuffer(buffer, binding.buffer_id); - const u32 size = binding.size; - - if constexpr (USE_UNIFIED_MEMORY) { - const auto window = TryResolveUnifiedRange(binding.device_addr, size); - if (window && runtime.IsUnifiedStorageRange(size, window->offset)) { - if (is_written) { - memory_tracker.MarkRegionAsCpuModified(binding.device_addr, size); - } - runtime.BindStorageBuffer(runtime.UnifiedWindowBuffer(window->window), - runtime.UnifiedWindowAddress(window->window), - static_cast(window->offset), size, is_written); - return; - } + if (BindUnifiedStorage(binding, is_written)) { + return; } + const u32 size = binding.size; SynchronizeBuffer(buffer, binding.device_addr, size); @@ -1288,6 +1330,7 @@ void BufferCache

::BindHostComputeUniformBuffers() { }(); if constexpr (!IS_OPENGL) { if (needs_alignment_stream) { + WaitForUnifiedWrites(binding.device_addr, size); const std::span span = runtime.BindMappedUniformBuffer(0, binding_index, size); device_memory.ReadBlockUnsafe(binding.device_addr, span.data(), size); @@ -1319,6 +1362,9 @@ void BufferCache

::BindHostComputeStorageBuffers() { } Buffer& buffer = slot_buffers[binding.buffer_id]; TouchBuffer(buffer, binding.buffer_id); + if (BindUnifiedStorage(binding, is_written)) { + return; + } const u32 size = binding.size; SynchronizeBuffer(buffer, binding.device_addr, size); @@ -1847,6 +1893,7 @@ bool BufferCache

::SynchronizeBuffer(Buffer& buffer, DAddr device_addr, u32 si if (total_size_bytes == 0) { return true; } + WaitForUnifiedWrites(device_addr, size); const std::span copies_span(upload_copies.data(), upload_copies.size()); UploadMemory(buffer, total_size_bytes, largest_copy, copies_span); any_buffer_uploaded = true; diff --git a/src/video_core/buffer_cache/buffer_cache_base.h b/src/video_core/buffer_cache/buffer_cache_base.h index 6eb3daf3aa..0f2323b99f 100644 --- a/src/video_core/buffer_cache/buffer_cache_base.h +++ b/src/video_core/buffer_cache/buffer_cache_base.h @@ -230,6 +230,8 @@ public: bool BindMultiRangeStorage(const Binding& binding, bool is_written, std::span pool); + bool BindUnifiedStorage(const Binding& binding, bool is_written); + void ResolveMultiRangeStorage(Binding& binding, bool is_written, std::vector& pool); @@ -473,6 +475,8 @@ private: std::optional TryResolveUnifiedRange(DAddr device_addr, u64 size); + void WaitForUnifiedWrites(DAddr device_addr, u64 size); + using UnifiedWindowGroups = boost::container::small_vector, 4>; @@ -533,11 +537,15 @@ private: Common::RangeSet uncommitted_gpu_modified_ranges; Common::RangeSet gpu_modified_ranges; std::deque> committed_gpu_modified_ranges; + Common::RangeSet unified_written_ranges; + u64 unified_write_tick = 0; + bool uncommitted_unified_writes = false; // Async Buffers struct AsyncDownloadBatch { boost::container::small_vector staging_copies; boost::container::small_vector unified_copies; + bool unified_writes = false; }; Common::OverlapRangeSet async_downloads; diff --git a/src/video_core/host_shaders/CMakeLists.txt b/src/video_core/host_shaders/CMakeLists.txt index f8b64c57e8..78322d81dc 100644 --- a/src/video_core/host_shaders/CMakeLists.txt +++ b/src/video_core/host_shaders/CMakeLists.txt @@ -16,6 +16,7 @@ set(GLSL_INCLUDES set(SHADER_FILES ${CMAKE_CURRENT_SOURCE_DIR}/astc_decoder.comp ${CMAKE_CURRENT_SOURCE_DIR}/blit_color_float.frag + ${CMAKE_CURRENT_SOURCE_DIR}/block_linear_swizzle_2d_buffer.comp ${CMAKE_CURRENT_SOURCE_DIR}/block_linear_unswizzle_2d.comp ${CMAKE_CURRENT_SOURCE_DIR}/block_linear_unswizzle_2d_buffer.comp ${CMAKE_CURRENT_SOURCE_DIR}/blit_color_msaa.frag diff --git a/src/video_core/host_shaders/block_linear_swizzle_2d_buffer.comp b/src/video_core/host_shaders/block_linear_swizzle_2d_buffer.comp new file mode 100644 index 0000000000..3497a5942c --- /dev/null +++ b/src/video_core/host_shaders/block_linear_swizzle_2d_buffer.comp @@ -0,0 +1,83 @@ +// SPDX-FileCopyrightText: Copyright 2026 Eden Emulator Project +// SPDX-License-Identifier: GPL-3.0-or-later + +#version 430 + +#define BINDING_INPUT_BUFFER 0 +#define BINDING_OUTPUT_BUFFER 1 + +layout(push_constant) uniform PushConstants { + uvec3 dim; + uint bytes_per_block_log2; + + uvec3 origin; + uint layer_stride; + + uint block_size; + uint x_shift; + uint block_height; + uint block_height_mask; +} pc; + +layout(binding = BINDING_INPUT_BUFFER, std430) readonly buffer InputBuffer { + uint in_u32[]; +}; + +layout(binding = BINDING_OUTPUT_BUFFER, std430) buffer OutputBuffer { + uint out_u32[]; +}; + +layout(local_size_x = 16, local_size_y = 8, local_size_z = 1) in; + +const uint GOB_SIZE_X = 64; +const uint GOB_SIZE_Y = 8; + +const uint GOB_SIZE_X_SHIFT = 6; +const uint GOB_SIZE_Y_SHIFT = 3; +const uint GOB_SIZE_SHIFT = GOB_SIZE_X_SHIFT + GOB_SIZE_Y_SHIFT; + +const uvec2 SWIZZLE_MASK = uvec2(GOB_SIZE_X - 1u, GOB_SIZE_Y - 1u); + +uint SwizzleTable(uint pos) { + const uint t[8] = uint[]( + 0x12100200, 0x13110301, 0x16140604, 0x17150705, + 0x1a180a08, 0x1b190b09, 0x1e1c0e0c, 0x1f1d0f0d + ); + const uint i = pos >> 4; + const uint h = (t[i / 4] >> ((i % 4) * 8)) & 0xff; + return (h << 4) | (pos & 0xf); +} + +uint SwizzleOffset(uvec2 pos) { + pos = pos & SWIZZLE_MASK; + return SwizzleTable(pos.y * 64u + pos.x); +} + +void main() { + uvec3 coord = gl_GlobalInvocationID; + if (coord.x >= pc.dim.x || coord.y >= pc.dim.y || coord.z >= pc.dim.z) { + return; + } + + uvec3 pos = coord + pc.origin; + pos.x <<= pc.bytes_per_block_log2; + + uint swizzle = SwizzleOffset(pos.xy); + uint block_y = pos.y >> GOB_SIZE_Y_SHIFT; + + uint offset = 0u; + offset += pos.z * pc.layer_stride; + offset += (block_y >> pc.block_height) * pc.block_size; + offset += (block_y & pc.block_height_mask) << GOB_SIZE_SHIFT; + offset += (pos.x >> GOB_SIZE_X_SHIFT) << pc.x_shift; + offset += swizzle; + + uint words = 1u << (pc.bytes_per_block_log2 - 2u); + uint linear_index = coord.x + coord.y * pc.dim.x + coord.z * pc.dim.x * pc.dim.y; + uint in_idx = linear_index * words; + uint out_idx = offset >> 2u; + + for (uint word = 0u; word < words; ++word) { + out_u32[out_idx + word] = in_u32[in_idx + word]; + } +} diff --git a/src/video_core/renderer_vulkan/vk_compute_pass.cpp b/src/video_core/renderer_vulkan/vk_compute_pass.cpp index fe0a93a94f..fb2e79e42f 100644 --- a/src/video_core/renderer_vulkan/vk_compute_pass.cpp +++ b/src/video_core/renderer_vulkan/vk_compute_pass.cpp @@ -24,6 +24,7 @@ #include "video_core/host_shaders/resolve_conditional_render_comp_spv.h" #include "video_core/host_shaders/vulkan_quad_indexed_comp_spv.h" #include "video_core/host_shaders/vulkan_uint8_comp_spv.h" +#include "video_core/host_shaders/block_linear_swizzle_2d_buffer_comp_spv.h" #include "video_core/host_shaders/block_linear_unswizzle_2d_buffer_comp_spv.h" #include "video_core/host_shaders/block_linear_unswizzle_3d_bcn_comp_spv.h" #include "video_core/host_shaders/block_linear_unswizzle_3d_buffer_comp_spv.h" @@ -35,6 +36,7 @@ #include "video_core/renderer_vulkan/vk_update_descriptor.h" #include "video_core/texture_cache/accelerated_swizzle.h" #include "video_core/texture_cache/types.h" +#include "video_core/texture_cache/util.h" #include "video_core/textures/decoders.h" #include "video_core/vulkan_common/vulkan_device.h" #include "video_core/vulkan_common/vulkan_wrapper.h" @@ -1156,6 +1158,141 @@ void BlockLinearUnswizzle2DPass::UnswizzleFrom( }); } +BlockLinearSwizzle2DPass::BlockLinearSwizzle2DPass( + const Device& device_, Scheduler& scheduler_, DescriptorPool& descriptor_pool_, + StagingBufferPool& staging_buffer_pool_, + ComputePassDescriptorQueue& compute_pass_descriptor_queue_) + : ComputePass(device_, scheduler_, descriptor_pool_, BL2D_BINDINGS, BL2D_TEMPLATE, + BL2D_BANK_INFO, + COMPUTE_PUSH_CONSTANT_RANGE, + BLOCK_LINEAR_SWIZZLE_2D_BUFFER_COMP_SPV), + scheduler{scheduler_}, staging_buffer_pool{staging_buffer_pool_}, + compute_pass_descriptor_queue{compute_pass_descriptor_queue_} {} + +BlockLinearSwizzle2DPass::~BlockLinearSwizzle2DPass() = default; + +void BlockLinearSwizzle2DPass::SwizzleInto(Image& image, VkBuffer dst_buffer, + VkDeviceSize dst_offset, bool foreign_ownership) { + const u32 layers = image.info.resources.layers; + const VkDeviceSize guest_size = image.guest_size_bytes; + const VkDeviceSize input_alignment = + (std::max)(device.GetStorageBufferAlignment(), VkDeviceSize{16}); + auto copies = VideoCommon::FullDownloadCopies(image.info); + const auto swizzles = VideoCommon::FullUploadSwizzles(image.info); + VkDeviceSize total_size = 0; + for (VideoCommon::BufferImageCopy& copy : copies) { + total_size = Common::AlignUp(total_size, input_alignment); + copy.buffer_offset = static_cast(total_size); + total_size += copy.buffer_size; + } + const StagingBufferRef scratch = + staging_buffer_pool.Request(static_cast(total_size), MemoryUsage::DeviceLocal); + const VkBuffer scratch_buffer = scratch.buffer; + const VkDeviceSize scratch_offset = scratch.offset; + image.DownloadMemory(scratch_buffer, static_cast(scratch_offset), + std::span(copies.data(), + copies.size())); + + const u32 queue_family = device.GetGraphicsFamily(); + scheduler.RequestOutsideRenderPassOperationContext(); + scheduler.Record([scratch_buffer, scratch_offset, total_size, dst_buffer, dst_offset, + guest_size, queue_family, foreign_ownership](vk::CommandBuffer cmdbuf) { + const VkBufferMemoryBarrier scratch_barrier{ + .sType = VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER, + .pNext = nullptr, + .srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT, + .dstAccessMask = VK_ACCESS_SHADER_READ_BIT, + .srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, + .dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, + .buffer = scratch_buffer, + .offset = scratch_offset, + .size = total_size, + }; + cmdbuf.PipelineBarrier(VK_PIPELINE_STAGE_TRANSFER_BIT, + VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, scratch_barrier); + if (foreign_ownership) { + const VkBufferMemoryBarrier acquire{ + .sType = VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER, + .pNext = nullptr, + .srcAccessMask = 0, + .dstAccessMask = VK_ACCESS_SHADER_WRITE_BIT, + .srcQueueFamilyIndex = VK_QUEUE_FAMILY_FOREIGN_EXT, + .dstQueueFamilyIndex = queue_family, + .buffer = dst_buffer, + .offset = dst_offset, + .size = guest_size, + }; + cmdbuf.PipelineBarrier(VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, + VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, acquire); + } + }); + + for (size_t level = 0; level < copies.size(); ++level) { + const VideoCommon::SwizzleParameters& sw = swizzles[level]; + const VideoCommon::BufferImageCopy& copy = copies[level]; + const auto params = + VideoCommon::Accelerated::MakeBlockLinearSwizzle2DParams(sw, image.info); + + BlockLinearUnswizzle2DPushConstants pc{}; + pc.dim = {sw.num_tiles.width, sw.num_tiles.height, layers}; + pc.bytes_per_block_log2 = params.bytes_per_block_log2; + pc.origin = params.origin; + pc.layer_stride = params.layer_stride; + pc.block_size = params.block_size; + pc.x_shift = params.x_shift; + pc.block_height = params.block_height; + pc.block_height_mask = params.block_height_mask; + + compute_pass_descriptor_queue.Acquire(scheduler, 2); + compute_pass_descriptor_queue.AddBuffer(scratch_buffer, scratch_offset + copy.buffer_offset, + copy.buffer_size); + compute_pass_descriptor_queue.AddBuffer(dst_buffer, dst_offset + sw.buffer_offset, + guest_size - sw.buffer_offset); + const void* descriptor_data = compute_pass_descriptor_queue.UpdateData(); + const VkDescriptorSet set = descriptor_allocator.Commit(); + + const u32 gx = Common::DivCeil(sw.num_tiles.width, 16u); + const u32 gy = Common::DivCeil(sw.num_tiles.height, 8u); + + scheduler.Record( + [this, set, descriptor_data, pc, gx, gy, layers](vk::CommandBuffer cmdbuf) { + device.GetLogical().UpdateDescriptorSet(set, *descriptor_template, + descriptor_data); + cmdbuf.BindPipeline(VK_PIPELINE_BIND_POINT_COMPUTE, *pipeline); + cmdbuf.BindDescriptorSets(VK_PIPELINE_BIND_POINT_COMPUTE, *layout, 0, set, {}); + cmdbuf.PushConstants(*layout, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(pc), &pc); + cmdbuf.Dispatch(gx, gy, layers); + }); + } + + scheduler.Record([dst_buffer, dst_offset, guest_size, queue_family, + foreign_ownership](vk::CommandBuffer cmdbuf) { + if (foreign_ownership) { + const VkBufferMemoryBarrier release{ + .sType = VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER, + .pNext = nullptr, + .srcAccessMask = VK_ACCESS_SHADER_WRITE_BIT, + .dstAccessMask = 0, + .srcQueueFamilyIndex = queue_family, + .dstQueueFamilyIndex = VK_QUEUE_FAMILY_FOREIGN_EXT, + .buffer = dst_buffer, + .offset = dst_offset, + .size = guest_size, + }; + cmdbuf.PipelineBarrier(VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, + VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, 0, release); + } + static constexpr VkMemoryBarrier HOST_BARRIER{ + .sType = VK_STRUCTURE_TYPE_MEMORY_BARRIER, + .pNext = nullptr, + .srcAccessMask = VK_ACCESS_SHADER_WRITE_BIT, + .dstAccessMask = VK_ACCESS_HOST_READ_BIT, + }; + cmdbuf.PipelineBarrier(VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_HOST_BIT, + 0, HOST_BARRIER); + }); +} + namespace { constexpr u32 BL3DB_BINDING_INPUT_BUFFER = 0; constexpr u32 BL3DB_BINDING_OUTPUT_BUFFER = 1; diff --git a/src/video_core/renderer_vulkan/vk_compute_pass.h b/src/video_core/renderer_vulkan/vk_compute_pass.h index d303161292..c6b34c9c26 100644 --- a/src/video_core/renderer_vulkan/vk_compute_pass.h +++ b/src/video_core/renderer_vulkan/vk_compute_pass.h @@ -187,6 +187,23 @@ private: ComputePassDescriptorQueue& compute_pass_descriptor_queue; }; +class BlockLinearSwizzle2DPass final : public ComputePass { +public: + explicit BlockLinearSwizzle2DPass(const Device& device_, Scheduler& scheduler_, + DescriptorPool& descriptor_pool_, + StagingBufferPool& staging_buffer_pool_, + ComputePassDescriptorQueue& compute_pass_descriptor_queue_); + ~BlockLinearSwizzle2DPass(); + + void SwizzleInto(Image& image, VkBuffer dst_buffer, VkDeviceSize dst_offset, + bool foreign_ownership); + +private: + Scheduler& scheduler; + StagingBufferPool& staging_buffer_pool; + ComputePassDescriptorQueue& compute_pass_descriptor_queue; +}; + class BlockLinearUnswizzle3DBufferPass final : public ComputePass { public: explicit BlockLinearUnswizzle3DBufferPass( diff --git a/src/video_core/renderer_vulkan/vk_texture_cache.cpp b/src/video_core/renderer_vulkan/vk_texture_cache.cpp index 549eedfe14..dd1bfeefcc 100644 --- a/src/video_core/renderer_vulkan/vk_texture_cache.cpp +++ b/src/video_core/renderer_vulkan/vk_texture_cache.cpp @@ -972,6 +972,8 @@ TextureCacheRuntime::TextureCacheRuntime(const Device& device_, Scheduler& sched compute_pass_descriptor_queue); bl3db_unswizzle_pass.emplace(device, scheduler, descriptor_pool, staging_buffer_pool, compute_pass_descriptor_queue); + bl2d_swizzle_pass.emplace(device, scheduler, descriptor_pool, staging_buffer_pool, + compute_pass_descriptor_queue); } void TextureCacheRuntime::Finish() { @@ -3209,20 +3211,26 @@ bool TextureCacheRuntime::CanUploadImageDirectly(const VideoCommon::ImageInfo& i BlockLinearUnswizzle2DPass::IsSupported(device, info); } -bool TextureCacheRuntime::UploadImageDirectly( - Image& image, size_t window_index, u64 window_offset, - std::span swizzles) { +VkBuffer TextureCacheRuntime::ResolveDirectWindow(size_t window_index, u64 window_offset, + u64 size) const { if ((window_offset % device.GetStorageBufferAlignment()) != 0) { - return false; + return VK_NULL_HANDLE; } - if (image.guest_size_bytes > device.GetMaxStorageBufferRange()) { - return false; + if (size > device.GetMaxStorageBufferRange()) { + return VK_NULL_HANDLE; } const HostMemoryImport* const import = memory_allocator.GetHostMemoryImport(); if (import == nullptr || window_index >= import->GetWindowCount()) { - return false; + return VK_NULL_HANDLE; } - const VkBuffer window_buffer = import->GetWindowBuffer(window_index); + return import->GetWindowBuffer(window_index); +} + +bool TextureCacheRuntime::UploadImageDirectly( + Image& image, size_t window_index, u64 window_offset, + std::span swizzles) { + const VkBuffer window_buffer = + ResolveDirectWindow(window_index, window_offset, image.guest_size_bytes); if (window_buffer == VK_NULL_HANDLE) { return false; } @@ -3231,6 +3239,23 @@ bool TextureCacheRuntime::UploadImageDirectly( return true; } +bool TextureCacheRuntime::CanDownloadImageDirectly(const VideoCommon::ImageInfo& info) const { + return bl2d_swizzle_pass.has_value() && BlockLinearUnswizzle2DPass::IsSupported(device, info); +} + +bool TextureCacheRuntime::DownloadImageDirectly(Image& image, size_t window_index, + u64 window_offset) { + const u64 size = (std::max)(image.guest_size_bytes, image.unswizzled_size_bytes); + const VkBuffer window_buffer = ResolveDirectWindow(window_index, window_offset, size); + if (window_buffer == VK_NULL_HANDLE) { + return false; + } + const HostMemoryImport* const import = memory_allocator.GetHostMemoryImport(); + bl2d_swizzle_pass->SwizzleInto(image, window_buffer, static_cast(window_offset), + import->NeedsForeignOwnershipTransfer()); + return true; +} + u64 TextureCacheRuntime::CurrentTick() const noexcept { return scheduler.CurrentTick(); } diff --git a/src/video_core/renderer_vulkan/vk_texture_cache.h b/src/video_core/renderer_vulkan/vk_texture_cache.h index f5f498879c..65b88f6b20 100644 --- a/src/video_core/renderer_vulkan/vk_texture_cache.h +++ b/src/video_core/renderer_vulkan/vk_texture_cache.h @@ -114,6 +114,13 @@ public: bool UploadImageDirectly(Image& image, size_t window_index, u64 window_offset, std::span swizzles); + [[nodiscard]] bool CanDownloadImageDirectly(const VideoCommon::ImageInfo& info) const; + + bool DownloadImageDirectly(Image& image, size_t window_index, u64 window_offset); + + [[nodiscard]] VkBuffer ResolveDirectWindow(size_t window_index, u64 window_offset, + u64 size) const; + [[nodiscard]] u64 CurrentTick() const noexcept; [[nodiscard]] bool IsDirectUploadRetired(u64 tick); @@ -178,6 +185,7 @@ public: std::optional bl3d_unswizzle_pass; std::optional bl2d_unswizzle_pass; std::optional bl3db_unswizzle_pass; + std::optional bl2d_swizzle_pass; const Settings::ResolutionScalingInfo& resolution; std::array, VideoCore::Surface::MaxPixelFormat> view_formats; diff --git a/src/video_core/texture_cache/texture_cache.h b/src/video_core/texture_cache/texture_cache.h index a0d01e5de6..e74a8baae0 100644 --- a/src/video_core/texture_cache/texture_cache.h +++ b/src/video_core/texture_cache/texture_cache.h @@ -146,11 +146,15 @@ void TextureCache

::RunGarbageCollector() { return false; } --num_downloads; - auto map = runtime.DownloadStagingBuffer(image.unswizzled_size_bytes); - const auto copies = FixSmallVectorADL(FullDownloadCopies(image.info)); - image.DownloadMemory(map, copies); - runtime.Finish(); - SwizzleImage(*gpu_memory, image.gpu_addr, image.info, copies, map.mapped_span, swizzle_data_buffer); + if (TryDownloadToUnifiedMemory(image)) { + runtime.Finish(); + } else { + auto map = runtime.DownloadStagingBuffer(image.unswizzled_size_bytes); + const auto copies = FixSmallVectorADL(FullDownloadCopies(image.info)); + image.DownloadMemory(map, copies); + runtime.Finish(); + SwizzleImage(*gpu_memory, image.gpu_addr, image.info, copies, map.mapped_span, swizzle_data_buffer); + } } if (True(image.flags & ImageFlagBits::Tracked)) { UntrackImage(image, image_id); @@ -642,15 +646,24 @@ void TextureCache

::DownloadMemory(DAddr cpu_addr, size_t size) { std::ranges::sort(images, [this](ImageId lhs, ImageId rhs) { return slot_images[lhs].modification_tick < slot_images[rhs].modification_tick; }); + bool pending_unified = false; for (const ImageId image_id : images) { Image& image = slot_images[image_id]; + if (TryDownloadToUnifiedMemory(image)) { + pending_unified = true; + continue; + } auto map = runtime.DownloadStagingBuffer(image.unswizzled_size_bytes); const auto copies = FixSmallVectorADL(FullDownloadCopies(image.info)); image.DownloadMemory(map, copies); runtime.Finish(); + pending_unified = false; SwizzleImage(*gpu_memory, image.gpu_addr, image.info, copies, map.mapped_span, swizzle_data_buffer); } + if (pending_unified) { + runtime.Finish(); + } } template @@ -897,6 +910,10 @@ void TextureCache

::CommitAsyncFlushes() { bool any_none_dma = false; for (PendingDownload& download_info : download_ids) { if (download_info.is_swizzle) { + if (TryDownloadToUnifiedMemory(slot_images[download_info.object_id])) { + download_info.is_unified = true; + continue; + } total_size_bytes += Common::AlignUp(slot_images[download_info.object_id].unswizzled_size_bytes, 64); any_none_dma = true; @@ -907,7 +924,7 @@ void TextureCache

::CommitAsyncFlushes() { if (any_none_dma) { auto download_map = runtime.DownloadStagingBuffer(total_size_bytes, true); for (const PendingDownload& download_info : download_ids) { - if (download_info.is_swizzle) { + if (download_info.is_swizzle && !download_info.is_unified) { Image& image = slot_images[download_info.object_id]; const auto copies = FixSmallVectorADL(FullDownloadCopies(image.info)); image.DownloadMemory(download_map, copies); @@ -939,6 +956,9 @@ void TextureCache

::PopAsyncFlushes() { auto download_map = std::move(async_buffers.front()); for (size_t i = download_ids.size(); i > 0; i--) { auto& download_info = download_ids[i - 1]; + if (download_info.is_unified) { + continue; + } auto& download_buffer = download_map[download_info.async_buffer_id]; if (download_info.is_swizzle) { const ImageBase& image = slot_images[download_info.object_id]; @@ -1172,39 +1192,53 @@ void TextureCache

::RefreshContents(Image& image, ImageId image_id) { } template -bool TextureCache

::TryUploadFromUnifiedMemory([[maybe_unused]] Image& image) { +std::optional> TextureCache

::ResolveUnifiedImageWindow( + [[maybe_unused]] const ImageBase& image) { if constexpr (USE_UNIFIED_MEMORY) { - if (image.direct_upload_blocked || image.guest_size_bytes == 0) { - return false; - } - if (!runtime.IsUnifiedMemoryBindable() || !runtime.CanUploadImageDirectly(image.info)) { - return false; + if (image.guest_size_bytes == 0 || !runtime.IsUnifiedMemoryBindable()) { + return std::nullopt; } const u64 window_size = runtime.UnifiedMemoryWindowSize(); if (window_size == 0) { - return false; + return std::nullopt; } const u8* const first = gpu_memory->GetSpan(image.gpu_addr, image.guest_size_bytes); if (first == nullptr) { - return false; + return std::nullopt; } const u64 phys_offset = static_cast(first - device_memory.GetPhysicalBase()); const u64 unified_base = runtime.UnifiedMemoryBase(); if (phys_offset < unified_base) { - return false; + return std::nullopt; } const u64 relative = phys_offset - unified_base; const u64 unified_size = runtime.UnifiedMemorySize(); if (relative >= unified_size || unified_size - relative < image.guest_size_bytes) { - return false; + return std::nullopt; } const u64 local_offset = relative % window_size; if (window_size - local_offset < image.guest_size_bytes) { + return std::nullopt; + } + return std::pair{static_cast(relative / window_size), local_offset}; + } else { + return std::nullopt; + } +} + +template +bool TextureCache

::TryUploadFromUnifiedMemory([[maybe_unused]] Image& image) { + if constexpr (USE_UNIFIED_MEMORY) { + if (image.direct_upload_blocked || !runtime.CanUploadImageDirectly(image.info)) { + return false; + } + const auto window = ResolveUnifiedImageWindow(image); + if (!window) { return false; } const auto swizzles = FullUploadSwizzles(image.info); - if (!runtime.UploadImageDirectly(image, static_cast(relative / window_size), - local_offset, FixSmallVectorADL(swizzles))) { + if (!runtime.UploadImageDirectly(image, window->first, window->second, + FixSmallVectorADL(swizzles))) { return false; } image.direct_upload_tick = runtime.CurrentTick(); @@ -1214,6 +1248,26 @@ bool TextureCache

::TryUploadFromUnifiedMemory([[maybe_unused]] Image& image) } } +template +bool TextureCache

::TryDownloadToUnifiedMemory([[maybe_unused]] Image& image) { + if constexpr (USE_UNIFIED_MEMORY) { + if (!runtime.CanDownloadImageDirectly(image.info)) { + return false; + } + if (image.info.resources.layers > 1 && + image.info.layer_stride != CalculateLayerStride(image.info)) { + return false; + } + const auto window = ResolveUnifiedImageWindow(image); + if (!window) { + return false; + } + return runtime.DownloadImageDirectly(image, window->first, window->second); + } else { + return false; + } +} + template template void TextureCache

::UploadImageContents(Image& image, StagingBuffer& staging) { diff --git a/src/video_core/texture_cache/texture_cache_base.h b/src/video_core/texture_cache/texture_cache_base.h index 96cd2cdd42..28205cdbe6 100644 --- a/src/video_core/texture_cache/texture_cache_base.h +++ b/src/video_core/texture_cache/texture_cache_base.h @@ -310,8 +310,13 @@ private: void RefreshContents(Image& image, ImageId image_id); + [[nodiscard]] std::optional> ResolveUnifiedImageWindow( + const ImageBase& image); + bool TryUploadFromUnifiedMemory(Image& image); + bool TryDownloadToUnifiedMemory(Image& image); + /// Upload data from guest to an image template void UploadImageContents(Image& image, StagingBuffer& staging_buffer); @@ -471,6 +476,7 @@ private: bool is_swizzle; size_t async_buffer_id; Common::SlotId object_id; + bool is_unified = false; }; Common::SlotVector slot_images; From 36b1b23d40e858cc0c11a52fb7dadf5296fb19dc Mon Sep 17 00:00:00 2001 From: CamilleLaVey Date: Tue, 15 Sep 2026 03:02:55 -0400 Subject: [PATCH 26/27] Experiments on window mirroring + add vertex/index to the virtual page --- src/video_core/buffer_cache/buffer_cache.h | 369 +++++++++++++++--- .../buffer_cache/buffer_cache_base.h | 39 +- src/video_core/memory_manager.cpp | 23 ++ src/video_core/memory_manager.h | 2 + .../renderer_vulkan/vk_buffer_cache.cpp | 294 +++++++++++++- .../renderer_vulkan/vk_buffer_cache.h | 67 +++- .../renderer_vulkan/vk_multi_range_buffer.cpp | 150 ++++++- .../renderer_vulkan/vk_multi_range_buffer.h | 19 +- .../renderer_vulkan/vk_texture_cache.cpp | 54 ++- .../renderer_vulkan/vk_texture_cache.h | 12 +- src/video_core/texture_cache/image_base.h | 3 + src/video_core/texture_cache/texture_cache.h | 120 ++++-- .../texture_cache/texture_cache_base.h | 11 +- src/video_core/vulkan_common/vulkan_device.h | 4 + .../vulkan_common/vulkan_memory_allocator.cpp | 210 +++++++++- .../vulkan_common/vulkan_memory_allocator.h | 49 +++ .../vulkan_common/vulkan_wrapper.cpp | 23 ++ src/video_core/vulkan_common/vulkan_wrapper.h | 5 + 18 files changed, 1296 insertions(+), 158 deletions(-) diff --git a/src/video_core/buffer_cache/buffer_cache.h b/src/video_core/buffer_cache/buffer_cache.h index be85cd63de..b09f26f4f1 100644 --- a/src/video_core/buffer_cache/buffer_cache.h +++ b/src/video_core/buffer_cache/buffer_cache.h @@ -838,6 +838,9 @@ void BufferCache

::BindHostIndexBuffer() { const u32 size = channel_state->index_buffer.size; const auto& draw_state = maxwell3d->draw_manager.draw_state; if (draw_state.inline_index_draw_indexes.empty()) { + if (BindVirtualIndexBuffer()) { + return; + } SynchronizeBuffer(buffer, channel_state->index_buffer.device_addr, size); } else { if constexpr (USE_MEMORY_MAPS_FOR_UPLOADS) { @@ -891,6 +894,7 @@ void BufferCache

::UpdateVertexBufferSlot(u32 index, const Binding& binding) { enabled_vertex_buffers_mask |= (1u << index); } else { enabled_vertex_buffers_mask &= ~(1u << index); + virtual_vertex_buffers_mask &= ~(1u << index); } } @@ -923,8 +927,16 @@ void BufferCache

::BindHostVertexBuffers() { const Binding& binding = VertexBufferSlot(index); Buffer& buffer = slot_buffers[binding.buffer_id]; TouchBuffer(buffer, binding.buffer_id); + if (StageVirtualVertexBuffer(index, binding, false)) { + continue; + } + bool needs_bind = flags[Dirty::VertexBuffer0 + index]; + if (((virtual_vertex_buffers_mask >> index) & 1) != 0) { + virtual_vertex_buffers_mask &= ~(1u << index); + needs_bind = true; + } SynchronizeBuffer(buffer, binding.device_addr, binding.size); - if (!flags[Dirty::VertexBuffer0 + index]) { + if (!needs_bind) { flush_bindings(); continue; } @@ -945,6 +957,7 @@ void BufferCache

::BindHostVertexBuffers() { last_index = index; } flush_bindings(); + BindStagedVertexBuffers(); } else { HostBindings host_bindings; bool any_valid{false}; @@ -953,8 +966,17 @@ void BufferCache

::BindHostVertexBuffers() { const Binding& binding = channel_state->vertex_buffers[index]; Buffer& buffer = slot_buffers[binding.buffer_id]; TouchBuffer(buffer, binding.buffer_id); + if (((enabled_vertex_buffers_mask >> index) & 1) != 0 && + StageVirtualVertexBuffer(index, binding, true)) { + continue; + } + bool needs_bind = flags[Dirty::VertexBuffer0 + index]; + if (((virtual_vertex_buffers_mask >> index) & 1) != 0) { + virtual_vertex_buffers_mask &= ~(1u << index); + needs_bind = true; + } SynchronizeBuffer(buffer, binding.device_addr, binding.size); - if (!flags[Dirty::VertexBuffer0 + index]) { + if (!needs_bind) { continue; } flags[Dirty::VertexBuffer0 + index] = false; @@ -983,6 +1005,7 @@ void BufferCache

::BindHostVertexBuffers() { } runtime.BindVertexBuffers(host_bindings); } + BindStagedVertexBuffers(); } } @@ -1038,9 +1061,12 @@ void BufferCache

::BindHostGraphicsUniformBuffer(size_t stage, u32 index, u32 }(); const bool use_fast_buffer = needs_alignment_stream || (has_host_buffer && size <= channel_state->uniform_buffer_skip_cache_size - && !memory_tracker.IsRegionGpuModified(device_addr, size)); + && !memory_tracker.IsRegionGpuModified(device_addr, size) + && !HasPendingUnifiedWrites(device_addr, size)); if (use_fast_buffer) { - WaitForUnifiedWrites(device_addr, size); + if (needs_alignment_stream) { + WaitForUnifiedWrites(device_addr, size); + } if constexpr (IS_OPENGL) { if (runtime.HasFastBufferSubData()) { // Fast path for Nvidia @@ -1136,6 +1162,34 @@ void BufferCache

::ResolveMultiRangeStorage(Binding& binding, bool is_written, template bool BufferCache

::BindMultiRangeStorage(const Binding& binding, bool is_written, std::span pool) { + if constexpr (requires { runtime.BindMultiRangeStorageBuffer(u64{}, bool{}); }) { + const u64 key = GeometryKey(binding.gpu_addr, 0); + if (!PushMultiRangeSources(binding, is_written, pool, key)) { + return false; + } + return runtime.BindMultiRangeStorageBuffer(key, is_written); + } else { + return false; + } +} + +template +u64 BufferCache

::GeometryKey(GPUVAddr gpu_addr, u64 salt) const { + return ((static_cast(gpu_memory->GetID()) << 48) ^ gpu_addr) ^ salt; +} + +template +u32 BufferCache

::ClampToMappedRange(GPUVAddr gpu_addr, u32 size) const { + const size_t mapped = gpu_memory->MaxMappedRange(gpu_addr, size); + if (mapped == 0 || mapped >= size) { + return size; + } + return static_cast(mapped); +} + +template +bool BufferCache

::PushMultiRangeSources(const Binding& binding, bool is_written, + std::span pool, u64 key) { if constexpr (requires { runtime.BindMultiRangeStorageBuffer(u64{}, bool{}); }) { if (binding.segment_count < 2) { return false; @@ -1143,23 +1197,188 @@ bool BufferCache

::BindMultiRangeStorage(const Binding& binding, bool is_writt if (binding.segment_first + binding.segment_count > pool.size()) { return false; } - const u64 key = (static_cast(gpu_memory->GetID()) << 48) ^ binding.gpu_addr; + const std::span segments = + pool.subspan(binding.segment_first, binding.segment_count); + boost::container::small_vector buffer_ids; + for (const MultiRangeSegment& segment : segments) { + BufferId buffer_id = segment.buffer_id; + if (!buffer_id) { + buffer_id = page_table[segment.device_addr >> CACHING_PAGEBITS]; + } + if (!buffer_id || + !slot_buffers[buffer_id].IsInBounds(segment.device_addr, segment.size)) { + return false; + } + buffer_ids.push_back(buffer_id); + } runtime.ResetMultiRange(); for (u32 index = 0; index < binding.segment_count; ++index) { - const MultiRangeSegment& segment = pool[binding.segment_first + index]; - Buffer& buffer = slot_buffers[segment.buffer_id]; - TouchBuffer(buffer, segment.buffer_id); - if (SynchronizeBuffer(buffer, segment.device_addr, segment.size)) { + const MultiRangeSegment& segment = segments[index]; + const BufferId buffer_id = buffer_ids[index]; + Buffer& buffer = slot_buffers[buffer_id]; + TouchBuffer(buffer, buffer_id); + if (!SynchronizeBuffer(buffer, segment.device_addr, segment.size)) { runtime.InvalidateMultiRange(key); } const u32 offset = buffer.Offset(segment.device_addr); buffer.MarkUsage(offset, segment.size); if (is_written) { - MarkWrittenBuffer(segment.buffer_id, segment.device_addr, segment.size); + MarkWrittenBuffer(buffer_id, segment.device_addr, segment.size); } runtime.PushMultiRangeSource(buffer, offset, segment.size); } - return runtime.BindMultiRangeStorageBuffer(key, is_written); + return true; + } else { + return false; + } +} + +template +bool BufferCache

::TryResolveUnifiedSegments( + [[maybe_unused]] const Binding& binding, + [[maybe_unused]] std::span pool, + [[maybe_unused]] UnifiedExtents& extents) { + if constexpr (USE_UNIFIED_MEMORY) { + extents.clear(); + const auto push = [&](DAddr device_addr, u64 size) { + const std::optional relative = TryResolveUnifiedRange(device_addr, size); + if (!relative) { + return false; + } + if (!extents.empty() && extents.back().relative + extents.back().size == *relative) { + extents.back().size += size; + return true; + } + extents.push_back(UnifiedExtent{.relative = *relative, .size = size}); + return true; + }; + if (binding.segment_count < 2) { + return push(binding.device_addr, binding.size); + } + if (binding.segment_first + binding.segment_count > pool.size()) { + return false; + } + for (const MultiRangeSegment& segment : + pool.subspan(binding.segment_first, binding.segment_count)) { + if (!push(segment.device_addr, segment.size)) { + return false; + } + } + return true; + } else { + return false; + } +} + +template +void BufferCache

::ResolveGeometrySegments([[maybe_unused]] bool is_indexed) { + if constexpr (requires { runtime.BindStagedVertexBuffers(); }) { + const auto& draw_state = maxwell3d->draw_manager.draw_state; + if (is_indexed && draw_state.inline_index_draw_indexes.empty()) { + ResolveMultiRangeStorage(channel_state->index_buffer, false, graphics_segments); + } + u32 enabled_mask = enabled_vertex_buffers_mask; + while (enabled_mask != 0) { + const u32 index = std::countr_zero(enabled_mask); + enabled_mask &= enabled_mask - 1; + Binding& slot = VertexBufferSlot(index); + ResolveMultiRangeStorage(slot, false, graphics_segments); + Binding& channel_binding = channel_state->vertex_buffers[index]; + channel_binding.segment_first = slot.segment_first; + channel_binding.segment_count = slot.segment_count; + } + } +} + +template +bool BufferCache

::StageVirtualVertexBuffer([[maybe_unused]] u32 index, + [[maybe_unused]] const Binding& binding, + [[maybe_unused]] bool force) { + if constexpr (requires { runtime.BindStagedVertexBuffers(); }) { + auto& flags = maxwell3d->dirty.flags; + const bool rebind = force || flags[Dirty::VertexBuffer0 + index] || + ((virtual_vertex_buffers_mask >> index) & 1) == 0; + const u32 stride = maxwell3d->regs.vertex_streams[index].stride; + const u64 salt = VERTEX_GEOMETRY_SALT + (u64{index} << 40); + bool staged = false; + if constexpr (USE_UNIFIED_MEMORY) { + UnifiedExtents extents; + if (TryResolveUnifiedSegments(binding, graphics_segments, extents)) { + const u64 view_key = GeometryKey(binding.gpu_addr, salt + VIEW_GEOMETRY_SALT); + staged = runtime.StageUnifiedVertexBuffer(index, view_key, extents, binding.size, + stride, rebind); + } + } + if (!staged) { + const u64 key = GeometryKey(binding.gpu_addr, salt); + if (PushMultiRangeSources(binding, false, graphics_segments, key)) { + staged = runtime.StageMultiRangeVertexBuffer(index, key, binding.size, stride, + rebind); + } + } + if (!staged) { + return false; + } + flags[Dirty::VertexBuffer0 + index] = false; + virtual_vertex_buffers_mask |= 1u << index; + return true; + } else { + return false; + } +} + +template +bool BufferCache

::BindVirtualIndexBuffer() { + if constexpr (!HAS_FULL_INDEX_AND_PRIMITIVE_SUPPORT && + requires { runtime.BindStagedVertexBuffers(); }) { + const Binding& binding = channel_state->index_buffer; + const auto& draw_state = maxwell3d->draw_manager.draw_state; + const auto& index_ref = draw_state.index_buffer; + if constexpr (USE_UNIFIED_MEMORY) { + UnifiedExtents extents; + const u64 view_key = + GeometryKey(binding.gpu_addr, INDEX_GEOMETRY_SALT + VIEW_GEOMETRY_SALT); + if (TryResolveUnifiedSegments(binding, graphics_segments, extents) && + runtime.BindUnifiedIndexBuffer(draw_state.topology, index_ref.format, + index_ref.first, index_ref.count, view_key, + extents, binding.size)) { + return true; + } + } + const u64 key = GeometryKey(binding.gpu_addr, INDEX_GEOMETRY_SALT); + if (!PushMultiRangeSources(binding, false, graphics_segments, key)) { + return false; + } + return runtime.BindMultiRangeIndexBuffer(draw_state.topology, index_ref.format, + index_ref.first, index_ref.count, key, + binding.size); + } else { + return false; + } +} + +template +void BufferCache

::BindStagedVertexBuffers() { + if constexpr (requires { runtime.BindStagedVertexBuffers(); }) { + runtime.BindStagedVertexBuffers(); + } +} + +template +bool BufferCache

::HasPendingUnifiedWrites([[maybe_unused]] DAddr device_addr, + [[maybe_unused]] u64 size) { + if constexpr (USE_UNIFIED_MEMORY) { + if (unified_written_ranges.Empty()) { + return false; + } + if (runtime.KnownGpuTick() >= unified_write_tick) { + unified_written_ranges.Clear(); + return false; + } + bool overlaps = false; + unified_written_ranges.ForEachInRange(device_addr, size, + [&overlaps](DAddr, DAddr) { overlaps = true; }); + return overlaps; } else { return false; } @@ -1169,13 +1388,7 @@ template void BufferCache

::WaitForUnifiedWrites([[maybe_unused]] DAddr device_addr, [[maybe_unused]] u64 size) { if constexpr (USE_UNIFIED_MEMORY) { - if (unified_written_ranges.Empty()) { - return; - } - bool overlaps = false; - unified_written_ranges.ForEachInRange(device_addr, size, - [&overlaps](DAddr, DAddr) { overlaps = true; }); - if (!overlaps) { + if (!HasPendingUnifiedWrites(device_addr, size)) { return; } runtime.Wait(unified_write_tick); @@ -1183,12 +1396,63 @@ void BufferCache

::WaitForUnifiedWrites([[maybe_unused]] DAddr device_addr, } } +template +template +bool BufferCache

::CopyUnifiedWrites([[maybe_unused]] Buffer& buffer, + [[maybe_unused]] DAddr device_addr, + [[maybe_unused]] u64 size, + [[maybe_unused]] Func&& add_upload) { + if constexpr (USE_UNIFIED_MEMORY) { + if (!HasPendingUnifiedWrites(device_addr, size)) { + return false; + } + boost::container::small_vector, 4> overlaps; + unified_written_ranges.ForEachInRange(device_addr, size, + [&overlaps](DAddr start, DAddr end) { + overlaps.emplace_back(start, end); + }); + const DAddr buffer_start = buffer.CpuAddr(); + boost::container::small_vector window_ids; + UnifiedWindowGroups groups; + for (const auto& [start, end] : overlaps) { + if (!ResolveUnifiedWindows(start, start - buffer_start, end - start, window_ids, + groups)) { + runtime.Wait(unified_write_tick); + unified_written_ranges.Clear(); + return false; + } + } + for (size_t i = 0; i < window_ids.size(); ++i) { + const std::span group_span(groups[i].data(), groups[i].size()); + runtime.CopyFromUnifiedMemory(window_ids[i], buffer, group_span); + } + DAddr cursor = device_addr; + for (const auto& [start, end] : overlaps) { + buffer.MarkUsage(start - buffer_start, end - start); + if (start > cursor) { + add_upload(cursor, start - cursor); + } + cursor = end; + } + if (cursor < device_addr + size) { + add_upload(cursor, device_addr + size - cursor); + } + return true; + } else { + return false; + } +} + template bool BufferCache

::BindUnifiedStorage([[maybe_unused]] const Binding& binding, [[maybe_unused]] bool is_written) { if constexpr (USE_UNIFIED_MEMORY) { - const auto window = TryResolveUnifiedRange(binding.device_addr, binding.size); - if (!window || !runtime.IsUnifiedStorageRange(binding.size, window->offset)) { + const auto relative = TryResolveUnifiedRange(binding.device_addr, binding.size); + if (!relative) { + return false; + } + const auto range = runtime.ResolveUnifiedStorage(*relative, binding.size); + if (!range) { return false; } if (is_written) { @@ -1197,9 +1461,8 @@ bool BufferCache

::BindUnifiedStorage([[maybe_unused]] const Binding& binding, unified_write_tick = runtime.CurrentTick(); uncommitted_unified_writes = true; } - runtime.BindStorageBuffer(runtime.UnifiedWindowBuffer(window->window), - runtime.UnifiedWindowAddress(window->window), - static_cast(window->offset), binding.size, is_written); + runtime.BindStorageBuffer(range->buffer, range->address, range->offset, + binding.size, is_written); return true; } else { return false; @@ -1421,6 +1684,7 @@ void BufferCache

::DoUpdateGraphicsBuffers(bool is_indexed) { UpdateIndexBuffer(); } UpdateVertexBuffers(); + ResolveGeometrySegments(is_indexed); UpdateTransformFeedbackBuffers(); for (size_t stage = 0; stage < NUM_STAGES; ++stage) { UpdateUniformBuffers(stage); @@ -1477,13 +1741,17 @@ void BufferCache

::UpdateIndexBuffer() { const std::optional device_addr = gpu_memory->GpuToCpuAddress(gpu_addr_begin); const u32 address_size = static_cast(gpu_addr_end - gpu_addr_begin); const u32 draw_size = (index_buffer_ref.count + index_buffer_ref.first) * u32(index_buffer_ref.FormatSizeInBytes()); - const u32 size = (std::min)(address_size, draw_size); + u32 size = (std::min)(address_size, draw_size); if (size == 0 || !device_addr) { channel_state->index_buffer = NULL_BINDING; return; } + if constexpr (requires { runtime.BindStagedVertexBuffers(); }) { + size = ClampToMappedRange(gpu_addr_begin, size); + } channel_state->index_buffer = Binding{ .device_addr = *device_addr, + .gpu_addr = gpu_addr_begin, .size = size, .buffer_id = FindBuffer(*device_addr, size, false), }; @@ -1521,10 +1789,13 @@ void BufferCache

::UpdateVertexBuffer(u32 index) { } if (!gpu_memory->IsWithinGPUAddressRange(gpu_addr_end) || size >= 64_MiB) { size = static_cast(gpu_memory->MaxContinuousRange(gpu_addr_begin, size)); + } else if constexpr (requires { runtime.BindStagedVertexBuffers(); }) { + size = ClampToMappedRange(gpu_addr_begin, size); } const BufferId buffer_id = FindBuffer(*device_addr, size, false); const Binding binding{ .device_addr = *device_addr, + .gpu_addr = gpu_addr_begin, .size = size, .buffer_id = buffer_id, }; @@ -1881,19 +2152,30 @@ bool BufferCache

::SynchronizeBuffer(Buffer& buffer, DAddr device_addr, u32 si u64 total_size_bytes = 0; u64 largest_copy = 0; const DAddr buffer_start = buffer.cpu_addr_cached; - memory_tracker.ForEachUploadRange(device_addr, size, [&](u64 device_addr_out, u64 range_size) { + const auto add_upload = [&](u64 upload_addr, u64 upload_size) { upload_copies.push_back(BufferCopy{ .src_offset = total_size_bytes, - .dst_offset = device_addr_out - buffer_start, - .size = range_size, + .dst_offset = upload_addr - buffer_start, + .size = upload_size, }); - total_size_bytes += range_size; - largest_copy = (std::max)(largest_copy, range_size); + total_size_bytes += upload_size; + largest_copy = (std::max)(largest_copy, upload_size); + }; + bool copied_from_windows = false; + memory_tracker.ForEachUploadRange(device_addr, size, [&](u64 device_addr_out, u64 range_size) { + if (CopyUnifiedWrites(buffer, device_addr_out, range_size, add_upload)) { + copied_from_windows = true; + return; + } + add_upload(device_addr_out, range_size); }); if (total_size_bytes == 0) { + if (copied_from_windows) { + any_buffer_uploaded = true; + return false; + } return true; } - WaitForUnifiedWrites(device_addr, size); const std::span copies_span(upload_copies.data(), upload_copies.size()); UploadMemory(buffer, total_size_bytes, largest_copy, copies_span); any_buffer_uploaded = true; @@ -2004,17 +2286,12 @@ bool BufferCache

::ResolveUnifiedWindows( } template -std::optional::UnifiedWindowRange> -BufferCache

::TryResolveUnifiedRange([[maybe_unused]] DAddr device_addr, - [[maybe_unused]] u64 size) { +std::optional BufferCache

::TryResolveUnifiedRange([[maybe_unused]] DAddr device_addr, + [[maybe_unused]] u64 size) { if constexpr (USE_UNIFIED_MEMORY) { if (size == 0 || !runtime.IsUnifiedMemoryBindable()) { return std::nullopt; } - const u64 window_size = runtime.UnifiedMemoryWindowSize(); - if (window_size == 0) { - return std::nullopt; - } const u8* const first = device_memory.GetSpan(device_addr, size); if (first == nullptr) { return std::nullopt; @@ -2029,18 +2306,11 @@ BufferCache

::TryResolveUnifiedRange([[maybe_unused]] DAddr device_addr, if (relative >= unified_size || unified_size - relative < size) { return std::nullopt; } - const u64 local_offset = relative % window_size; - if (window_size - local_offset < size) { - return std::nullopt; - } if (memory_tracker.IsRegionGpuModified(device_addr, size) || IsRegionGpuModified(device_addr, size)) { return std::nullopt; } - return UnifiedWindowRange{ - .window = static_cast(relative / window_size), - .offset = local_offset, - }; + return relative; } else { return std::nullopt; } @@ -2245,6 +2515,15 @@ void BufferCache

::DeleteBuffer(BufferId buffer_id, bool do_not_mark) { replace(channel_state->transform_feedback_buffers); replace(channel_state->compute_uniform_buffers); replace(channel_state->compute_storage_buffers); + const auto drop_segments = [buffer_id](std::vector& pool) { + for (MultiRangeSegment& segment : pool) { + if (segment.buffer_id == buffer_id) { + segment.buffer_id = BufferId{}; + } + } + }; + drop_segments(graphics_segments); + drop_segments(compute_segments); // Mark the whole buffer as CPU written to stop tracking CPU writes if (!do_not_mark) { diff --git a/src/video_core/buffer_cache/buffer_cache_base.h b/src/video_core/buffer_cache/buffer_cache_base.h index 0f2323b99f..211b67a883 100644 --- a/src/video_core/buffer_cache/buffer_cache_base.h +++ b/src/video_core/buffer_cache/buffer_cache_base.h @@ -96,6 +96,11 @@ struct MultiRangeSegment { u32 size{}; }; +struct UnifiedExtent { + u64 relative{}; + u64 size{}; +}; + struct TextureBufferBinding : Binding { PixelFormat format; }; @@ -192,6 +197,9 @@ class BufferCache : public VideoCommon::ChannelSetupCaches pool, u64 key); + void ResolveMultiRangeStorage(Binding& binding, bool is_written, std::vector& pool); @@ -468,15 +479,32 @@ private: bool TryUnifiedDownloadMemory(Buffer& buffer, std::span copies); - struct UnifiedWindowRange { - size_t window; - u64 offset; - }; + std::optional TryResolveUnifiedRange(DAddr device_addr, u64 size); - std::optional TryResolveUnifiedRange(DAddr device_addr, u64 size); + using UnifiedExtents = boost::container::small_vector; + + bool TryResolveUnifiedSegments(const Binding& binding, std::span pool, + UnifiedExtents& extents); + + void ResolveGeometrySegments(bool is_indexed); + + bool StageVirtualVertexBuffer(u32 index, const Binding& binding, bool force); + + bool BindVirtualIndexBuffer(); + + void BindStagedVertexBuffers(); + + [[nodiscard]] u64 GeometryKey(GPUVAddr gpu_addr, u64 salt) const; + + [[nodiscard]] u32 ClampToMappedRange(GPUVAddr gpu_addr, u32 size) const; + + bool HasPendingUnifiedWrites(DAddr device_addr, u64 size); void WaitForUnifiedWrites(DAddr device_addr, u64 size); + template + bool CopyUnifiedWrites(Buffer& buffer, DAddr device_addr, u64 size, Func&& add_upload); + using UnifiedWindowGroups = boost::container::small_vector, 4>; @@ -528,6 +556,7 @@ private: u32 last_index_count = 0; u32 enabled_vertex_buffers_mask = 0; + u32 virtual_vertex_buffers_mask = 0; u64 vertex_buffers_serial = 0; std::array v_buffer{}; diff --git a/src/video_core/memory_manager.cpp b/src/video_core/memory_manager.cpp index d5838a387d..9556115426 100644 --- a/src/video_core/memory_manager.cpp +++ b/src/video_core/memory_manager.cpp @@ -529,6 +529,29 @@ size_t MemoryManager::MaxContinuousRange(GPUVAddr gpu_addr, size_t size) const { return range_so_far; } +size_t MemoryManager::MaxMappedRange(GPUVAddr gpu_addr, size_t size) const { + size_t range_so_far = 0; + bool stopped{false}; + auto stop = [&]([[maybe_unused]] std::size_t page_index, [[maybe_unused]] std::size_t offset, + [[maybe_unused]] std::size_t copy_amount) { + stopped = true; + return true; + }; + auto accumulate = [&]([[maybe_unused]] std::size_t page_index, + [[maybe_unused]] std::size_t offset, std::size_t copy_amount) { + range_so_far += copy_amount; + return false; + }; + auto check_short_pages = [&](std::size_t page_index, std::size_t offset, + std::size_t copy_amount) { + GPUVAddr base = (page_index << big_page_bits) + offset; + MemoryOperation(base, copy_amount, false, accumulate, stop, stop); + return stopped; + }; + MemoryOperation(gpu_addr, size, true, accumulate, stop, check_short_pages); + return range_so_far; +} + size_t MemoryManager::GetMemoryLayoutSize(GPUVAddr gpu_addr, size_t max_size) const { std::unique_lock lock(guard); return kind_map.GetContinuousSizeFrom(gpu_addr); diff --git a/src/video_core/memory_manager.h b/src/video_core/memory_manager.h index 08978567d2..5eabcb2f8c 100644 --- a/src/video_core/memory_manager.h +++ b/src/video_core/memory_manager.h @@ -141,6 +141,8 @@ public: size_t MaxContinuousRange(GPUVAddr gpu_addr, size_t size) const; + size_t MaxMappedRange(GPUVAddr gpu_addr, size_t size) const; + bool IsWithinGPUAddressRange(GPUVAddr gpu_addr) const { return gpu_addr < address_space_size; } diff --git a/src/video_core/renderer_vulkan/vk_buffer_cache.cpp b/src/video_core/renderer_vulkan/vk_buffer_cache.cpp index 595acab8da..655db98450 100644 --- a/src/video_core/renderer_vulkan/vk_buffer_cache.cpp +++ b/src/video_core/renderer_vulkan/vk_buffer_cache.cpp @@ -12,6 +12,7 @@ #include #include +#include "common/alignment.h" #include "video_core/buffer_cache/buffer_cache_base.h" #include "video_core/renderer_vulkan/vk_buffer_cache.h" @@ -435,6 +436,11 @@ void BufferCacheRuntime::TryEnableUnifiedMemory(void* base, size_t size, size_t hardware_buffer_base) { unified_memory = memory_allocator.CreateHostMemoryImport( base, size, hardware_buffers, hardware_buffer_window, hardware_buffer_base); + if (unified_memory) { + unified_memory->CreateMirror(scheduler.submit_mutex, + device.GetSparseAddressSpaceSize() / 2); + multi_range_buffers.ReserveSparseAddressSpace(unified_memory->GetMirrorSize()); + } } void BufferCacheRuntime::CopyToUnifiedMemory( @@ -452,6 +458,74 @@ void BufferCacheRuntime::CopyToUnifiedMemory( std::ranges::transform(copies, pending.copies.begin(), MakeBufferCopy); } +void BufferCacheRuntime::CopyFromUnifiedMemory( + size_t window_index, VkBuffer dst_buffer, std::span copies) { + if (!unified_memory || dst_buffer == VK_NULL_HANDLE || copies.empty() || + window_index >= unified_memory->GetWindowCount()) { + return; + } + const VkBuffer window_buffer = unified_memory->GetWindowBuffer(window_index); + if (window_buffer == VK_NULL_HANDLE) { + return; + } + const bool foreign = unified_memory->NeedsForeignOwnershipTransfer(); + const u32 queue_family = device.GetGraphicsFamily(); + boost::container::small_vector vk_copies; + WindowRanges ranges; + for (const VideoCommon::BufferCopy& copy : copies) { + vk_copies.push_back(VkBufferCopy{ + .srcOffset = static_cast(copy.dst_offset), + .dstOffset = static_cast(copy.src_offset), + .size = static_cast(copy.size), + }); + ranges.emplace_back(copy.dst_offset, copy.dst_offset + copy.size); + } + CoalesceWindowRanges(ranges); + boost::container::small_vector acquire; + boost::container::small_vector release; + if (foreign) { + for (const WindowRange& range : ranges) { + acquire.push_back(VkBufferMemoryBarrier{ + .sType = VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER, + .pNext = nullptr, + .srcAccessMask = 0, + .dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT, + .srcQueueFamilyIndex = VK_QUEUE_FAMILY_FOREIGN_EXT, + .dstQueueFamilyIndex = queue_family, + .buffer = window_buffer, + .offset = range.first, + .size = range.second - range.first, + }); + release.push_back(VkBufferMemoryBarrier{ + .sType = VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER, + .pNext = nullptr, + .srcAccessMask = VK_ACCESS_TRANSFER_READ_BIT, + .dstAccessMask = 0, + .srcQueueFamilyIndex = queue_family, + .dstQueueFamilyIndex = VK_QUEUE_FAMILY_FOREIGN_EXT, + .buffer = window_buffer, + .offset = range.first, + .size = range.second - range.first, + }); + } + } + scheduler.RequestOutsideRenderPassOperationContext(); + scheduler.Record([window_buffer, dst_buffer, vk_copies, acquire = std::move(acquire), + release = std::move(release)](vk::CommandBuffer cmdbuf) { + if (!acquire.empty()) { + cmdbuf.PipelineBarrier(VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, + VK_PIPELINE_STAGE_TRANSFER_BIT, 0, {}, + VideoCommon::FixSmallVectorADL(acquire), {}); + } + cmdbuf.CopyBuffer(window_buffer, dst_buffer, VideoCommon::FixSmallVectorADL(vk_copies)); + if (!release.empty()) { + cmdbuf.PipelineBarrier(VK_PIPELINE_STAGE_TRANSFER_BIT, + VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, 0, {}, + VideoCommon::FixSmallVectorADL(release), {}); + } + }); +} + void BufferCacheRuntime::FlushUnifiedMemoryCopies() { if (pending_unified_copies.empty()) { return; @@ -733,17 +807,17 @@ void BufferCacheRuntime::ClearBuffer(VkBuffer dest_buffer, u32 offset, size_t si }); } -bool BufferCacheRuntime::BindMultiRangeStorageBuffer(u64 key, bool is_written) { +MultiRangeRef BufferCacheRuntime::AcquireMultiRange(u64 key, bool require_sparse) { if (multi_range_sources.empty() || multi_range_total == 0) { - return false; + return MultiRangeRef{}; } const MultiRangeRef ref = multi_range_buffers.Get(device, scheduler, memory_allocator, key, multi_range_sources, multi_range_total); if (ref.handle == VK_NULL_HANDLE) { - return false; + return MultiRangeRef{}; } - if (is_written && !ref.sparse) { - return false; + if (require_sparse && !ref.sparse) { + return MultiRangeRef{}; } if (ref.needs_gather) { PreCopyBarrier(); @@ -760,10 +834,220 @@ bool BufferCacheRuntime::BindMultiRangeStorageBuffer(u64 key, bool is_written) { PostCopyBarrier(); multi_range_buffers.MarkGathered(key); } + return ref; +} + +bool BufferCacheRuntime::BindMultiRangeStorageBuffer(u64 key, bool is_written) { + const MultiRangeRef ref = AcquireMultiRange(key, is_written); + if (ref.handle == VK_NULL_HANDLE) { + return false; + } guest_descriptor_queue.AddBuffer(ref.handle, ref.address, 0, ref.size); return true; } +std::optional BufferCacheRuntime::ResolveUnifiedExtents( + u64 key, std::span extents, u32 size) { + if (extents.size() == 1) { + return unified_memory->ResolveRange(extents.front().relative, size); + } + return AcquireUnifiedView(key, extents); +} + +std::optional BufferCacheRuntime::AcquireUnifiedView( + u64 key, std::span extents) { + const VkBufferUsageFlags usage = unified_memory->GetViewUsage(); + if (usage == 0 || !multi_range_buffers.use_sparse || extents.size() < 2) { + return std::nullopt; + } + const VkDeviceSize block = multi_range_buffers.block_size; + boost::container::small_vector sources; + VkDeviceSize total = 0; + VkDeviceSize padding = 0; + for (size_t index = 0; index < extents.size(); ++index) { + VkDeviceSize begin = extents[index].relative; + VkDeviceSize end = begin + extents[index].size; + if (index == 0) { + padding = begin % block; + begin -= padding; + } else if ((begin % block) != 0) { + return std::nullopt; + } + if (index + 1 == extents.size()) { + end = Common::AlignUp(end, block); + } else if ((end % block) != 0) { + return std::nullopt; + } + while (begin < end) { + const auto memory = unified_memory->ResolveViewMemory(begin); + if (!memory || (memory->offset % block) != 0) { + return std::nullopt; + } + const VkDeviceSize length = (std::min)(end - begin, memory->available); + if ((length % block) != 0) { + return std::nullopt; + } + sources.push_back(MultiRangeSource{ + .handle = memory->buffer, + .memory = memory->memory, + .memory_offset = 0, + .offset = memory->offset, + .size = length, + .write_tick = 0, + .memory_type = memory->memory_type, + }); + total += length; + begin += length; + } + } + const MultiRangeRef ref = multi_range_buffers.GetView( + device, scheduler, key, sources, total, usage, + VK_EXTERNAL_MEMORY_HANDLE_TYPE_ANDROID_HARDWARE_BUFFER_BIT_ANDROID); + if (ref.handle == VK_NULL_HANDLE) { + return std::nullopt; + } + return HostMemoryImport::Range{ + .buffer = ref.handle, + .address = ref.address, + .offset = padding, + }; +} + +bool BufferCacheRuntime::StageUnifiedVertexBuffer( + u32 index, u64 key, std::span extents, u32 size, u32 stride, + bool force) { + if (!unified_memory || + (unified_memory->GetUsage() & VK_BUFFER_USAGE_VERTEX_BUFFER_BIT) == 0) { + return false; + } + const auto range = ResolveUnifiedExtents(key, extents, size); + if (!range) { + return false; + } + StageVertexBuffer( + StagedVertexBuffer{ + .index = index, + .buffer = range->buffer, + .offset = range->offset, + .size = size, + .stride = stride, + }, + force); + return true; +} + +bool BufferCacheRuntime::StageMultiRangeVertexBuffer(u32 index, u64 key, u32 size, u32 stride, + bool force) { + const MultiRangeRef ref = AcquireMultiRange(key, false); + if (ref.handle == VK_NULL_HANDLE) { + return false; + } + StageVertexBuffer( + StagedVertexBuffer{ + .index = index, + .buffer = ref.handle, + .offset = 0, + .size = size, + .stride = stride, + }, + force); + return true; +} + +void BufferCacheRuntime::StageVertexBuffer(const StagedVertexBuffer& target, bool force) { + StagedVertexBuffer& bound = bound_vertex_buffers[target.index]; + if (!force && bound == target) { + return; + } + bound = target; + if (target.index < device.GetMaxVertexInputBindings()) { + staged_vertex_buffers.push_back(target); + } +} + +void BufferCacheRuntime::BindStagedVertexBuffers() { + if (staged_vertex_buffers.empty()) { + return; + } + scheduler.Record([staged = staged_vertex_buffers, + extended = device.IsExtExtendedDynamicStateSupported()]( + vk::CommandBuffer cmdbuf) { + std::array buffers{}; + std::array offsets{}; + std::array sizes{}; + std::array strides{}; + size_t begin = 0; + while (begin < staged.size()) { + const u32 first = staged[begin].index; + u32 count = 0; + while (begin + count < staged.size() && staged[begin + count].index == first + count) { + const StagedVertexBuffer& entry = staged[begin + count]; + buffers[count] = entry.buffer; + offsets[count] = entry.offset; + sizes[count] = entry.size; + strides[count] = entry.stride; + ++count; + } + if (extended) { + cmdbuf.BindVertexBuffers2EXT(first, count, buffers.data(), offsets.data(), + sizes.data(), strides.data()); + } else { + cmdbuf.BindVertexBuffers(first, count, buffers.data(), offsets.data()); + } + begin += count; + } + }); + staged_vertex_buffers.clear(); +} + +bool BufferCacheRuntime::IsIndexRangeUsable(PrimitiveTopology topology, IndexFormat index_format, + VkDeviceSize offset, u32 size) const { + const VkIndexType vk_index_type = MaxwellToVK::IndexFormat(index_format); + const bool is_quad = + topology == PrimitiveTopology::Quads || topology == PrimitiveTopology::QuadStrip; + const bool is_emulated_uint8 = + vk_index_type == VK_INDEX_TYPE_UINT8_EXT && !device.IsExtIndexTypeUint8Supported(); + if (is_quad || is_emulated_uint8) { + return size <= device.GetMaxStorageBufferRange() && + (offset % device.GetStorageBufferAlignment()) == 0; + } + return (offset % BytesPerIndex(vk_index_type)) == 0; +} + +bool BufferCacheRuntime::BindUnifiedIndexBuffer(PrimitiveTopology topology, + IndexFormat index_format, u32 base_vertex, + u32 num_indices, u64 key, + std::span extents, + u32 size) { + constexpr VkBufferUsageFlags GeometryUsage = + VK_BUFFER_USAGE_INDEX_BUFFER_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT; + if (!unified_memory || (unified_memory->GetUsage() & GeometryUsage) != GeometryUsage) { + return false; + } + const auto range = ResolveUnifiedExtents(key, extents, size); + if (!range || range->offset > (std::numeric_limits::max)() - size || + !IsIndexRangeUsable(topology, index_format, range->offset, size)) { + return false; + } + BindIndexBuffer(topology, index_format, base_vertex, num_indices, range->buffer, + static_cast(range->offset), size); + return true; +} + +bool BufferCacheRuntime::BindMultiRangeIndexBuffer(PrimitiveTopology topology, + IndexFormat index_format, u32 base_vertex, + u32 num_indices, u64 key, u32 size) { + if (!IsIndexRangeUsable(topology, index_format, 0, size)) { + return false; + } + const MultiRangeRef ref = AcquireMultiRange(key, false); + if (ref.handle == VK_NULL_HANDLE) { + return false; + } + BindIndexBuffer(topology, index_format, base_vertex, num_indices, ref.handle, 0, size); + return true; +} + void BufferCacheRuntime::BindIndexBuffer(PrimitiveTopology topology, IndexFormat index_format, u32 base_vertex, u32 num_indices, VkBuffer buffer, u32 offset, [[maybe_unused]] u32 size) { diff --git a/src/video_core/renderer_vulkan/vk_buffer_cache.h b/src/video_core/renderer_vulkan/vk_buffer_cache.h index 2cbbcca140..828bc0c339 100644 --- a/src/video_core/renderer_vulkan/vk_buffer_cache.h +++ b/src/video_core/renderer_vulkan/vk_buffer_cache.h @@ -135,6 +135,9 @@ public: void CopyToUnifiedMemory(size_t window_index, VkBuffer src_buffer, std::span copies); + void CopyFromUnifiedMemory(size_t window_index, VkBuffer dst_buffer, + std::span copies); + void FlushUnifiedMemoryCopies(); void UnifiedMemoryHostBarrier(); @@ -229,6 +232,21 @@ public: bool BindMultiRangeStorageBuffer(u64 key, bool is_written); + bool StageUnifiedVertexBuffer(u32 index, u64 key, + std::span extents, u32 size, + u32 stride, bool force); + + bool StageMultiRangeVertexBuffer(u32 index, u64 key, u32 size, u32 stride, bool force); + + void BindStagedVertexBuffers(); + + bool BindUnifiedIndexBuffer(PrimitiveTopology topology, IndexFormat index_format, + u32 base_vertex, u32 num_indices, u64 key, + std::span extents, u32 size); + + bool BindMultiRangeIndexBuffer(PrimitiveTopology topology, IndexFormat index_format, + u32 base_vertex, u32 num_indices, u64 key, u32 size); + void InvalidateMultiRange(u64 key) { multi_range_buffers.Invalidate(key); } @@ -246,7 +264,7 @@ public: BindBuffer(buffer, offset, size); } - void BindStorageBuffer(VkBuffer buffer, VkDeviceAddress address, u32 offset, u32 size, + void BindStorageBuffer(VkBuffer buffer, VkDeviceAddress address, VkDeviceSize offset, u32 size, [[maybe_unused]] bool is_written) { guest_descriptor_queue.AddBuffer(buffer, address, offset, size); } @@ -256,17 +274,16 @@ public: unified_memory->IsBindable(); } - [[nodiscard]] VkBuffer UnifiedWindowBuffer(size_t index) const noexcept { - return unified_memory->GetWindowBuffer(index); - } - - [[nodiscard]] VkDeviceAddress UnifiedWindowAddress(size_t index) const noexcept { - return unified_memory->GetWindowAddress(index); - } - - [[nodiscard]] bool IsUnifiedStorageRange(u32 size, u64 offset) const { - return size <= device.GetMaxStorageBufferRange() && - (offset % device.GetStorageBufferAlignment()) == 0; + [[nodiscard]] std::optional ResolveUnifiedStorage(u64 relative, + u32 size) const { + if (size > device.GetMaxStorageBufferRange()) { + return std::nullopt; + } + const auto range = unified_memory->ResolveRange(relative, size); + if (!range || (range->offset % device.GetStorageBufferAlignment()) != 0) { + return std::nullopt; + } + return range; } void BindTextureBuffer(Buffer& buffer, u32 offset, u32 size, @@ -291,6 +308,29 @@ private: boost::container::small_vector copies; }; + struct StagedVertexBuffer { + u32 index; + VkBuffer buffer; + VkDeviceSize offset; + u32 size; + u32 stride; + + bool operator==(const StagedVertexBuffer&) const = default; + }; + + [[nodiscard]] MultiRangeRef AcquireMultiRange(u64 key, bool require_sparse); + + [[nodiscard]] std::optional ResolveUnifiedExtents( + u64 key, std::span extents, u32 size); + + [[nodiscard]] std::optional AcquireUnifiedView( + u64 key, std::span extents); + + void StageVertexBuffer(const StagedVertexBuffer& target, bool force); + + [[nodiscard]] bool IsIndexRangeUsable(PrimitiveTopology topology, IndexFormat index_format, + VkDeviceSize offset, u32 size) const; + void BindBuffer(const Buffer& buffer, u32 offset, u32 size) { const VkBuffer handle = buffer.Handle(); if (handle == VK_NULL_HANDLE) { @@ -324,6 +364,9 @@ private: MultiRangeBufferCache multi_range_buffers; boost::container::small_vector multi_range_sources; VkDeviceSize multi_range_total{}; + boost::container::static_vector + staged_vertex_buffers; + std::array bound_vertex_buffers{}; bool limit_dynamic_storage_buffers = false; u32 max_dynamic_storage_buffers = (std::numeric_limits::max)(); diff --git a/src/video_core/renderer_vulkan/vk_multi_range_buffer.cpp b/src/video_core/renderer_vulkan/vk_multi_range_buffer.cpp index 4d84390002..84f25a4655 100644 --- a/src/video_core/renderer_vulkan/vk_multi_range_buffer.cpp +++ b/src/video_core/renderer_vulkan/vk_multi_range_buffer.cpp @@ -13,7 +13,8 @@ namespace Vulkan { MultiRangeBufferCache::MultiRangeBufferCache(const Device& device) { sparse_usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT | - VK_BUFFER_USAGE_STORAGE_BUFFER_BIT; + VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_VERTEX_BUFFER_BIT | + VK_BUFFER_USAGE_INDEX_BUFFER_BIT; if (device.IsBufferDeviceAddressSupported()) { sparse_usage |= VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT; } @@ -27,9 +28,14 @@ MultiRangeBufferCache::MultiRangeBufferCache(const Device& device) { } block_size = queried; sparse_memory_type_bits = memory_type_bits; + sparse_budget = device.GetSparseAddressSpaceSize(); use_sparse = true; } +void MultiRangeBufferCache::ReserveSparseAddressSpace(VkDeviceSize size) noexcept { + sparse_budget -= (std::min)(sparse_budget, size); +} + VkDeviceSize MultiRangeBufferCache::QueryBlockSize(const Device& device, u32& memory_type_bits) const { const VkDevice logical = *device.GetLogical(); @@ -100,15 +106,26 @@ bool MultiRangeBufferCache::CanBindSparse(std::span sour SparseBuffer MultiRangeBufferCache::CreateSparse(const Device& device, Scheduler& scheduler, std::span sources, - VkDeviceSize total) { + VkDeviceSize total, VkBufferCreateFlags flags, + VkBufferUsageFlags usage, + VkExternalMemoryHandleTypeFlags handle_types) { const VkDevice logical = *device.GetLogical(); const auto& dld = device.GetDispatchLoader(); + const VkExternalMemoryBufferCreateInfo external_info{ + .sType = VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_BUFFER_CREATE_INFO, + .pNext = nullptr, + .handleTypes = handle_types, + }; + const void* next = nullptr; + if (handle_types != 0) { + next = &external_info; + } const VkBufferCreateInfo buffer_ci{ .sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO, - .pNext = nullptr, - .flags = VK_BUFFER_CREATE_SPARSE_BINDING_BIT | VK_BUFFER_CREATE_SPARSE_ALIASED_BIT, + .pNext = next, + .flags = flags, .size = total, - .usage = sparse_usage, + .usage = usage, .sharingMode = VK_SHARING_MODE_EXCLUSIVE, .queueFamilyIndexCount = 0, .pQueueFamilyIndices = nullptr, @@ -118,6 +135,27 @@ SparseBuffer MultiRangeBufferCache::CreateSparse(const Device& device, Scheduler return SparseBuffer{}; } SparseBuffer handle{raw, logical, dld}; + const VkBufferMemoryRequirementsInfo2 reqs_info{ + .sType = VK_STRUCTURE_TYPE_BUFFER_MEMORY_REQUIREMENTS_INFO_2, + .pNext = nullptr, + .buffer = raw, + }; + VkMemoryRequirements2 reqs2{ + .sType = VK_STRUCTURE_TYPE_MEMORY_REQUIREMENTS_2, + .pNext = nullptr, + .memoryRequirements = {}, + }; + dld.vkGetBufferMemoryRequirements2(logical, &reqs_info, &reqs2); + const VkMemoryRequirements& requirements = reqs2.memoryRequirements; + if (requirements.alignment == 0 || (block_size % requirements.alignment) != 0) { + return SparseBuffer{}; + } + for (const MultiRangeSource& source : sources) { + if (source.memory_type >= 32 || + ((requirements.memoryTypeBits >> source.memory_type) & 1) == 0) { + return SparseBuffer{}; + } + } std::vector binds; binds.reserve(sources.size()); VkDeviceSize resource_offset = 0; @@ -185,10 +223,16 @@ void MultiRangeBufferCache::RetireEntry(Scheduler& scheduler, Entry& entry) { scheduler.Wait(oldest); DrainRetired(scheduler); } + VkDeviceSize sparse_size = 0; + if (entry.sparse_handle) { + sparse_size = entry.size; + } + sparse_retiring += sparse_size; retired.push_back(Retired{ .handle = std::move(entry.sparse_handle), .gathered = std::move(entry.gathered), .tick = scheduler.CurrentTick(), + .sparse_size = sparse_size, }); } @@ -196,6 +240,8 @@ void MultiRangeBufferCache::DrainRetired(Scheduler& scheduler) { size_t index = 0; while (index < retired.size()) { if (scheduler.IsFree(retired[index].tick)) { + sparse_in_use -= (std::min)(sparse_in_use, retired[index].sparse_size); + sparse_retiring -= (std::min)(sparse_retiring, retired[index].sparse_size); if (index + 1 != retired.size()) { retired[index] = std::move(retired.back()); } @@ -221,6 +267,7 @@ MultiRangeRef MultiRangeBufferCache::Get(const Device& device, Scheduler& schedu const auto it = entries.find(key); if (it != entries.end() && it->second.geometry == geometry && it->second.size == total) { Entry& entry = it->second; + entry.last_use = scheduler.CurrentTick(); if (entry.content != content) { entry.content = content; entry.dirty = true; @@ -248,9 +295,14 @@ MultiRangeRef MultiRangeBufferCache::Get(const Device& device, Scheduler& schedu entry.geometry = geometry; entry.content = content; entry.size = total; - if (CanBindSparse(sources)) { - entry.sparse_handle = CreateSparse(device, scheduler, sources, total); + entry.last_use = scheduler.CurrentTick(); + if (CanBindSparse(sources) && FitsSparse(scheduler, total)) { + entry.sparse_handle = CreateSparse( + device, scheduler, sources, total, + VK_BUFFER_CREATE_SPARSE_BINDING_BIT | VK_BUFFER_CREATE_SPARSE_ALIASED_BIT, + sparse_usage, 0); if (entry.sparse_handle) { + sparse_in_use += total; entry.owners.reserve(sources.size()); for (const MultiRangeSource& source : sources) { entry.owners.push_back(source.handle); @@ -260,7 +312,9 @@ MultiRangeRef MultiRangeBufferCache::Get(const Device& device, Scheduler& schedu if (!entry.sparse_handle) { VkBufferUsageFlags flags = VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT | - VK_BUFFER_USAGE_STORAGE_BUFFER_BIT; + VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | + VK_BUFFER_USAGE_VERTEX_BUFFER_BIT | + VK_BUFFER_USAGE_INDEX_BUFFER_BIT; if (device.IsBufferDeviceAddressSupported()) { flags |= VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT; } @@ -301,6 +355,86 @@ MultiRangeRef MultiRangeBufferCache::Get(const Device& device, Scheduler& schedu return ref; } +MultiRangeRef MultiRangeBufferCache::GetView(const Device& device, Scheduler& scheduler, u64 key, + std::span sources, + VkDeviceSize total, VkBufferUsageFlags usage, + VkExternalMemoryHandleTypeFlags handle_types) { + if (!use_sparse || !views_supported || sources.empty() || total == 0) { + return MultiRangeRef{}; + } + if (!retired.empty()) { + DrainRetired(scheduler); + } + const u64 geometry = HashSources(sources); + const auto it = entries.find(key); + if (it != entries.end() && it->second.sparse_handle && it->second.geometry == geometry && + it->second.size == total) { + it->second.last_use = scheduler.CurrentTick(); + return MultiRangeRef{ + .handle = *it->second.sparse_handle, + .address = it->second.address, + .size = total, + .sparse = true, + .needs_gather = false, + }; + } + if (it != entries.end()) { + RetireEntry(scheduler, it->second); + entries.erase(it); + } + if (!FitsSparse(scheduler, total)) { + return MultiRangeRef{}; + } + Entry entry{}; + entry.sparse_handle = CreateSparse(device, scheduler, sources, total, + VK_BUFFER_CREATE_SPARSE_BINDING_BIT, usage, handle_types); + if (!entry.sparse_handle) { + views_supported = false; + return MultiRangeRef{}; + } + sparse_in_use += total; + entry.geometry = geometry; + entry.size = total; + entry.last_use = scheduler.CurrentTick(); + entry.dirty = false; + if ((usage & VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT) != 0) { + entry.address = device.GetLogical().GetBufferDeviceAddress(*entry.sparse_handle); + } + const MultiRangeRef ref{ + .handle = *entry.sparse_handle, + .address = entry.address, + .size = total, + .sparse = true, + .needs_gather = false, + }; + entries.emplace(key, std::move(entry)); + return ref; +} + +bool MultiRangeBufferCache::FitsSparse(Scheduler& scheduler, VkDeviceSize total) { + if (total > sparse_budget) { + return false; + } + const u64 current_tick = scheduler.CurrentTick(); + while (sparse_in_use - sparse_retiring > sparse_budget - total) { + auto victim = entries.end(); + for (auto it = entries.begin(); it != entries.end(); ++it) { + if (!it->second.sparse_handle || it->second.last_use >= current_tick) { + continue; + } + if (victim == entries.end() || it->second.last_use < victim->second.last_use) { + victim = it; + } + } + if (victim == entries.end()) { + break; + } + RetireEntry(scheduler, victim->second); + entries.erase(victim); + } + return sparse_in_use <= sparse_budget - total; +} + void MultiRangeBufferCache::MarkGathered(u64 key) { if (auto const it = entries.find(key); it != entries.end()) { it->second.dirty = false; diff --git a/src/video_core/renderer_vulkan/vk_multi_range_buffer.h b/src/video_core/renderer_vulkan/vk_multi_range_buffer.h index f40d3aa1f8..a6734878cb 100644 --- a/src/video_core/renderer_vulkan/vk_multi_range_buffer.h +++ b/src/video_core/renderer_vulkan/vk_multi_range_buffer.h @@ -53,12 +53,19 @@ public: std::span sources, VkDeviceSize total); + [[nodiscard]] MultiRangeRef GetView(const Device& device, Scheduler& scheduler, u64 key, + std::span sources, + VkDeviceSize total, VkBufferUsageFlags usage, + VkExternalMemoryHandleTypeFlags handle_types); + void MarkGathered(u64 key); void Invalidate(u64 key); void DropOwner(Scheduler& scheduler, VkBuffer owner); + void ReserveSparseAddressSpace(VkDeviceSize size) noexcept; + VkDeviceSize block_size{DEFAULT_BLOCK_SIZE}; bool use_sparse{}; @@ -67,6 +74,7 @@ private: SparseBuffer handle; vk::Buffer gathered; u64 tick{}; + VkDeviceSize sparse_size{}; }; struct Entry { @@ -77,6 +85,7 @@ private: VkDeviceSize size{}; u64 geometry{}; u64 content{}; + u64 last_use{}; bool dirty{true}; }; @@ -88,7 +97,11 @@ private: [[nodiscard]] SparseBuffer CreateSparse(const Device& device, Scheduler& scheduler, std::span sources, - VkDeviceSize total); + VkDeviceSize total, VkBufferCreateFlags flags, + VkBufferUsageFlags usage, + VkExternalMemoryHandleTypeFlags handle_types); + + [[nodiscard]] bool FitsSparse(Scheduler& scheduler, VkDeviceSize total); [[nodiscard]] VkDeviceSize QueryBlockSize(const Device& device, u32& memory_type_bits) const; @@ -100,6 +113,10 @@ private: boost::container::static_vector retired; u32 sparse_memory_type_bits{}; VkBufferUsageFlags sparse_usage{}; + VkDeviceSize sparse_budget{}; + VkDeviceSize sparse_in_use{}; + VkDeviceSize sparse_retiring{}; + bool views_supported{true}; }; } // namespace Vulkan diff --git a/src/video_core/renderer_vulkan/vk_texture_cache.cpp b/src/video_core/renderer_vulkan/vk_texture_cache.cpp index dd1bfeefcc..82f34157d5 100644 --- a/src/video_core/renderer_vulkan/vk_texture_cache.cpp +++ b/src/video_core/renderer_vulkan/vk_texture_cache.cpp @@ -3198,44 +3198,35 @@ u64 TextureCacheRuntime::UnifiedMemorySize() const noexcept { return import->GetSize(); } -u64 TextureCacheRuntime::UnifiedMemoryWindowSize() const noexcept { - const HostMemoryImport* const import = memory_allocator.GetHostMemoryImport(); - if (import == nullptr) { - return 0; - } - return import->GetWindowSize(); -} - bool TextureCacheRuntime::CanUploadImageDirectly(const VideoCommon::ImageInfo& info) const { return bl2d_unswizzle_pass.has_value() && BlockLinearUnswizzle2DPass::IsSupported(device, info); } -VkBuffer TextureCacheRuntime::ResolveDirectWindow(size_t window_index, u64 window_offset, - u64 size) const { - if ((window_offset % device.GetStorageBufferAlignment()) != 0) { - return VK_NULL_HANDLE; - } +std::optional TextureCacheRuntime::ResolveDirectRange(u64 relative, + u64 size) const { if (size > device.GetMaxStorageBufferRange()) { - return VK_NULL_HANDLE; + return std::nullopt; } const HostMemoryImport* const import = memory_allocator.GetHostMemoryImport(); - if (import == nullptr || window_index >= import->GetWindowCount()) { - return VK_NULL_HANDLE; + if (import == nullptr) { + return std::nullopt; } - return import->GetWindowBuffer(window_index); + const auto range = import->ResolveRange(relative, size); + if (!range || range->buffer == VK_NULL_HANDLE || + (range->offset % device.GetStorageBufferAlignment()) != 0) { + return std::nullopt; + } + return range; } bool TextureCacheRuntime::UploadImageDirectly( - Image& image, size_t window_index, u64 window_offset, - std::span swizzles) { - const VkBuffer window_buffer = - ResolveDirectWindow(window_index, window_offset, image.guest_size_bytes); - if (window_buffer == VK_NULL_HANDLE) { + Image& image, u64 relative, std::span swizzles) { + const auto range = ResolveDirectRange(relative, image.guest_size_bytes); + if (!range) { return false; } - bl2d_unswizzle_pass->UnswizzleFrom(image, window_buffer, - static_cast(window_offset), swizzles); + bl2d_unswizzle_pass->UnswizzleFrom(image, range->buffer, range->offset, swizzles); return true; } @@ -3243,15 +3234,16 @@ bool TextureCacheRuntime::CanDownloadImageDirectly(const VideoCommon::ImageInfo& return bl2d_swizzle_pass.has_value() && BlockLinearUnswizzle2DPass::IsSupported(device, info); } -bool TextureCacheRuntime::DownloadImageDirectly(Image& image, size_t window_index, - u64 window_offset) { - const u64 size = (std::max)(image.guest_size_bytes, image.unswizzled_size_bytes); - const VkBuffer window_buffer = ResolveDirectWindow(window_index, window_offset, size); - if (window_buffer == VK_NULL_HANDLE) { +bool TextureCacheRuntime::DownloadImageDirectly(Image& image, u64 relative) { + if (image.unswizzled_size_bytes > device.GetMaxStorageBufferRange()) { + return false; + } + const auto range = ResolveDirectRange(relative, image.guest_size_bytes); + if (!range) { return false; } const HostMemoryImport* const import = memory_allocator.GetHostMemoryImport(); - bl2d_swizzle_pass->SwizzleInto(image, window_buffer, static_cast(window_offset), + bl2d_swizzle_pass->SwizzleInto(image, range->buffer, range->offset, import->NeedsForeignOwnershipTransfer()); return true; } @@ -3260,7 +3252,7 @@ u64 TextureCacheRuntime::CurrentTick() const noexcept { return scheduler.CurrentTick(); } -bool TextureCacheRuntime::IsDirectUploadRetired(u64 tick) { +bool TextureCacheRuntime::IsTickRetired(u64 tick) { if (scheduler.IsFree(tick)) { return true; } diff --git a/src/video_core/renderer_vulkan/vk_texture_cache.h b/src/video_core/renderer_vulkan/vk_texture_cache.h index 65b88f6b20..946cf25cd4 100644 --- a/src/video_core/renderer_vulkan/vk_texture_cache.h +++ b/src/video_core/renderer_vulkan/vk_texture_cache.h @@ -107,23 +107,21 @@ public: [[nodiscard]] u64 UnifiedMemorySize() const noexcept; - [[nodiscard]] u64 UnifiedMemoryWindowSize() const noexcept; - [[nodiscard]] bool CanUploadImageDirectly(const VideoCommon::ImageInfo& info) const; - bool UploadImageDirectly(Image& image, size_t window_index, u64 window_offset, + bool UploadImageDirectly(Image& image, u64 relative, std::span swizzles); [[nodiscard]] bool CanDownloadImageDirectly(const VideoCommon::ImageInfo& info) const; - bool DownloadImageDirectly(Image& image, size_t window_index, u64 window_offset); + bool DownloadImageDirectly(Image& image, u64 relative); - [[nodiscard]] VkBuffer ResolveDirectWindow(size_t window_index, u64 window_offset, - u64 size) const; + [[nodiscard]] std::optional ResolveDirectRange(u64 relative, + u64 size) const; [[nodiscard]] u64 CurrentTick() const noexcept; - [[nodiscard]] bool IsDirectUploadRetired(u64 tick); + [[nodiscard]] bool IsTickRetired(u64 tick); void InsertUploadMemoryBarrier() {} diff --git a/src/video_core/texture_cache/image_base.h b/src/video_core/texture_cache/image_base.h index 6915a4d9af..f1eb6aa5b7 100644 --- a/src/video_core/texture_cache/image_base.h +++ b/src/video_core/texture_cache/image_base.h @@ -97,6 +97,9 @@ struct ImageBase { bool has_scaled = false; u64 direct_upload_tick = 0; bool direct_upload_blocked = false; + bool eviction_pending = false; + u64 eviction_tick = 0; + u64 eviction_modification_tick = 0; size_t channel = 0; diff --git a/src/video_core/texture_cache/texture_cache.h b/src/video_core/texture_cache/texture_cache.h index e74a8baae0..a18314ae0a 100644 --- a/src/video_core/texture_cache/texture_cache.h +++ b/src/video_core/texture_cache/texture_cache.h @@ -137,6 +137,9 @@ void TextureCache

::RunGarbageCollector() { if (True(image.flags & ImageFlagBits::IsDecoding)) { return false; } + if (image.eviction_pending) { + return false; + } const bool must_download = IsDownloadable(image) && False(image.flags & ImageFlagBits::BadOverlap); if ((!aggressive_mode && True(image.flags & ImageFlagBits::CostlyLoad)) || (!high_priority_mode && must_download)) { return false; @@ -146,15 +149,14 @@ void TextureCache

::RunGarbageCollector() { return false; } --num_downloads; - if (TryDownloadToUnifiedMemory(image)) { - runtime.Finish(); - } else { - auto map = runtime.DownloadStagingBuffer(image.unswizzled_size_bytes); - const auto copies = FixSmallVectorADL(FullDownloadCopies(image.info)); - image.DownloadMemory(map, copies); - runtime.Finish(); - SwizzleImage(*gpu_memory, image.gpu_addr, image.info, copies, map.mapped_span, swizzle_data_buffer); + if (StartEviction(image_id, image)) { + return false; } + auto map = runtime.DownloadStagingBuffer(image.unswizzled_size_bytes); + const auto copies = FixSmallVectorADL(FullDownloadCopies(image.info)); + image.DownloadMemory(map, copies); + runtime.Finish(); + SwizzleImage(*gpu_memory, image.gpu_addr, image.info, copies, map.mapped_span, swizzle_data_buffer); } if (True(image.flags & ImageFlagBits::Tracked)) { UntrackImage(image, image_id); @@ -180,6 +182,7 @@ void TextureCache

::RunGarbageCollector() { template void TextureCache

::TickFrame() { + FinishEvictions(); // If we can obtain the memory info, use it instead of the estimate. if (runtime.CanReportMemoryUsage()) { total_used_memory = runtime.GetDeviceMemoryUsage(); @@ -600,7 +603,7 @@ void TextureCache

::WriteMemory(DAddr cpu_addr, size_t size) { if (image.direct_upload_tick != 0) { const u64 upload_tick = image.direct_upload_tick; image.direct_upload_tick = 0; - if (!runtime.IsDirectUploadRetired(upload_tick)) { + if (!runtime.IsTickRetired(upload_tick)) { image.direct_upload_blocked = true; } } @@ -910,10 +913,6 @@ void TextureCache

::CommitAsyncFlushes() { bool any_none_dma = false; for (PendingDownload& download_info : download_ids) { if (download_info.is_swizzle) { - if (TryDownloadToUnifiedMemory(slot_images[download_info.object_id])) { - download_info.is_unified = true; - continue; - } total_size_bytes += Common::AlignUp(slot_images[download_info.object_id].unswizzled_size_bytes, 64); any_none_dma = true; @@ -924,7 +923,7 @@ void TextureCache

::CommitAsyncFlushes() { if (any_none_dma) { auto download_map = runtime.DownloadStagingBuffer(total_size_bytes, true); for (const PendingDownload& download_info : download_ids) { - if (download_info.is_swizzle && !download_info.is_unified) { + if (download_info.is_swizzle) { Image& image = slot_images[download_info.object_id]; const auto copies = FixSmallVectorADL(FullDownloadCopies(image.info)); image.DownloadMemory(download_map, copies); @@ -956,9 +955,6 @@ void TextureCache

::PopAsyncFlushes() { auto download_map = std::move(async_buffers.front()); for (size_t i = download_ids.size(); i > 0; i--) { auto& download_info = download_ids[i - 1]; - if (download_info.is_unified) { - continue; - } auto& download_buffer = download_map[download_info.async_buffer_id]; if (download_info.is_swizzle) { const ImageBase& image = slot_images[download_info.object_id]; @@ -1192,16 +1188,12 @@ void TextureCache

::RefreshContents(Image& image, ImageId image_id) { } template -std::optional> TextureCache

::ResolveUnifiedImageWindow( +std::optional TextureCache

::ResolveUnifiedImageOffset( [[maybe_unused]] const ImageBase& image) { if constexpr (USE_UNIFIED_MEMORY) { if (image.guest_size_bytes == 0 || !runtime.IsUnifiedMemoryBindable()) { return std::nullopt; } - const u64 window_size = runtime.UnifiedMemoryWindowSize(); - if (window_size == 0) { - return std::nullopt; - } const u8* const first = gpu_memory->GetSpan(image.gpu_addr, image.guest_size_bytes); if (first == nullptr) { return std::nullopt; @@ -1216,11 +1208,7 @@ std::optional> TextureCache

::ResolveUnifiedImageWindow if (relative >= unified_size || unified_size - relative < image.guest_size_bytes) { return std::nullopt; } - const u64 local_offset = relative % window_size; - if (window_size - local_offset < image.guest_size_bytes) { - return std::nullopt; - } - return std::pair{static_cast(relative / window_size), local_offset}; + return relative; } else { return std::nullopt; } @@ -1232,13 +1220,12 @@ bool TextureCache

::TryUploadFromUnifiedMemory([[maybe_unused]] Image& image) if (image.direct_upload_blocked || !runtime.CanUploadImageDirectly(image.info)) { return false; } - const auto window = ResolveUnifiedImageWindow(image); - if (!window) { + const auto relative = ResolveUnifiedImageOffset(image); + if (!relative) { return false; } const auto swizzles = FullUploadSwizzles(image.info); - if (!runtime.UploadImageDirectly(image, window->first, window->second, - FixSmallVectorADL(swizzles))) { + if (!runtime.UploadImageDirectly(image, *relative, FixSmallVectorADL(swizzles))) { return false; } image.direct_upload_tick = runtime.CurrentTick(); @@ -1258,16 +1245,75 @@ bool TextureCache

::TryDownloadToUnifiedMemory([[maybe_unused]] Image& image) image.info.layer_stride != CalculateLayerStride(image.info)) { return false; } - const auto window = ResolveUnifiedImageWindow(image); - if (!window) { + const auto relative = ResolveUnifiedImageOffset(image); + if (!relative) { return false; } - return runtime.DownloadImageDirectly(image, window->first, window->second); + return runtime.DownloadImageDirectly(image, *relative); } else { return false; } } +template +bool TextureCache

::StartEviction([[maybe_unused]] ImageId image_id, + [[maybe_unused]] Image& image) { + if constexpr (requires { runtime.IsTickRetired(u64{}); }) { + auto staging = runtime.DownloadStagingBuffer(image.unswizzled_size_bytes, true); + const auto copies = FixSmallVectorADL(FullDownloadCopies(image.info)); + image.DownloadMemory(staging, copies); + eviction_staging.emplace_back(image_id, staging); + image.eviction_pending = true; + image.eviction_tick = runtime.CurrentTick(); + image.eviction_modification_tick = image.modification_tick; + return true; + } else { + return false; + } +} + +template +void TextureCache

::FinishEvictions() { + if constexpr (requires { runtime.IsTickRetired(u64{}); }) { + size_t index = 0; + while (index < eviction_staging.size()) { + const ImageId image_id = eviction_staging[index].first; + Image& image = slot_images[image_id]; + if (!runtime.IsTickRetired(image.eviction_tick)) { + ++index; + continue; + } + const bool unchanged = image.modification_tick == image.eviction_modification_tick; + if (unchanged && False(image.flags & ImageFlagBits::CpuModified)) { + const auto copies = FixSmallVectorADL(FullDownloadCopies(image.info)); + SwizzleImage(*gpu_memory, image.gpu_addr, image.info, copies, + eviction_staging[index].second.mapped_span, swizzle_data_buffer); + } + CancelEviction(image_id); + if (!unchanged) { + continue; + } + if (True(image.flags & ImageFlagBits::Tracked)) { + UntrackImage(image, image_id); + } + UnregisterImage(image_id); + DeleteImage(image_id, image.scale_tick > frame_tick + 5); + } + } +} + +template +void TextureCache

::CancelEviction(ImageId image_id) { + slot_images[image_id].eviction_pending = false; + const auto it = std::ranges::find_if( + eviction_staging, [image_id](const auto& entry) { return entry.first == image_id; }); + if (it == eviction_staging.end()) { + return; + } + async_buffers_death_ring.emplace_back(std::move(it->second)); + eviction_staging.erase(it); +} + template template void TextureCache

::UploadImageContents(Image& image, StagingBuffer& staging) { @@ -2434,6 +2480,9 @@ void TextureCache

::UntrackImage(ImageBase& image, ImageId image_id) { template void TextureCache

::DeleteImage(ImageId image_id, bool immediate_delete) { ImageBase& image = slot_images[image_id]; + if (image.eviction_pending) { + CancelEviction(image_id); + } if (image.HasScaled()) { total_used_memory -= GetScaledImageSizeBytes(image); } @@ -2621,6 +2670,9 @@ void TextureCache

::SynchronizeAliases(ImageId image_id) { template void TextureCache

::PrepareImage(ImageId image_id, bool is_modification, bool invalidate) { Image& image = slot_images[image_id]; + if (image.eviction_pending) { + CancelEviction(image_id); + } if (invalidate) { image.flags &= ~(ImageFlagBits::CpuModified | ImageFlagBits::GpuModified); if (False(image.flags & ImageFlagBits::Tracked)) { diff --git a/src/video_core/texture_cache/texture_cache_base.h b/src/video_core/texture_cache/texture_cache_base.h index 28205cdbe6..9e80204377 100644 --- a/src/video_core/texture_cache/texture_cache_base.h +++ b/src/video_core/texture_cache/texture_cache_base.h @@ -310,13 +310,18 @@ private: void RefreshContents(Image& image, ImageId image_id); - [[nodiscard]] std::optional> ResolveUnifiedImageWindow( - const ImageBase& image); + [[nodiscard]] std::optional ResolveUnifiedImageOffset(const ImageBase& image); bool TryUploadFromUnifiedMemory(Image& image); bool TryDownloadToUnifiedMemory(Image& image); + bool StartEviction(ImageId image_id, Image& image); + + void FinishEvictions(); + + void CancelEviction(ImageId image_id); + /// Upload data from guest to an image template void UploadImageContents(Image& image, StagingBuffer& staging_buffer); @@ -476,7 +481,6 @@ private: bool is_swizzle; size_t async_buffer_id; Common::SlotId object_id; - bool is_unified = false; }; Common::SlotVector slot_images; @@ -494,6 +498,7 @@ private: std::vector uncommitted_async_buffers; std::deque> async_buffers; std::deque async_buffers_death_ring; + std::vector> eviction_staging; struct LRUItemParams { using ObjectType = ImageId; diff --git a/src/video_core/vulkan_common/vulkan_device.h b/src/video_core/vulkan_common/vulkan_device.h index cdd683f016..236f93aa27 100644 --- a/src/video_core/vulkan_common/vulkan_device.h +++ b/src/video_core/vulkan_common/vulkan_device.h @@ -920,6 +920,10 @@ FN_MAX_LIMIT_LIST return properties.maintenance4.maxBufferSize; } + u64 GetSparseAddressSpaceSize() const { + return properties.properties.limits.sparseAddressSpaceSize; + } + u64 GetMaxMemoryAllocationSize() const { return properties.maintenance3.maxMemoryAllocationSize; } diff --git a/src/video_core/vulkan_common/vulkan_memory_allocator.cpp b/src/video_core/vulkan_common/vulkan_memory_allocator.cpp index 96690a19c6..38c679fb5a 100644 --- a/src/video_core/vulkan_common/vulkan_memory_allocator.cpp +++ b/src/video_core/vulkan_common/vulkan_memory_allocator.cpp @@ -251,6 +251,7 @@ bool HostMemoryImport::ImportHostPointer(void *base, size_t size) { return false; } window_size = candidate_window; + buffer_usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT; const auto &logical = device.GetLogical(); const auto memory_props = device.GetPhysical().GetMemoryProperties().memoryProperties; @@ -331,6 +332,9 @@ bool HostMemoryImport::ImportHostPointer(void *base, size_t size) { windows.push_back(Window{ .memory = std::move(memory), .buffer = new_buffer, + .address = 0, + .size = window_len, + .memory_type = *type_index, }); imported_size += static_cast(window_len); } @@ -361,7 +365,7 @@ bool HostMemoryImport::ImportHardwareBuffers( window_size = hardware_buffer_window; base_offset = hardware_buffer_base; - const auto import_all = [&](VkBufferUsageFlags usage, bool want_address) { + const auto import_all = [&](VkBufferUsageFlags usage, bool want_address, bool dedicated) { for (size_t i = 0; i < hardware_buffers.size(); ++i) { const size_t offset = hardware_buffer_base + i * hardware_buffer_window; if (offset >= size) { @@ -424,13 +428,17 @@ bool HostMemoryImport::ImportHardwareBuffers( .image = VK_NULL_HANDLE, .buffer = new_buffer, }; + const void *memory_next = &import_info; + if (dedicated) { + memory_next = &dedicated_info; + } const VkMemoryAllocateFlagsInfo flags_info{ .sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_FLAGS_INFO, - .pNext = &dedicated_info, + .pNext = memory_next, .flags = VK_MEMORY_ALLOCATE_DEVICE_ADDRESS_BIT, .deviceMask = 0, }; - const void *alloc_next = &dedicated_info; + const void *alloc_next = memory_next; if (want_address) { alloc_next = &flags_info; } @@ -457,6 +465,8 @@ bool HostMemoryImport::ImportHardwareBuffers( .memory = std::move(memory), .buffer = new_buffer, .address = address, + .size = window_len, + .memory_type = *type_index, }); imported_size += static_cast(window_len); } @@ -487,14 +497,26 @@ bool HostMemoryImport::ImportHardwareBuffers( imported_size = 0; }; - bindable = import_all(shader_usage, want_address); - if (!bindable) { + mirror_capable = SupportsMirror(shader_usage); + buffer_usage = shader_usage; + bindable = import_all(shader_usage, want_address, !mirror_capable); + if (!bindable && mirror_capable) { + mirror_capable = false; reset_windows(); - bindable = import_all(minimal_usage, want_address); + bindable = import_all(shader_usage, want_address, true); + } + if (bindable) { + mirror_usage = shader_usage; } if (!bindable) { reset_windows(); - import_all(TransferUsage, false); + buffer_usage = minimal_usage; + bindable = import_all(minimal_usage, want_address, true); + } + if (!bindable) { + reset_windows(); + buffer_usage = TransferUsage; + import_all(TransferUsage, false, true); } if (windows.empty()) { window_size = 0; @@ -508,7 +530,181 @@ bool HostMemoryImport::ImportHardwareBuffers( #endif } +bool HostMemoryImport::SupportsMirror([[maybe_unused]] VkBufferUsageFlags usage) const { +#ifdef __ANDROID__ + if (!device.IsSparseBindingSupported()) { + return false; + } + const auto supports = [&](VkBufferCreateFlags flags) { + const VkExternalMemoryProperties properties = + device.GetPhysical().GetExternalBufferProperties( + flags, usage, + VK_EXTERNAL_MEMORY_HANDLE_TYPE_ANDROID_HARDWARE_BUFFER_BIT_ANDROID); + const VkExternalMemoryFeatureFlags features = properties.externalMemoryFeatures; + return (features & VK_EXTERNAL_MEMORY_FEATURE_IMPORTABLE_BIT) != 0 && + (features & VK_EXTERNAL_MEMORY_FEATURE_DEDICATED_ONLY_BIT) == 0; + }; + return supports(0) && supports(VK_BUFFER_CREATE_SPARSE_BINDING_BIT); +#else + return false; +#endif +} + +std::optional HostMemoryImport::ResolveRange( + VkDeviceSize relative, VkDeviceSize size) const noexcept { + if (window_size == 0 || size == 0 || relative >= imported_size || + imported_size - relative < size) { + return std::nullopt; + } + const size_t index = static_cast(relative / window_size); + const VkDeviceSize local_offset = relative % window_size; + if (index < windows.size() && windows[index].buffer != VK_NULL_HANDLE && + local_offset < windows[index].size && windows[index].size - local_offset >= size) { + return Range{ + .buffer = windows[index].buffer, + .address = windows[index].address, + .offset = local_offset, + }; + } + if (mirror_buffer != VK_NULL_HANDLE && relative < mirror_size && + mirror_size - relative >= size) { + return Range{ + .buffer = mirror_buffer, + .address = mirror_address, + .offset = relative, + }; + } + return std::nullopt; +} + +std::optional HostMemoryImport::ResolveViewMemory( + VkDeviceSize relative) const noexcept { + if (!mirror_capable || !bindable || window_size == 0) { + return std::nullopt; + } + const size_t index = static_cast(relative / window_size); + if (index >= windows.size()) { + return std::nullopt; + } + const Window &window = windows[index]; + const VkDeviceSize local_offset = relative % window_size; + if (window.buffer == VK_NULL_HANDLE || local_offset >= window.size) { + return std::nullopt; + } + return ViewMemory{ + .buffer = window.buffer, + .memory = *window.memory, + .offset = local_offset, + .available = window.size - local_offset, + .memory_type = window.memory_type, + }; +} + +void HostMemoryImport::CreateMirror(std::mutex &submit_mutex, VkDeviceSize max_size) { + if (!mirror_capable || mirror_usage == 0 || !bindable || window_size == 0) { + return; + } + size_t mirror_windows = 0; + while (mirror_windows < windows.size() && windows[mirror_windows].size == window_size) { + ++mirror_windows; + } + mirror_windows = (std::min)(mirror_windows, static_cast(max_size / window_size)); + const u64 max_buffer_size = device.GetMaxBufferSize(); + if (max_buffer_size != 0) { + const size_t max_windows = static_cast(max_buffer_size / window_size); + mirror_windows = (std::min)(mirror_windows, max_windows); + } + if (mirror_windows < 2) { + return; + } + const auto &logical = device.GetLogical(); + const VkDeviceSize total_size = static_cast(mirror_windows) * window_size; + const VkExternalMemoryBufferCreateInfo external_info{ + .sType = VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_BUFFER_CREATE_INFO, + .pNext = nullptr, + .handleTypes = VK_EXTERNAL_MEMORY_HANDLE_TYPE_ANDROID_HARDWARE_BUFFER_BIT_ANDROID, + }; + const VkBufferCreateInfo buffer_ci{ + .sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO, + .pNext = &external_info, + .flags = VK_BUFFER_CREATE_SPARSE_BINDING_BIT, + .size = total_size, + .usage = mirror_usage, + .sharingMode = VK_SHARING_MODE_EXCLUSIVE, + .queueFamilyIndexCount = 0, + .pQueueFamilyIndices = nullptr, + }; + VkBuffer buffer{}; + if (logical.CreateBufferRaw(buffer_ci, &buffer) != VK_SUCCESS) { + return; + } + const VkMemoryRequirements requirements = logical.GetBufferMemoryRequirements(buffer); + bool compatible = requirements.alignment != 0 && + (window_size % requirements.alignment) == 0 && + requirements.size <= total_size; + for (size_t index = 0; index < mirror_windows && compatible; ++index) { + compatible = ((requirements.memoryTypeBits >> windows[index].memory_type) & 1u) != 0; + } + if (!compatible) { + logical.DestroyBufferRaw(buffer); + return; + } + std::vector binds; + binds.reserve(mirror_windows); + for (size_t index = 0; index < mirror_windows; ++index) { + binds.push_back(VkSparseMemoryBind{ + .resourceOffset = static_cast(index) * window_size, + .size = window_size, + .memory = *windows[index].memory, + .memoryOffset = 0, + .flags = 0, + }); + } + const VkSparseBufferMemoryBindInfo buffer_bind{ + .buffer = buffer, + .bindCount = static_cast(binds.size()), + .pBinds = binds.data(), + }; + const VkBindSparseInfo bind_info{ + .sType = VK_STRUCTURE_TYPE_BIND_SPARSE_INFO, + .pNext = nullptr, + .waitSemaphoreCount = 0, + .pWaitSemaphores = nullptr, + .bufferBindCount = 1, + .pBufferBinds = &buffer_bind, + .imageOpaqueBindCount = 0, + .pImageOpaqueBinds = nullptr, + .imageBindCount = 0, + .pImageBinds = nullptr, + .signalSemaphoreCount = 0, + .pSignalSemaphores = nullptr, + }; + vk::Fence fence = logical.CreateFence(VkFenceCreateInfo{ + .sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO, + .pNext = nullptr, + .flags = 0, + }); + VkResult result = VK_ERROR_UNKNOWN; + { + std::scoped_lock lock{submit_mutex}; + result = device.GetGraphicsQueue().BindSparse(bind_info, *fence); + } + if (result != VK_SUCCESS) { + logical.DestroyBufferRaw(buffer); + return; + } + fence.Wait(); + mirror_buffer = buffer; + mirror_size = total_size; + if ((mirror_usage & VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT) != 0) { + mirror_address = logical.GetBufferDeviceAddress(buffer); + } +} + HostMemoryImport::~HostMemoryImport() { + if (mirror_buffer != VK_NULL_HANDLE) { + device.GetLogical().DestroyBufferRaw(mirror_buffer); + } for (Window &window : windows) { if (window.buffer != VK_NULL_HANDLE) { device.GetLogical().DestroyBufferRaw(window.buffer); diff --git a/src/video_core/vulkan_common/vulkan_memory_allocator.h b/src/video_core/vulkan_common/vulkan_memory_allocator.h index 39bf26d40e..402b6ef35c 100644 --- a/src/video_core/vulkan_common/vulkan_memory_allocator.h +++ b/src/video_core/vulkan_common/vulkan_memory_allocator.h @@ -7,6 +7,8 @@ #pragma once #include +#include +#include #include #include @@ -134,13 +136,54 @@ namespace Vulkan { return bindable; } + [[nodiscard]] VkBufferUsageFlags GetUsage() const noexcept { + return buffer_usage; + } + + struct Range { + VkBuffer buffer{}; + VkDeviceAddress address{}; + VkDeviceSize offset{}; + }; + + [[nodiscard]] std::optional ResolveRange(VkDeviceSize relative, + VkDeviceSize size) const noexcept; + + struct ViewMemory { + VkBuffer buffer{}; + VkDeviceMemory memory{}; + VkDeviceSize offset{}; + VkDeviceSize available{}; + u32 memory_type{}; + }; + + [[nodiscard]] std::optional ResolveViewMemory( + VkDeviceSize relative) const noexcept; + + [[nodiscard]] VkBufferUsageFlags GetViewUsage() const noexcept { + if (!mirror_capable || !bindable) { + return 0; + } + return mirror_usage; + } + + void CreateMirror(std::mutex &submit_mutex, VkDeviceSize max_size); + + [[nodiscard]] VkDeviceSize GetMirrorSize() const noexcept { + return mirror_size; + } + private: struct Window { vk::DeviceMemory memory; VkBuffer buffer{}; VkDeviceAddress address{}; + VkDeviceSize size{}; + u32 memory_type{}; }; + [[nodiscard]] bool SupportsMirror(VkBufferUsageFlags usage) const; + bool ImportHostPointer(void *base, size_t size); bool ImportHardwareBuffers(std::span hardware_buffers, @@ -154,6 +197,12 @@ namespace Vulkan { size_t base_offset{}; bool foreign_ownership{}; bool bindable{}; + bool mirror_capable{}; + VkBufferUsageFlags buffer_usage{}; + VkBufferUsageFlags mirror_usage{}; + VkBuffer mirror_buffer{}; + VkDeviceAddress mirror_address{}; + VkDeviceSize mirror_size{}; }; /// Memory allocator container. diff --git a/src/video_core/vulkan_common/vulkan_wrapper.cpp b/src/video_core/vulkan_common/vulkan_wrapper.cpp index 9c86ee15ad..db1325a183 100644 --- a/src/video_core/vulkan_common/vulkan_wrapper.cpp +++ b/src/video_core/vulkan_common/vulkan_wrapper.cpp @@ -316,6 +316,7 @@ bool Load(VkInstance instance, InstanceDispatch& dld) noexcept { X(vkDestroyDebugUtilsMessengerEXT); X(vkDestroyDebugReportCallbackEXT); X(vkDestroySurfaceKHR); + X(vkGetPhysicalDeviceExternalBufferProperties); X(vkGetPhysicalDeviceFeatures2); X(vkGetPhysicalDeviceFormatProperties2); X(vkGetPhysicalDeviceProperties2); @@ -1038,6 +1039,28 @@ VkPhysicalDeviceMemoryProperties2 PhysicalDevice::GetMemoryProperties( return properties; } +VkExternalMemoryProperties PhysicalDevice::GetExternalBufferProperties( + VkBufferCreateFlags flags, VkBufferUsageFlags usage, + VkExternalMemoryHandleTypeFlagBits handle_type) const noexcept { + VkExternalBufferProperties properties{ + .sType = VK_STRUCTURE_TYPE_EXTERNAL_BUFFER_PROPERTIES, + .pNext = nullptr, + .externalMemoryProperties = {}, + }; + if (!dld->vkGetPhysicalDeviceExternalBufferProperties) { + return properties.externalMemoryProperties; + } + const VkPhysicalDeviceExternalBufferInfo info{ + .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTERNAL_BUFFER_INFO, + .pNext = nullptr, + .flags = flags, + .usage = usage, + .handleType = handle_type, + }; + dld->vkGetPhysicalDeviceExternalBufferProperties(physical_device, &info, &properties); + return properties.externalMemoryProperties; +} + u32 AvailableVersion(const InstanceDispatch& dld) noexcept { PFN_vkEnumerateInstanceVersion vkEnumerateInstanceVersion; if (!Proc(vkEnumerateInstanceVersion, dld, "vkEnumerateInstanceVersion")) { diff --git a/src/video_core/vulkan_common/vulkan_wrapper.h b/src/video_core/vulkan_common/vulkan_wrapper.h index d23f8fd8a2..e32181f5ff 100644 --- a/src/video_core/vulkan_common/vulkan_wrapper.h +++ b/src/video_core/vulkan_common/vulkan_wrapper.h @@ -178,6 +178,7 @@ struct InstanceDispatch { PFN_vkEnumerateDeviceExtensionProperties vkEnumerateDeviceExtensionProperties{}; PFN_vkEnumeratePhysicalDevices vkEnumeratePhysicalDevices{}; PFN_vkGetDeviceProcAddr vkGetDeviceProcAddr{}; + PFN_vkGetPhysicalDeviceExternalBufferProperties vkGetPhysicalDeviceExternalBufferProperties{}; PFN_vkGetPhysicalDeviceFeatures2 vkGetPhysicalDeviceFeatures2{}; PFN_vkGetPhysicalDeviceFormatProperties vkGetPhysicalDeviceFormatProperties{}; PFN_vkGetPhysicalDeviceFormatProperties2 vkGetPhysicalDeviceFormatProperties2{}; @@ -1243,6 +1244,10 @@ public: VkPhysicalDeviceMemoryProperties2 GetMemoryProperties( void* next_structures = nullptr) const noexcept; + VkExternalMemoryProperties GetExternalBufferProperties( + VkBufferCreateFlags flags, VkBufferUsageFlags usage, + VkExternalMemoryHandleTypeFlagBits handle_type) const noexcept; + private: VkPhysicalDevice physical_device = nullptr; const InstanceDispatch* dld = nullptr; From 6e85c2307099c9a438c98c8c5809a21a90b9ce92 Mon Sep 17 00:00:00 2001 From: CamilleLaVey Date: Tue, 15 Sep 2026 05:02:32 -0400 Subject: [PATCH 27/27] TEST --- src/video_core/vulkan_common/vulkan_wrapper.cpp | 17 ++--------------- 1 file changed, 2 insertions(+), 15 deletions(-) diff --git a/src/video_core/vulkan_common/vulkan_wrapper.cpp b/src/video_core/vulkan_common/vulkan_wrapper.cpp index db1325a183..ec23ad253b 100644 --- a/src/video_core/vulkan_common/vulkan_wrapper.cpp +++ b/src/video_core/vulkan_common/vulkan_wrapper.cpp @@ -465,20 +465,8 @@ Instance Instance::Create(u32 version, Span layers, Span gloom + yellow line glitch appears -#ifdef __ANDROID__ - const VkApplicationInfo application_info{ - .sType = VK_STRUCTURE_TYPE_APPLICATION_INFO, - .pNext = nullptr, - .pApplicationName = "PUBGMobile", - .applicationVersion = VK_MAKE_VERSION(1, 7, 0), - .pEngineName = "UnrealEngine", - .engineVersion = VK_MAKE_VERSION(4, 23, 0), - .apiVersion = VK_API_VERSION_1_3, - }; -#else + // DO NOT TOUCH, breaks RNDA3!! + // Don't know why, but gloom + yellow line glitch appears const VkApplicationInfo application_info{ .sType = VK_STRUCTURE_TYPE_APPLICATION_INFO, .pNext = nullptr, @@ -488,7 +476,6 @@ Instance Instance::Create(u32 version, Span layers, Span