diff --git a/core/kyty/graphics/host_gpu/graphicContext.h b/core/kyty/graphics/host_gpu/graphicContext.h index a59c2ac1ff..5b5e06d771 100644 --- a/core/kyty/graphics/host_gpu/graphicContext.h +++ b/core/kyty/graphics/host_gpu/graphicContext.h @@ -127,7 +127,9 @@ struct GraphicContext { [[nodiscard]] bool CreateAllocator(); void DestroyAllocator(); void LogMemoryBudget() const; - [[nodiscard]] bool CanReportMemoryUsage() const noexcept { return memory_budget_ext_enabled; } + [[nodiscard]] bool CanReportMemoryUsage() const noexcept { + return memory_budget_ext_enabled || m_memory_override_enabled; + } [[nodiscard]] uint64_t GetDeviceMemoryUsage() const; [[nodiscard]] uint64_t GetTotalMemoryBudget() const; @@ -140,11 +142,17 @@ struct GraphicContext { [[nodiscard]] uint32_t GetHeapUsage(std::span heaps) const; [[nodiscard]] bool CreateImage(const vk::ImageCreateInfo& info, VulkanImage& image); void DeleteImage(VulkanImage& image); + void TrimRecycledImages(); + [[nodiscard]] size_t RecycledImageCount() const; uint32_t screen_width = 0; uint32_t screen_height = 0; private: + friend struct VramBudgetTestAccess; + bool m_memory_override_enabled = false; + uint64_t m_memory_budget_override = 0; + uint64_t m_memory_usage_override = 0; mutable std::mutex m_format_properties_mutex; mutable std::map m_format_properties; mutable std::mutex m_image_format_properties_mutex; diff --git a/core/kyty/graphics/host_gpu/renderer/cache/bufferCache.cpp b/core/kyty/graphics/host_gpu/renderer/cache/bufferCache.cpp index 2e6e38998c..1249b8d4ca 100644 --- a/core/kyty/graphics/host_gpu/renderer/cache/bufferCache.cpp +++ b/core/kyty/graphics/host_gpu/renderer/cache/bufferCache.cpp @@ -392,15 +392,19 @@ BufferCache::BufferCache(GraphicContext& graphics, CommandScheduler& scheduler, if (!m_graphics.CanReportMemoryUsage()) { return; } + UpdateMemoryThresholds(m_graphics.GetTotalMemoryBudget()); +} + +void BufferCache::UpdateMemoryThresholds(uint64_t budget_bytes) { + m_memory_budget = budget_bytes; constexpr int64_t GiB = 1024ll * 1024 * 1024; constexpr int64_t target_threshold = 8 * GiB; - const auto budget = - static_cast(std::min(m_graphics.GetTotalMemoryBudget(), INT64_MAX)); - const auto threshold = std::min(budget, target_threshold); - const auto expected = std::min(budget - 6 * threshold / 10, budget - GiB); - const auto critical = std::min(budget - 2 * threshold / 10, budget - GiB / 2); - m_trigger_gc_memory = static_cast(std::max(expected, GiB)); - m_critical_gc_memory = static_cast(std::max(critical, 2 * GiB)); + const auto budget = static_cast(std::min(budget_bytes, INT64_MAX)); + const auto threshold = std::min(budget, target_threshold); + const auto expected = std::min(budget - 6 * threshold / 10, budget - GiB); + const auto critical = std::min(budget - 2 * threshold / 10, budget - GiB / 2); + m_trigger_gc_memory = static_cast(std::max(expected, GiB)); + m_critical_gc_memory = static_cast(std::max(critical, 2 * GiB)); } BufferCache::~BufferCache() { @@ -3251,6 +3255,10 @@ void BufferCache::RunGarbageCollector() { const auto tick = m_gc_tick++; CollectStaleBuffers(tick); if (m_graphics.CanReportMemoryUsage()) { + const auto budget = m_graphics.GetTotalMemoryBudget(); + if (budget != m_memory_budget) { + UpdateMemoryThresholds(budget); + } m_total_used_memory = m_graphics.GetDeviceMemoryUsage(); } if (m_total_used_memory < m_trigger_gc_memory) { diff --git a/core/kyty/graphics/host_gpu/renderer/cache/bufferCache.h b/core/kyty/graphics/host_gpu/renderer/cache/bufferCache.h index 94ba4de757..73a40abac0 100644 --- a/core/kyty/graphics/host_gpu/renderer/cache/bufferCache.h +++ b/core/kyty/graphics/host_gpu/renderer/cache/bufferCache.h @@ -292,6 +292,7 @@ class BufferCache { private: friend struct BufferCacheTestAccess; friend struct BufferCacheGcTestAccess; + friend struct VramBudgetTestAccess; friend struct IndirectDispatchTestAccess; friend class TextureCache; @@ -600,9 +601,11 @@ class BufferCache { static constexpr size_t WrittenMemoSlots = 1024; std::unique_ptr> m_written_memo = std::make_unique>(); + uint64_t m_memory_budget = 0; uint64_t m_trigger_gc_memory = 1ull * 1024 * 1024 * 1024; uint64_t m_critical_gc_memory = 2ull * 1024 * 1024 * 1024; uint64_t m_gc_tick = 0; + void UpdateMemoryThresholds(uint64_t budget_bytes); void NoteBufferRegions(const Buffer& buffer, bool insert); void GrowRegionTables(uint64_t region); std::vector m_region_buffer_count; diff --git a/core/kyty/graphics/host_gpu/renderer/cache/textureCache.cpp b/core/kyty/graphics/host_gpu/renderer/cache/textureCache.cpp index 3893b55589..8ed13b93c0 100644 --- a/core/kyty/graphics/host_gpu/renderer/cache/textureCache.cpp +++ b/core/kyty/graphics/host_gpu/renderer/cache/textureCache.cpp @@ -164,18 +164,22 @@ TextureCache::TextureCache(GraphicContext& graphics, CommandScheduler& scheduler m_readback_storage_images = write_back_value != "0"; #endif if (m_graphics.CanReportMemoryUsage()) { - constexpr int64_t GiB = 1024ll * 1024 * 1024; - const auto budget = - static_cast(std::min(m_graphics.GetTotalMemoryBudget(), INT64_MAX)); - const auto threshold = std::min(budget, 8 * GiB); - m_pressure_gc_memory = static_cast( - std::max(std::min(budget - 6 * threshold / 10, budget - GiB), GiB + GiB / 2)); - m_critical_gc_memory = static_cast( - std::max(std::min(budget - 2 * threshold / 10, budget - GiB / 2), 3 * GiB)); - m_trigger_gc_memory = static_cast(std::max((budget - threshold) / 2, 0)); + UpdateMemoryThresholds(m_graphics.GetTotalMemoryBudget()); } } +void TextureCache::UpdateMemoryThresholds(uint64_t budget_bytes) { + m_memory_budget = budget_bytes; + constexpr int64_t GiB = 1024ll * 1024 * 1024; + const auto budget = static_cast(std::min(budget_bytes, INT64_MAX)); + const auto threshold = std::min(budget, 8 * GiB); + m_pressure_gc_memory = static_cast( + std::max(std::min(budget - 6 * threshold / 10, budget - GiB), GiB + GiB / 2)); + m_critical_gc_memory = static_cast( + std::max(std::min(budget - 2 * threshold / 10, budget - GiB / 2), 3 * GiB)); + m_trigger_gc_memory = static_cast(std::max((budget - threshold) / 2, 0)); +} + TextureCache::~TextureCache() { m_slot_images.ForEach([&](ImageId id, const Image& image) KYTY_NO_THREAD_SAFETY_ANALYSIS { if (image.registered) { @@ -3777,6 +3781,10 @@ void TextureCache::RunGarbageCollector() { const uint64_t tick = m_gc_tick++; DiscardParkedImages(0, 0); if (m_graphics.CanReportMemoryUsage()) { + const auto budget = m_graphics.GetTotalMemoryBudget(); + if (budget != m_memory_budget) { + UpdateMemoryThresholds(budget); + } m_total_used_memory = m_graphics.GetDeviceMemoryUsage(); } if (m_total_used_memory < m_trigger_gc_memory) { @@ -3788,10 +3796,10 @@ void TextureCache::RunGarbageCollector() { uint64_t age = 16; size_t deletions = 10; if (aggressive) { - age = 160; + age = 2; deletions = 40; } else if (pressured) { - age = GcDownloadAge; + age = 8; deletions = 20; } age = std::min(age, tick); @@ -3835,6 +3843,9 @@ void TextureCache::RunGarbageCollector() { if (m_total_used_memory >= m_critical_gc_memory) { collect(true); } + if (m_total_used_memory >= m_pressure_gc_memory) { + m_graphics.TrimRecycledImages(); + } } void TextureCache::ProcessDownloadImages() { diff --git a/core/kyty/graphics/host_gpu/renderer/cache/textureCache.h b/core/kyty/graphics/host_gpu/renderer/cache/textureCache.h index 877470354a..853968a26a 100644 --- a/core/kyty/graphics/host_gpu/renderer/cache/textureCache.h +++ b/core/kyty/graphics/host_gpu/renderer/cache/textureCache.h @@ -475,10 +475,12 @@ class TextureCache { std::unordered_map> m_stencil_copies; std::vector> m_parked_images; std::map m_surface_metas; + uint64_t m_memory_budget = 0; uint64_t m_total_used_memory = 0; uint64_t m_trigger_gc_memory = 0; uint64_t m_pressure_gc_memory = 1536ull * 1024 * 1024; uint64_t m_critical_gc_memory = 3ull * 1024 * 1024 * 1024; + void UpdateMemoryThresholds(uint64_t budget_bytes); uint64_t m_gc_tick = 0; std::atomic m_partial_candidates {0}; uint64_t m_image_set_epoch = 0; @@ -499,6 +501,7 @@ class TextureCache { [[nodiscard]] uint64_t ImageEpochInRegionUnlocked(uint64_t address, uint64_t size) const; friend struct TextureCacheTestAccess; + friend struct VramBudgetTestAccess; friend class BufferCache; friend class RenderExecutor; friend class ImageHeap; diff --git a/core/kyty/graphics/host_gpu/vma.cpp b/core/kyty/graphics/host_gpu/vma.cpp index 172c9dc541..f4a27c17c0 100644 --- a/core/kyty/graphics/host_gpu/vma.cpp +++ b/core/kyty/graphics/host_gpu/vma.cpp @@ -199,6 +199,9 @@ void GraphicContext::LogMemoryBudget() const { } uint64_t GraphicContext::GetDeviceMemoryUsage() const { + if (m_memory_override_enabled) { + return m_memory_usage_override; + } if (!CanReportMemoryUsage() || allocator == nullptr) { return 0; } @@ -237,6 +240,9 @@ uint32_t GraphicContext::GetHeapUsage(std::span } uint64_t GraphicContext::GetTotalMemoryBudget() const { + if (m_memory_override_enabled) { + return m_memory_budget_override; + } if (allocator == nullptr) { return 0; } @@ -357,4 +363,16 @@ void GraphicContext::DeleteImage(VulkanImage& image) { image.allocation = nullptr; } +void GraphicContext::TrimRecycledImages() { + if (allocator == nullptr) { + return; + } + DestroyRecycledImages(allocator); +} + +size_t GraphicContext::RecycledImageCount() const { + std::lock_guard lock(g_recycled_mutex); + return g_recycled.size(); +} + } diff --git a/core/libs/prx/libSceAgcDriver/KytyShim/tests/CMakeLists.txt b/core/libs/prx/libSceAgcDriver/KytyShim/tests/CMakeLists.txt index 4d5bdc20d1..4551e057ae 100644 --- a/core/libs/prx/libSceAgcDriver/KytyShim/tests/CMakeLists.txt +++ b/core/libs/prx/libSceAgcDriver/KytyShim/tests/CMakeLists.txt @@ -267,6 +267,14 @@ if(NOT ANYPS5_KYTY_DLL AND (WIN32 OR CMAKE_SYSTEM_NAME STREQUAL "Linux")) set_tests_properties(kyty_shim_buffer_cache_pages PROPERTIES TIMEOUT 25 SKIP_RETURN_CODE 77 ENVIRONMENT "KYTY_GPU_PIPELINE=0" PASS_REGULAR_EXPRESSION "kyty_shim_buffer_cache_pages: ok" FAIL_REGULAR_EXPRESSION "FAILED") + target_sources(libSceAgcDriver PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/VramBudget.cpp) + add_test_executable(kyty_shim_vram_budget_tests ${CMAKE_CURRENT_SOURCE_DIR}/VramBudgetMain.cpp) + configure_host_test_executable(kyty_shim_vram_budget_tests) + target_link_libraries(kyty_shim_vram_budget_tests PRIVATE libSceAgcDriver libkernel libc) + add_test(NAME kyty_shim_vram_budget COMMAND kyty_shim_vram_budget_tests) + set_tests_properties(kyty_shim_vram_budget PROPERTIES TIMEOUT 25 SKIP_RETURN_CODE 77 + ENVIRONMENT "KYTY_GPU_PIPELINE=0" + PASS_REGULAR_EXPRESSION "kyty_shim_vram_budget: ok" FAIL_REGULAR_EXPRESSION "FAILED") if(NOT ANYPS5_ENABLE_ASAN) target_sources(libSceAgcDriver PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/IndirectDispatchDimensions.cpp) add_test_executable(kyty_shim_indirect_dispatch_dimensions_tests ${CMAKE_CURRENT_SOURCE_DIR}/IndirectDispatchDimensionsMain.cpp) diff --git a/core/libs/prx/libSceAgcDriver/KytyShim/tests/VramBudget.cpp b/core/libs/prx/libSceAgcDriver/KytyShim/tests/VramBudget.cpp new file mode 100644 index 0000000000..92900b8fb4 --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/KytyShim/tests/VramBudget.cpp @@ -0,0 +1,183 @@ +#include "TestVulkanDevice.h" +#include "common/emulatorConfig.h" +#include "common/threads.h" +#include "graphics/guest_gpu/command_processor/commandProcessor.h" +#include "graphics/host_gpu/graphicContext.h" +#include "graphics/host_gpu/renderer/cache/bufferCache.h" +#include "graphics/host_gpu/renderer/cache/textureCache.h" +#include "graphics/host_gpu/renderer/renderContext.h" +#include "kernel/memory.h" +#include "prx/libkernel/include/Api.hpp" + +#include +#include +#include + +namespace Libs::Graphics { + +struct VramBudgetTestAccess { + static void SetReportedMemory(GraphicContext& graphics, uint64_t budget, uint64_t usage) { + graphics.m_memory_override_enabled = true; + graphics.m_memory_budget_override = budget; + graphics.m_memory_usage_override = usage; + } + + static uint64_t TextureTrigger(const TextureCache& cache) { return cache.m_trigger_gc_memory; } + static uint64_t TexturePressure(const TextureCache& cache) { return cache.m_pressure_gc_memory; } + static uint64_t TextureCritical(const TextureCache& cache) { return cache.m_critical_gc_memory; } + static uint64_t BufferTrigger(const BufferCache& cache) { return cache.m_trigger_gc_memory; } + static uint64_t BufferCritical(const BufferCache& cache) { return cache.m_critical_gc_memory; } + + static ImageId CreateImage(TextureCache& cache, const ImageInfo& info) { + Common::ScopedLock lock {cache.m_lock}; + return cache.InsertImage(info); + } + + static bool IsImageRegistered(TextureCache& cache, ImageId id) { + Common::ScopedLock lock {cache.m_lock}; + const auto* image = cache.m_slot_images.try_get(id); + return image != nullptr && image->registered; + } +}; + +} + +namespace { + +using namespace Libs::Graphics; + +constexpr uint64_t GiB = 1024ull * 1024 * 1024; +constexpr uint64_t GuestBytes = 0x20000; +constexpr int CpuReadWrite = 0x03; + +const char* CheckVramBudget(GraphicContext& graphics, uint64_t address) { + VramBudgetTestAccess::SetReportedMemory(graphics, 16 * GiB, 0); + + RenderContext renderer(graphics); + CommandProcessor producer(renderer, 0); + producer.Reset(); + auto& scheduler = renderer.GetCommandScheduler(); + auto& textures = renderer.GetTextureCache(); + auto& buffers = renderer.GetBufferCache(); + scheduler.Begin(producer.GetCtx(), producer.GetUcfg(), producer.GetShCtx()); + + const auto tex_trigger_large = VramBudgetTestAccess::TextureTrigger(textures); + const auto tex_pressure_large = VramBudgetTestAccess::TexturePressure(textures); + const auto tex_critical_large = VramBudgetTestAccess::TextureCritical(textures); + const auto buf_trigger_large = VramBudgetTestAccess::BufferTrigger(buffers); + const auto buf_critical_large = VramBudgetTestAccess::BufferCritical(buffers); + + VramBudgetTestAccess::SetReportedMemory(graphics, 6 * GiB, 0); + textures.RunGarbageCollector(); + buffers.RunGarbageCollector(); + + const auto tex_trigger_small = VramBudgetTestAccess::TextureTrigger(textures); + const auto tex_pressure_small = VramBudgetTestAccess::TexturePressure(textures); + const auto tex_critical_small = VramBudgetTestAccess::TextureCritical(textures); + const auto buf_trigger_small = VramBudgetTestAccess::BufferTrigger(buffers); + const auto buf_critical_small = VramBudgetTestAccess::BufferCritical(buffers); + + if (tex_trigger_small >= tex_trigger_large || tex_pressure_small >= tex_pressure_large || + tex_critical_small >= tex_critical_large) { + return "texture cache GC did not refresh thresholds when reported budget decreased"; + } + if (tex_trigger_small != 0) { + return "texture cache trigger threshold was non-zero at <= 8 GiB budget"; + } + if (buf_trigger_small >= buf_trigger_large || buf_critical_small >= buf_critical_large) { + return "buffer cache GC did not refresh thresholds when reported budget decreased"; + } + + vk::ImageCreateInfo recycle_info {}; + recycle_info.imageType = vk::ImageType::e2D; + recycle_info.format = vk::Format::eR8G8B8A8Unorm; + recycle_info.extent = vk::Extent3D {64, 64, 1}; + recycle_info.mipLevels = 1; + recycle_info.arrayLayers = 1; + recycle_info.samples = vk::SampleCountFlagBits::e1; + recycle_info.tiling = vk::ImageTiling::eOptimal; + recycle_info.usage = vk::ImageUsageFlagBits::eTransferDst | vk::ImageUsageFlagBits::eSampled; + recycle_info.sharingMode = vk::SharingMode::eExclusive; + recycle_info.initialLayout = vk::ImageLayout::eUndefined; + + VulkanImage recycled_image {}; + if (!graphics.CreateImage(recycle_info, recycled_image)) { + return "could not create recyclable image for recycle pool check"; + } + graphics.DeleteImage(recycled_image); + if (graphics.RecycledImageCount() == 0) { + return "deleted recyclable image did not enter the recycle pool"; + } + + ImageInfo info; + info.data.address = address; + info.pixel_format = vk::Format::eR8G8B8A8Unorm; + info.guest_format = Prospero::BufferFormat::k8_8_8_8UNorm; + info.extent = vk::Extent3D {64, 64, 1}; + info.pitch = 64; + info.UpdateSize(); + + const auto id = VramBudgetTestAccess::CreateImage(textures, info); + if (!VramBudgetTestAccess::IsImageRegistered(textures, id)) { + return "test image was not registered"; + } + + VramBudgetTestAccess::SetReportedMemory(graphics, 6 * GiB, 6 * GiB); + for (uint32_t i = 0; i < 4; i++) { + textures.RunGarbageCollector(); + } + if (VramBudgetTestAccess::IsImageRegistered(textures, id)) { + return "critical memory pressure did not evict a recent unused texture"; + } + if (graphics.RecycledImageCount() != 0) { + return "pressure GC pass did not drain the recycled image pool"; + } + + const auto last = scheduler.CurrentTick(); + scheduler.Wait(last); + scheduler.WaitPriorityOperations(last); + return nullptr; +} + +} + +extern "C" int RunKytyVramBudgetTest() { + Common::InitializeThreads(); + Config::Initialize(); + Config::Load(Config::ConfigOptions {}); + KytyShimTests::TestVulkanDevice gpu; + if (const auto* unavailable = gpu.Initialize()) { + const bool required = std::getenv("ANYPS5_REQUIRE_VULKAN") != nullptr; + std::fprintf(stderr, "kyty_shim_vram_budget: %s, no usable Vulkan device (%s)\n", + required ? "FAILED" : "skipped", unavailable); + return required ? 1 : 77; + } + if (!gpu.graphics.CreateAllocator()) { + std::fputs("kyty_shim_vram_budget: FAILED: could not create the allocator\n", stderr); + return 1; + } + void* guest = nullptr; + if (sceKernelMapFlexibleMemory(&guest, GuestBytes, CpuReadWrite, 0) != 0 || guest == nullptr) { + std::fputs("kyty_shim_vram_budget: FAILED: could not map guest backing\n", stderr); + return 1; + } + const auto address = reinterpret_cast(guest); + if (!GuestRange {address, GuestBytes}.Valid()) { + (void)sceKernelMunmap(address, GuestBytes); + const bool required = std::getenv("ANYPS5_REQUIRE_VULKAN") != nullptr; + std::fprintf(stderr, "kyty_shim_vram_budget: %s, guest range 0x%llx is outside Kyty bounds\n", + required ? "FAILED" : "skipped", static_cast(address)); + return required ? 1 : 77; + } + const char* failure = CheckVramBudget(gpu.graphics, address); + if (sceKernelMunmap(address, GuestBytes) != 0) { + std::fputs("kyty_shim_vram_budget: FAILED: could not unmap guest backing\n", stderr); + return 1; + } + if (failure != nullptr) { + std::fprintf(stderr, "kyty_shim_vram_budget: FAILED: %s\n", failure); + return 1; + } + std::puts("kyty_shim_vram_budget: ok"); + return 0; +} diff --git a/core/libs/prx/libSceAgcDriver/KytyShim/tests/VramBudgetMain.cpp b/core/libs/prx/libSceAgcDriver/KytyShim/tests/VramBudgetMain.cpp new file mode 100644 index 0000000000..2616cbc2f4 --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/KytyShim/tests/VramBudgetMain.cpp @@ -0,0 +1,5 @@ +extern "C" int RunKytyVramBudgetTest(); + +int main() { + return RunKytyVramBudgetTest(); +}