From 06f8888a387cfbd9f3b2d563f0650dd5bbaa133a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jan=20=C5=A0l=C3=A9gl?= Date: Tue, 24 Nov 2026 19:25:30 +0100 Subject: [PATCH 1/2] fix(kyty): keep GPU writes when a request for more layers replaces an image When a lookup finds a cached image with fewer subresources than the request, FindImageImpl frees it and creates the requested image from guest memory. A GPU-written image whose writes were not written back loses them there: the new image holds the older guest bytes. Expand a GPU-written image with as many levels as the request instead, as ResolveOverlap already does for a same-format request with more subresources: the new image is loaded from guest memory and the cached image is copied into its first layers. With equal level counts a layer starts at the same guest offset in both images, so the copy by index keeps each layer in place. Other images are freed as before. --- .../host_gpu/renderer/cache/textureCache.cpp | 9 +- .../KytyShim/tests/ImageWriteBackAlias.cpp | 109 ++++++++++++++++++ 2 files changed, 116 insertions(+), 2 deletions(-) diff --git a/core/kyty/graphics/host_gpu/renderer/cache/textureCache.cpp b/core/kyty/graphics/host_gpu/renderer/cache/textureCache.cpp index 97be22166e2..c9ec1e89a48 100644 --- a/core/kyty/graphics/host_gpu/renderer/cache/textureCache.cpp +++ b/core/kyty/graphics/host_gpu/renderer/cache/textureCache.cpp @@ -2629,8 +2629,13 @@ ImageId TextureCache::FindImageImpl(ImageDesc& desc, bool exact_format, bool spe if (KeepsBoundDepth(desc.type, resolved)) { return NullForBoundDepth(desc, resolved); } - FreeImage(result); - result = {}; + if (resolved.IsGpuModified() && + resolved.info.resources.levels == desc.info.resources.levels) { + result = ExpandImage(desc.info, result); + } else { + FreeImage(result); + result = {}; + } } } if (result && same_backing && desc.type != BindingType::VideoOut) { diff --git a/core/libs/prx/libSceAgcDriver/KytyShim/tests/ImageWriteBackAlias.cpp b/core/libs/prx/libSceAgcDriver/KytyShim/tests/ImageWriteBackAlias.cpp index b4cbe79b59c..e765f8616e9 100644 --- a/core/libs/prx/libSceAgcDriver/KytyShim/tests/ImageWriteBackAlias.cpp +++ b/core/libs/prx/libSceAgcDriver/KytyShim/tests/ImageWriteBackAlias.cpp @@ -14,6 +14,7 @@ #include #include #include +#include namespace Libs::Graphics { @@ -333,6 +334,102 @@ const char* CheckRangePicksLatestWrite(GraphicContext& graphics, uint64_t addres return nullptr; } +struct LayerFormat { + vk::Format host; + Prospero::BufferFormat guest; +}; + +const char* CheckLargerRequestOverGpuWrites(GraphicContext& graphics, uint64_t address, + LayerFormat cached_format, LayerFormat requested_format, + uint32_t requested_levels) { + 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()); + + constexpr uint32_t Width = 64; + constexpr uint32_t Height = 4; + constexpr uint32_t CachedLayers = 4; + constexpr uint32_t RequestedLayers = 6; + constexpr uint32_t CachedWords = CachedLayers * Width * Height; + constexpr uint32_t RequestedWords = RequestedLayers * Width * Height; + const auto layered = [address](LayerFormat format, uint32_t levels, uint32_t layers) { + ImageInfo info; + info.data.address = address; + info.pixel_format = format.host; + info.guest_format = format.guest; + info.extent = vk::Extent3D {Width, Height, 1}; + info.pitch = Width; + info.resources = {levels, layers}; + info.UpdateSize(); + return info; + }; + const auto cached_info = layered(cached_format, 1, CachedLayers); + const auto requested_info = layered(requested_format, requested_levels, RequestedLayers); + const bool keeps = requested_levels == 1; + if (requested_info.data.size > GuestBytes / 8) return "the layered image does not fit its guest range"; + const std::vector guest(requested_info.data.size / sizeof(uint32_t), FillValue); + if (!Libs::LibKernel::Memory::TryWriteBacking(address, guest.data(), requested_info.data.size)) { + return "could not write the guest backing"; + } + + std::vector written(CachedWords); + for (uint32_t i = 0; i < CachedWords; ++i) { + written[i] = ImageValue + i; + } + const std::array cached_copies {vk::BufferImageCopy { + 0, 0, 0, {vk::ImageAspectFlagBits::eColor, 0, 0, CachedLayers}, {}, cached_info.extent}}; + const std::array requested_copies {vk::BufferImageCopy { + 0, 0, 0, {vk::ImageAspectFlagBits::eColor, 0, 0, RequestedLayers}, {}, requested_info.extent}}; + Buffer initial(graphics, scheduler, MemoryUsage::Upload, 0, vk::BufferUsageFlagBits::eTransferSrc, + CachedWords * sizeof(uint32_t)); + std::memcpy(initial.Mapped().data(), written.data(), CachedWords * sizeof(uint32_t)); + initial.Flush(0, CachedWords * sizeof(uint32_t)); + const auto cached = TextureCacheTestAccess::Create(textures, cached_info); + textures.GetImage(cached).Upload(cached_copies, initial.Handle(), 0, CachedWords * sizeof(uint32_t)); + textures.MarkGpuWritten(cached); + + TextureCache::ImageDesc desc {.info = requested_info}; + desc.view_info.format = requested_info.pixel_format; + const auto found = textures.FindImage(desc); + Buffer readback(graphics, scheduler, MemoryUsage::Download, 0, vk::BufferUsageFlagBits::eTransferDst, + RequestedWords * sizeof(uint32_t)); + bool kept_gpu_write = false; + uint32_t found_layers = 0; + if (found) { + textures.UpdateImage(found); + auto& image = textures.GetImage(found); + kept_gpu_write = image.IsGpuModified(); + found_layers = image.info.resources.layers; + image.Download(requested_copies, readback.Handle(), 0, RequestedWords * sizeof(uint32_t)); + } + const auto tick = scheduler.CurrentTick(); + scheduler.Wait(tick); + scheduler.WaitPriorityOperations(tick); + (void)buffers.DropFreedRange(address, requested_info.data.size, nullptr, nullptr); + if (found_layers != RequestedLayers) return "the larger request found no image with its layers"; + readback.Invalidate(0, RequestedWords * sizeof(uint32_t)); + std::vector actual(RequestedWords); + std::memcpy(actual.data(), readback.Mapped().data(), RequestedWords * sizeof(uint32_t)); + for (uint32_t i = 0; i < CachedWords; ++i) { + if (actual[i] != (keeps ? written[i] : FillValue)) { + return keeps ? "a request for more layers dropped the GPU-written layers" + : "an image with fewer levels was copied into the request's layers"; + } + } + for (uint32_t i = CachedWords; i < RequestedWords; ++i) { + if (actual[i] != FillValue) return "the added layers were not loaded from guest memory"; + } + if (kept_gpu_write != keeps) { + return keeps ? "the image that kept the GPU-written layers is not marked GPU-written" + : "the image loaded from guest memory is marked GPU-written"; + } + return nullptr; +} + } extern "C" int RunKytyImageWriteBackAliasTest() { @@ -368,6 +465,18 @@ extern "C" int RunKytyImageWriteBackAliasTest() { Prospero::TileMode::kStandard4KB); failure = linear != nullptr ? linear : tiled; } + constexpr LayerFormat Words {vk::Format::eR32Uint, Prospero::BufferFormat::k32UInt}; + constexpr LayerFormat Bytes {vk::Format::eR8G8B8A8Unorm, Prospero::BufferFormat::k8_8_8_8UNorm}; + constexpr LayerFormat SwappedBytes {vk::Format::eB8G8R8A8Unorm, Prospero::BufferFormat::k8_8_8_8UNorm}; + if (failure == nullptr) { + failure = CheckLargerRequestOverGpuWrites(graphics, address + GuestBytes / 8 * 5, Words, Bytes, 1); + } + if (failure == nullptr) { + failure = CheckLargerRequestOverGpuWrites(graphics, address + GuestBytes / 8 * 6, SwappedBytes, Bytes, 1); + } + if (failure == nullptr) { + failure = CheckLargerRequestOverGpuWrites(graphics, address + GuestBytes / 8 * 5, Words, Bytes, 2); + } if (failure == nullptr) { failure = CheckRangePicksLatestWrite(graphics, address + GuestBytes / 8 * 7); } From 9ca4f9888e8e55beaef9c575febed43b2bbe4242 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jan=20=C5=A0l=C3=A9gl?= Date: Wed, 25 Nov 2026 22:51:48 +0100 Subject: [PATCH 2/2] fix(kyty): expand only images the cache can refresh as copy sources A GPU-written image that a guest write invalidated keeps its GPU-modified flag, so the fewer-resources branch of FindImageImpl also expands it. ExpandImage refreshes the source first, and RefreshCopySource stops the process when the refresh cannot clear the CPU-dirty state: InitializeImage returns early for a multisampled image, and RefreshImage stops for a compressed one. Expand only single-sample uncompressed images, for which the refresh clears the CPU-dirty state; free the others as before, including clean multisampled and compressed ones. The new check covers a GPU-written image invalidated before the larger request: with one sample the expanded image holds the newer guest bytes in the old layers; with four samples the lookup returns an image with the requested layers instead of stopping in RefreshCopySource. The test device now enables shaderStorageImageMultisample when supported and otherwise limits storageImageSampleCounts to one sample, as VulkanCreateDevice does, so the multisampled images the check creates are valid under the validation layer. --- .../host_gpu/renderer/cache/textureCache.cpp | 7 +- .../KytyShim/tests/ImageWriteBackAlias.cpp | 115 ++++++++++++++++++ .../KytyShim/tests/TestVulkanDevice.h | 7 +- 3 files changed, 127 insertions(+), 2 deletions(-) diff --git a/core/kyty/graphics/host_gpu/renderer/cache/textureCache.cpp b/core/kyty/graphics/host_gpu/renderer/cache/textureCache.cpp index c9ec1e89a48..880580cdff4 100644 --- a/core/kyty/graphics/host_gpu/renderer/cache/textureCache.cpp +++ b/core/kyty/graphics/host_gpu/renderer/cache/textureCache.cpp @@ -1082,6 +1082,11 @@ void TextureCache::RefreshCopySource(ImageId id) { } } +static bool RefreshesAsCopySource(const Image& image) { + return image.info.samples == 1 && image.backing.samples == 1 && + image.info.metadata.compression == VideoOutCompression::Uncompressed; +} + static bool DepthColorCopyCompatible(vk::Format depth, vk::Format color) { switch (depth) { case vk::Format::eD16Unorm: @@ -2629,7 +2634,7 @@ ImageId TextureCache::FindImageImpl(ImageDesc& desc, bool exact_format, bool spe if (KeepsBoundDepth(desc.type, resolved)) { return NullForBoundDepth(desc, resolved); } - if (resolved.IsGpuModified() && + if (resolved.IsGpuModified() && RefreshesAsCopySource(resolved) && resolved.info.resources.levels == desc.info.resources.levels) { result = ExpandImage(desc.info, result); } else { diff --git a/core/libs/prx/libSceAgcDriver/KytyShim/tests/ImageWriteBackAlias.cpp b/core/libs/prx/libSceAgcDriver/KytyShim/tests/ImageWriteBackAlias.cpp index e765f8616e9..806d9445320 100644 --- a/core/libs/prx/libSceAgcDriver/KytyShim/tests/ImageWriteBackAlias.cpp +++ b/core/libs/prx/libSceAgcDriver/KytyShim/tests/ImageWriteBackAlias.cpp @@ -9,6 +9,7 @@ #include "prx/libkernel/DirectMemory/DirectMemory.hpp" #include "prx/libkernel/include/Api.hpp" +#include #include #include #include @@ -51,6 +52,9 @@ constexpr uint32_t WriteWords = 4; constexpr uint32_t ImageValue = 0x19283746; constexpr uint32_t CopyValue = 0xdecafbad; constexpr uint32_t FillValue = 0x1234fedc; +constexpr uint32_t CpuValue = 0x5aa5c33c; +constexpr uint64_t MultisampleGuestBytes = 0x100000; +constexpr uint64_t MultisampleAlignment = 0x10000; const char* CheckWriteBackOrder(GraphicContext& graphics, uint64_t address) { RenderContext renderer(graphics); @@ -430,6 +434,97 @@ const char* CheckLargerRequestOverGpuWrites(GraphicContext& graphics, uint64_t a return nullptr; } +const char* CheckLargerRequestOverInvalidatedWrites(GraphicContext& graphics, uint64_t address, uint64_t limit, + LayerFormat cached_format, LayerFormat requested_format, + uint32_t samples) { + 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()); + + constexpr uint32_t Width = 32; + constexpr uint32_t Height = 4; + constexpr uint32_t CachedLayers = 4; + constexpr uint32_t RequestedLayers = 6; + constexpr uint32_t CachedWords = CachedLayers * Width * Height; + constexpr uint32_t RequestedWords = RequestedLayers * Width * Height; + const auto layered = [address, samples](LayerFormat format, uint32_t layers) { + ImageInfo info; + info.data.address = address; + info.pixel_format = format.host; + info.guest_format = format.guest; + info.extent = vk::Extent3D {Width, Height, 1}; + info.tile_mode = samples == 1 ? Prospero::TileMode::kLinear : Prospero::TileMode::kRenderTarget; + info.pitch = samples == 1 ? Width : 0; + info.samples = samples; + info.resources = {1, layers}; + info.UpdateSize(); + return info; + }; + const auto cached_info = layered(cached_format, CachedLayers); + const auto requested_info = layered(requested_format, RequestedLayers); + if (requested_info.data.size > limit) return "the layered image does not fit its guest range"; + std::vector guest(requested_info.data.size / sizeof(uint32_t), FillValue); + if (!Libs::LibKernel::Memory::TryWriteBacking(address, guest.data(), requested_info.data.size)) { + return "could not write the guest backing"; + } + + const auto cached = TextureCacheTestAccess::Create(textures, cached_info); + { + auto& image = textures.GetImage(cached); + const auto native = scheduler.Current().Handle(); + image.Transit(vk::ImageLayout::eTransferDstOptimal, vk::AccessFlagBits2::eTransferWrite, {}, native); + const vk::ClearColorValue clear {.float32 = {std::array {1.0f, 0.5f, 0.25f, 1.0f}}}; + const vk::ImageSubresourceRange range {vk::ImageAspectFlagBits::eColor, 0, 1, 0, CachedLayers}; + native.clearColorImage(image.backing.image, vk::ImageLayout::eTransferDstOptimal, &clear, 1, &range); + } + textures.MarkGpuWritten(cached); + std::fill(guest.begin(), guest.begin() + cached_info.data.size / sizeof(uint32_t), CpuValue); + if (!Libs::LibKernel::Memory::TryWriteBacking(address, guest.data(), cached_info.data.size)) { + return "could not write the guest backing"; + } + (void)textures.InvalidateMemory(address, cached_info.data.size); + const auto& invalidated = textures.GetImage(cached); + const bool stale = invalidated.IsGpuModified() && invalidated.IsDefinitelyCpuDirty(); + + TextureCache::ImageDesc desc {.info = requested_info}; + desc.view_info.format = requested_info.pixel_format; + const auto found = textures.FindImage(desc); + const std::array requested_copies {vk::BufferImageCopy { + 0, 0, 0, {vk::ImageAspectFlagBits::eColor, 0, 0, RequestedLayers}, {}, requested_info.extent}}; + Buffer readback(graphics, scheduler, MemoryUsage::Download, 0, vk::BufferUsageFlagBits::eTransferDst, + RequestedWords * sizeof(uint32_t)); + uint32_t found_layers = 0; + if (found) { + auto& image = textures.GetImage(found); + found_layers = image.info.resources.layers; + if (samples == 1) { + textures.UpdateImage(found); + image.Download(requested_copies, readback.Handle(), 0, RequestedWords * sizeof(uint32_t)); + } + } + const auto tick = scheduler.CurrentTick(); + scheduler.Wait(tick); + scheduler.WaitPriorityOperations(tick); + (void)buffers.DropFreedRange(address, requested_info.data.size, nullptr, nullptr); + if (!stale) return "the guest write did not invalidate the GPU-written image"; + if (found_layers != RequestedLayers) return "the larger request found no image with its layers"; + if (samples != 1) return nullptr; + readback.Invalidate(0, RequestedWords * sizeof(uint32_t)); + std::vector actual(RequestedWords); + std::memcpy(actual.data(), readback.Mapped().data(), RequestedWords * sizeof(uint32_t)); + for (uint32_t i = 0; i < CachedWords; ++i) { + if (actual[i] != CpuValue) return "a request for more layers kept GPU writes over a newer guest write"; + } + for (uint32_t i = CachedWords; i < RequestedWords; ++i) { + if (actual[i] != FillValue) return "the added layers were not loaded from guest memory"; + } + return nullptr; +} + } extern "C" int RunKytyImageWriteBackAliasTest() { @@ -477,6 +572,26 @@ extern "C" int RunKytyImageWriteBackAliasTest() { if (failure == nullptr) { failure = CheckLargerRequestOverGpuWrites(graphics, address + GuestBytes / 8 * 5, Words, Bytes, 2); } + if (failure == nullptr) { + failure = CheckLargerRequestOverInvalidatedWrites(graphics, address + GuestBytes / 8 * 5, GuestBytes / 8, + SwappedBytes, Bytes, 1); + } + if (failure == nullptr) { + constexpr uint64_t Mapped = MultisampleGuestBytes + MultisampleAlignment; + void* multisample_guest = nullptr; + if (sceKernelMapFlexibleMemory(&multisample_guest, Mapped, CpuReadWrite, 0) != 0 || + multisample_guest == nullptr) { + failure = "could not map the multisample backing"; + } else { + const auto mapped = reinterpret_cast(multisample_guest); + const auto aligned = (mapped + MultisampleAlignment - 1) & ~(MultisampleAlignment - 1); + failure = CheckLargerRequestOverInvalidatedWrites(graphics, aligned, MultisampleGuestBytes, + SwappedBytes, Bytes, 4); + if (sceKernelMunmap(mapped, Mapped) != 0 && failure == nullptr) { + failure = "could not unmap the multisample backing"; + } + } + } if (failure == nullptr) { failure = CheckRangePicksLatestWrite(graphics, address + GuestBytes / 8 * 7); } diff --git a/core/libs/prx/libSceAgcDriver/KytyShim/tests/TestVulkanDevice.h b/core/libs/prx/libSceAgcDriver/KytyShim/tests/TestVulkanDevice.h index a161c08a0da..2cb6b13003d 100644 --- a/core/libs/prx/libSceAgcDriver/KytyShim/tests/TestVulkanDevice.h +++ b/core/libs/prx/libSceAgcDriver/KytyShim/tests/TestVulkanDevice.h @@ -117,7 +117,9 @@ struct TestVulkanDevice { const vk::PhysicalDeviceVulkan13Features features13 { .pNext = &features11, .synchronization2 = VK_TRUE, .dynamicRendering = VK_TRUE}; const vk::PhysicalDeviceFeatures core_features { - .sampleRateShading = VK_TRUE, .shaderInt64 = VK_TRUE}; + .sampleRateShading = VK_TRUE, + .shaderStorageImageMultisample = supported.features.shaderStorageImageMultisample, + .shaderInt64 = VK_TRUE}; const float priority = 1.0f; const vk::DeviceQueueCreateInfo queue_info { .queueFamilyIndex = static_cast(family - families.begin()), @@ -133,6 +135,9 @@ struct TestVulkanDevice { VULKAN_HPP_DEFAULT_DISPATCHER.init(graphics.device); graphics.physical_device = physical; graphics.physical_device_properties = properties.properties; + if (!core_features.shaderStorageImageMultisample) { + graphics.physical_device_properties.limits.storageImageSampleCounts = vk::SampleCountFlagBits::e1; + } graphics.physical_device_memory_properties = physical.getMemoryProperties(); graphics.queue_family = queue_info.queueFamilyIndex; graphics.device.getQueue(graphics.queue_family, 0, &graphics.queue);