#include "graphics/host_gpu/renderer/cache/textureCache.h" #include "common/alignment.h" #include "common/assert.h" #include "common/debugCounters.h" #include "common/emulatorConfig.h" #include "common/logging/log.h" #include "common/profiler.h" #include "graphics/guest_gpu/gpu_format.h" #include "graphics/guest_gpu/tile.h" #include "graphics/host_gpu/graphicContext.h" #include "graphics/host_gpu/renderer/cache/bufferCache.h" #include "graphics/host_gpu/renderer/commandScheduler.h" #include "graphics/host_gpu/renderer/image/imageView.h" #include "graphics/host_gpu/renderer/image/refreshRegions.h" #include "graphics/host_gpu/renderer/image/textureCommon.h" #include "graphics/host_gpu/renderer/image/tiler.h" #include "graphics/host_gpu/renderer/render.h" #include "kernel/memory.h" #include #include #include #include #include #include #include #include #include #include #include namespace Libs::Graphics { namespace { // Scheduler ticks. Each submit is a tick, so this was about two or three frames before the submit // cadence began to submit many times per frame. constexpr uint64_t NumFramesBeforeRemoval = 16; // With the submit cadence on, the age counts garbage collector ticks, which come once per frame // whatever the submit rate. Three keeps the protection of the 32 scheduler ticks above. constexpr uint64_t NumGcTicksBeforeRemoval = 3; // Largest GPU-written tiled image (in texels) that is written back to guest memory on submit. constexpr uint64_t SmallTiledReadbackTexels = 64 * 64; // A clear code is key << ColorClearKeyShift, so the code bits below the shift are always clear // in the DCC (0x00, 0x20, 0x40, 0x80 and 0xc0) and CMask (0x00) codes DecodeColorClear accepts. // The steady state code 0xff has them set, so it skips the decode. constexpr uint32_t ColorClearKeyShift = 5; constexpr uint8_t ColorClearCodeLowBits = (1u << ColorClearKeyShift) - 1u; // Slice counts up to this read their codes into the stack. Larger views fall back to the heap. constexpr uint32_t ColorClearCodesOnStack = 128; [[nodiscard]] bool SameMipPlacement(const TileMipLayout& left, const TileMipLayout& right) { return left == right; } // Guest mip chains run backwards, so a texture with fewer levels keeps its base level at a // different offset than one with a longer chain at the same address. Every level both layouts // have must be placed identically for one image to serve the other. [[nodiscard]] bool SharedLevelsMatch(const ImageInfo& left, const ImageInfo& right) { const auto shared = std::min(left.resources.levels, right.resources.levels); return std::equal(left.mip_layout.begin(), left.mip_layout.begin() + shared, right.mip_layout.begin(), SameMipPlacement); } // Reads the first byte of each of count metadata slices in one locked pass, so a clear applied // later cannot change a code that is still to be read. Slice counts up to // ColorClearCodesOnStack stay on the stack so the common case allocates nothing, and larger // views fall back to the heap. It exits on an unreadable slice. class ColorClearCodes { public: ColorClearCodes(uint64_t first, uint64_t stride, uint32_t count) { m_codes = m_stack.data(); if (count > m_stack.size()) { m_heap.resize(count); m_codes = m_heap.data(); } if (!LibKernel::Memory::TryReadBackingStrided(first, stride, count, m_codes)) { EXIT("TextureCache: failed to read color metadata backing\n"); } } KYTY_CLASS_NO_COPY(ColorClearCodes); [[nodiscard]] uint8_t operator[](uint32_t slice) const { return m_codes[slice]; } private: std::array m_stack; std::vector m_heap; uint8_t* m_codes = nullptr; }; // A buffer write over more than 1 / this of an image refreshes the whole image, because a partial // refresh then costs about as much as a full one. constexpr uint64_t PartialRefreshMaxFraction = 2; // Marks a whole image as newer in a buffer. gpu_mod is cleared first so that the next bind // treats the buffer as the source of truth, which is how every non-partial write behaves. void MarkWholeBufferWrite(Image& image) { if (image.IsGpuModified()) { image.ClearGpuModified(); } image.MarkBufferModified(); } // The bytes a set of refresh rectangles copies, for the transfer counters. [[nodiscard]] uint64_t RegionBytes(const ImageInfo& info, std::span regions) { uint64_t bytes = 0; for (const auto& region: regions) { bytes += uint64_t {region.width} * region.height * info.tiling.block.bytes_per_element; } return bytes; } // Tells whether a written range is small enough for a partial refresh to pay off. [[nodiscard]] bool WithinPartialLimit(const Image& image, uint64_t size) { return size <= image.info.data.size / PartialRefreshMaxFraction; } // Colour DCC and CMASK live at their own addresses, so a write at the image base is a data write // that never touches them. Their keys only matter to MaterializeColorClear, which runs after the // refresh and so wins in the viewed region exactly as it does after a full refresh, and which // keeps its checked state because a data write cannot change a key. HTILE is depth only. A // whitelist makes any metadata kind added later default to the full refresh. [[nodiscard]] bool IsPartialRefreshMetadata(ImageMetadataKind kind) { return kind == ImageMetadataKind::None || kind == ImageMetadataKind::Dcc || kind == ImageMetadataKind::Cmask; } // Tells whether a range-limited refresh is exact for this image. Layouts whose byte ranges do not // map to a contiguous set of texels stay on the full refresh, and so do images that other // objects share or convert, such as depth and stencil, video-out, Fmask and compressed images. [[nodiscard]] bool IsPartialRefreshEligible(const Image& image) { const auto& info = image.info; if (info.IsVolume() || info.samples != 1 || image.backing.samples != 1 || info.IsDepth() || info.HasStencil() || info.pixel_format == vk::Format::eS8Uint || image.depth_id || !image.stencil_ids.empty() || info.IsBlock() || !IsPartialRefreshMetadata(info.metadata.kind) || info.metadata.compression != VideoOutCompression::Uncompressed || image.usage.video_out || info.GetColorTransform() != ColorTransform::None) { return false; } switch (info.tile_mode) { case Prospero::TileMode::kLinear: return true; case Prospero::TileMode::kStandard256B: case Prospero::TileMode::kStandard4KB: case Prospero::TileMode::kStandard64KB: case Prospero::TileMode::kPrt: case Prospero::TileMode::kRenderTarget: return !Prospero::IsFmaskTextureFormat(info.guest_format); default: return false; } } } // namespace [[nodiscard]] bool DecodeColorClear(const TextureCache::ImageDesc& desc, uint8_t code, vk::ClearColorValue& clear) { const auto& metadata = desc.info.metadata; const auto format = desc.info.IsDepth() ? TextureGetSurfaceFormatInfo(desc.info.guest_format).vk_format : desc.view_info.format; const bool cmask = metadata.kind == ImageMetadataKind::Cmask; // PS5 DCC fast clears to the CB_COLOR_CLEAR_WORD value fill the keys with 0x10, not only the // GFX10 0x20. if (cmask ? code == 0 : (code == 0x20 || code == 0x10)) { // Register clears belong to the color buffer; the texture pipe cannot decode them. return desc.type == TextureCache::BindingType::RenderTarget && metadata.clear_register_valid && DecodePackedColorClear(format, metadata.clear_word, clear); } if (cmask) { return false; } switch (code) { case 0x00: case 0x40: case 0x80: case 0xc0: break; default: return false; } clear = {}; if (code == 0x00) { return true; } switch (format) { case vk::Format::eR8Unorm: case vk::Format::eR8G8Unorm: case vk::Format::eR8G8B8A8Unorm: case vk::Format::eR8G8B8A8Srgb: case vk::Format::eB8G8R8A8Unorm: case vk::Format::eB8G8R8A8Srgb: case vk::Format::eA2B10G10R10UnormPack32: case vk::Format::eA2R10G10B10UnormPack32: case vk::Format::eR5G6B5UnormPack16: case vk::Format::eA1R5G5B5UnormPack16: case vk::Format::eR4G4B4A4UnormPack16: case vk::Format::eR16Unorm: case vk::Format::eR16G16Unorm: case vk::Format::eR16G16B16A16Unorm: case vk::Format::eR16Sfloat: case vk::Format::eR16G16Sfloat: case vk::Format::eR16G16B16A16Sfloat: case vk::Format::eR32Sfloat: case vk::Format::eR32G32Sfloat: case vk::Format::eR32G32B32A32Sfloat: case vk::Format::eB10G11R11UfloatPack32: break; default: return false; } const float rgb = (code & 0x80u) != 0 ? 1.0f : 0.0f; const float alpha = (code & 0x40u) != 0 ? 1.0f : 0.0f; std::array channels {rgb, rgb, rgb, alpha}; if (!metadata.dcc_alpha_msb) { std::swap(channels[0], channels[3]); } // DCC clear decoding clamps missing lanes before applying the format swizzle. const auto components = vk::componentCount(format); if (components == 1) { channels[0] = channels[3]; } else if (components == 2) { channels[1] = channels[3]; } switch (format) { case vk::Format::eB8G8R8A8Unorm: case vk::Format::eB8G8R8A8Srgb: case vk::Format::eA2R10G10B10UnormPack32: case vk::Format::eA1R5G5B5UnormPack16: case vk::Format::eR5G6B5UnormPack16: std::swap(channels[0], channels[2]); break; case vk::Format::eR4G4B4A4UnormPack16: std::reverse(channels.begin(), channels.end()); break; default: break; } clear.float32 = channels; return true; } // True when a front-to-back write reaches a byte of the image the way its faults would. // A front-to-back CPU write faults at its first byte on each watched page, so it reaches an // image only when it starts inside the image or crosses a page boundary inside it. A write that // ends inside the image's first page faulted only before the image, which leaves the image // untracked on that page but not CPU dirty, so its GPU-written contents are not re-uploaded. bool SequentialWriteReachesImage(const Image& image, uint64_t address, uint64_t size) { const auto begin = image.info.data.address; const auto end = image.info.data.End(); if (address >= begin) { return address < end; } const auto first_boundary = Common::AlignUp(begin, TRACKER_PAGE_SIZE); return first_boundary < end && first_boundary < address + size; } // Bit key is set when code key << ColorClearKeyShift selects a clear. The check kernel reports // one bit per key because every accepted code has its low ColorClearKeyShift bits clear. uint32_t ColorClearKeys(const TextureCache::ImageDesc& desc) { uint32_t keys = 0; vk::ClearColorValue unused {}; for (uint32_t key = 0; key < TileManager::ColorClearSlots; key++) { if (DecodeColorClear(desc, static_cast(key << ColorClearKeyShift), unused)) { keys |= 1u << key; } } return keys; } namespace { // One clear attachment per key slot, decoded for the conditional clear path only. Slots with no // clear keep a zero value because the predicate never selects them. std::array BuildColorClears(const TextureCache::ImageDesc& desc) { std::array clears {}; for (uint32_t key = 0; key < clears.size(); key++) { clears[key].aspectMask = vk::ImageAspectFlagBits::eColor; (void)DecodeColorClear(desc, static_cast(key << ColorClearKeyShift), clears[key].clearValue.color); } return clears; } } // namespace TextureCache::TextureCache(GraphicContext& graphics, CommandScheduler& scheduler, PageManager& page_manager, BufferCache& buffer_cache) : m_graphics(graphics), m_scheduler(scheduler), m_page_manager(page_manager), m_blit_helper(graphics, scheduler), m_tiler(graphics, scheduler, buffer_cache.GetUtilityBuffer(MemoryUsage::Stream)), m_buffer_cache(buffer_cache), m_readback_linear_images(Config::ReadbackLinearImagesEnabled()), m_readback_tiled_images(Config::ReadbackTiledImagesEnabled()), m_readback_storage_images(Config::ReadbackStorageImagesEnabled()), m_partial_buffer_refresh(Config::PartialBufferRefreshEnabled()) { 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)); } } TextureCache::~TextureCache() { m_slot_images.ForEach([&](ImageId id, const Image& image) { if (image.registered) { UnregisterImage(id); } }); } bool TextureCache::SameBacking(const ImageInfo& cached, const ImageInfo& requested, bool exact_format) { if (cached.data.address != requested.data.address) { return false; } if (cached.data.size != requested.data.size) { return false; } if (cached.extent != requested.extent) { return false; } if (cached.resources.levels < requested.resources.levels || cached.resources.layers < requested.resources.layers) { return false; } if (cached.samples != requested.samples) { return false; } if (cached.bytes_per_block != requested.bytes_per_block) { return false; } if (cached.tile_mode != requested.tile_mode) { return false; } if (cached.GetColorTransform() != requested.GetColorTransform()) { return false; } if (!ImageViewOps::FormatsCompatible(cached.pixel_format, requested.pixel_format) || cached.type != requested.type) { return false; } if (exact_format && cached.pixel_format != requested.pixel_format) { return false; } return true; } TextureCache::BindingType TextureCache::UploadBinding(const Image& image) { if (image.info.IsDepth()) { if (image.info.tile_mode == Prospero::TileMode::kDepth || image.info.tile_mode == Prospero::TileMode::kLinear) { return BindingType::DepthTarget; } return BindingType::Texture; } if (image.usage.render_target) { return BindingType::RenderTarget; } if (image.usage.video_out) { return BindingType::VideoOut; } return BindingType::Texture; } ImageId TextureCache::InsertImage(const ImageInfo& info) { const auto id = m_slot_images.insert(m_graphics, m_scheduler, info); RegisterImage(id); return id; } void TextureCache::RegisterImage(ImageId id) { auto& image = m_slot_images[id]; const auto& data = image.info.data; if (image.registered || data.Empty()) { EXIT("TextureCache: invalid image registration\n"); } if (data.size > UINT32_MAX) { EXIT("TextureCache: image larger than 4 GiB\n"); } const BucketEntry entry { .address = data.address, .size = static_cast(data.size), .id = id}; ForEachPage(data.address, data.size, [this, &entry](uint64_t page) { m_image_page_table[page].entries.push_back(entry); }); image.registered = true; image.lru_id = m_lru_cache.Insert(id, m_gc_tick); m_total_used_memory += image.AccountedSize(); } void TextureCache::UnregisterImage(ImageId id) { auto& image = m_slot_images[id]; image.HeapChanged(); UntrackImage(id); ForEachPage(image.info.data.address, image.info.data.size, [this, id](uint64_t page) { auto* bucket = m_image_page_table.Find(page); if (bucket == nullptr) { EXIT("TextureCache: image missing from page owner index\n"); } auto& entries = bucket->entries; const auto entry = std::ranges::find(entries, id, &BucketEntry::id); if (entry == entries.end()) { EXIT("TextureCache: image missing from page owner index\n"); } entries.erase(entry); }); m_lru_cache.Free(image.lru_id); m_total_used_memory -= image.AccountedSize(); image.registered = false; } void TextureCache::DeleteImage(ImageId id) { auto& image = m_slot_images[id]; if (!image.registered) { return; } if (image.depth_id) { std::erase(m_slot_images[image.depth_id].stencil_ids, id); } else { // Detach first: deleting each association also unlinks it from its depth owner. for (const auto association: std::exchange(image.stencil_ids, {})) { FreeImage(association); } } m_download_images.erase(id); ReleaseHtileOwner(id, image.info.metadata); if (image.info.IsDepth() && !image.depth_id) { // HTile clear state belongs to the guest depth surface, not to one native image: UFC 6 // alternates D32 and D32S8 bindings with separate HTiles and clears each while the other // is bound. Keep the state while another HTile depth image of the surface remains; a // non-depth replacement still drops it. Entries another surface rebound are its own. const auto surface = image.info.data.address; bool retained = false; ForEachImageInRegion(surface, image.info.data.size, [&](ImageId other, Image& owner) { retained |= other != id && owner.registered && !owner.depth_id && owner.info.IsDepth() && owner.info.metadata.kind == ImageMetadataKind::Htile && owner.info.data.address == surface; }); if (!retained) { std::erase_if(m_surface_metas, [&](const auto& metadata) { return metadata.second.depth_address == surface; }); } } UnregisterImage(id); if (m_scheduler.Active()) { m_scheduler.DeferRelease([this, id] { m_slot_images.erase(id); }); } else { m_slot_images.erase(id); } } void TextureCache::ReleaseHtileOwner(ImageId id, const ImageMetadataInfo& released) { if (released.kind != ImageMetadataKind::Htile) { return; } const auto metadata = m_surface_metas.find(released.range.address); if (metadata == m_surface_metas.end() || metadata->second.owner != id) { return; } ImageId heir; m_slot_images.ForEach([&](ImageId other, const Image& candidate) { if (other != id && candidate.registered && candidate.info.metadata.kind == ImageMetadataKind::Htile && candidate.info.metadata.range.address == metadata->first) { heir = other; } }); if (heir) { metadata->second.owner = heir; } else { m_surface_metas.erase(metadata); } } void TextureCache::FreeImage(ImageId id) { m_slot_images[id].ClearGpuModified(); DeleteImage(id); } void TextureCache::TouchImage(Image& image) { if (image.registered) { m_lru_cache.Touch(image.lru_id, m_gc_tick); } } void TextureCache::MarkAsMaybeDirty(ImageId id, Image& image) { image.MarkMaybeCpuDirty(); UntrackImage(id); } void TextureCache::TrackImage(ImageId id) { auto& image = m_slot_images[id]; if (!image.registered) { return; } const auto image_begin = image.info.data.address; const auto image_end = image.info.data.End(); if (image_begin == image.track_addr && image_end == image.track_addr_end) { return; } if (!image.IsTracked()) { image.track_addr = image_begin; image.track_addr_end = image_end; m_page_manager.UpdatePageWatchers(image_begin, image.info.data.size); return; } if (image_begin < image.track_addr) { TrackImageHead(id); } if (image.track_addr_end < image_end) { TrackImageTail(id); } } void TextureCache::TrackImageHead(ImageId id) { auto& image = m_slot_images[id]; if (!image.registered) { return; } const auto image_begin = image.info.data.address; if (image_begin == image.track_addr) { return; } if (!image.IsTracked() || image_begin > image.track_addr) { EXIT("TextureCache: invalid image head tracking range\n"); } const auto size = image.track_addr - image_begin; image.track_addr = image_begin; m_page_manager.UpdatePageWatchers(image_begin, size); } void TextureCache::TrackImageTail(ImageId id) { auto& image = m_slot_images[id]; if (!image.registered) { return; } const auto image_end = image.info.data.End(); if (image_end == image.track_addr_end) { return; } if (!image.IsTracked() || image.track_addr_end > image_end) { EXIT("TextureCache: invalid image tail tracking range\n"); } const auto address = image.track_addr_end; const auto size = image_end - address; image.track_addr_end = image_end; m_page_manager.UpdatePageWatchers(address, size); } void TextureCache::UntrackImage(ImageId id) { auto& image = m_slot_images[id]; if (!image.IsTracked()) { return; } const auto address = image.track_addr; const auto size = image.track_addr_end - image.track_addr; image.track_addr = 0; image.track_addr_end = 0; if (size != 0) { m_page_manager.UpdatePageWatchers(address, size); } } void TextureCache::UntrackImageHead(ImageId id) { auto& image = m_slot_images[id]; const auto begin = image.info.data.address; if (!image.IsTracked() || begin < image.track_addr) { return; } const auto address = Common::AlignDown(begin + TRACKER_PAGE_SIZE, TRACKER_PAGE_SIZE); const auto size = address - begin; image.track_addr = address; image.HeapChanged(); if (image.track_addr == image.track_addr_end) { MarkAsMaybeDirty(id, image); } if (size != 0) { m_page_manager.UpdatePageWatchers(begin, size); } } void TextureCache::UntrackImageTail(ImageId id) { auto& image = m_slot_images[id]; const auto end = image.info.data.End(); if (!image.IsTracked() || image.track_addr_end < end) { return; } const auto address = Common::AlignDown(end, TRACKER_PAGE_SIZE); const auto size = end - address; image.track_addr_end = address; image.HeapChanged(); if (image.track_addr == image.track_addr_end) { MarkAsMaybeDirty(id, image); } if (size != 0) { m_page_manager.UpdatePageWatchers(address, size); } } void TextureCache::TrackImageDownload(ImageId id, Image& image) { // Small tiled targets are written back too: games read GPU results such as reductions and // simulation state from them on the CPU (PPSA04263 keeps the origin of its ocean wave grid // in a 1x1 R32G32 target, and its water physics read it to sample the wave heights). const auto& info = image.info; const auto texels = static_cast(info.extent.width) * info.extent.height * info.extent.depth * info.resources.layers; if (info.IsTiled() ? m_readback_tiled_images && texels <= SmallTiledReadbackTexels : m_readback_linear_images) { m_download_images.insert(id); } } void TextureCache::ValidateImageDesc(const ImageDesc& desc) const { ImageOps::Validate(desc.info); if (desc.view_info.format == vk::Format::eUndefined || desc.view_info.level_count == 0 || desc.view_info.layer_count == 0 || desc.view_info.base_level >= desc.info.resources.levels || desc.view_info.level_count > desc.info.resources.levels - desc.view_info.base_level || (!desc.info.IsVolume() && (desc.view_info.base_layer >= desc.info.resources.layers || desc.view_info.layer_count > desc.info.resources.layers - desc.view_info.base_layer))) { EXIT("TextureCache: invalid image view description\n"); } if (desc.type == BindingType::DepthTarget && !IsSupportedDepthTargetFormat(desc.info)) { EXIT("TextureCache: unsupported depth image description\n"); } if (desc.type == BindingType::VideoOut && !IsSupportedVideoOutFormat(desc.info)) { EXIT("TextureCache: unsupported video-out image description\n"); } if (desc.type == BindingType::VideoOut && desc.info.metadata.compression == VideoOutCompression::Unsupported) { EXIT("TextureCache: unsupported compressed video-out description\n"); } } void TextureCache::RefreshCopySource(ImageId id) { auto& image = m_slot_images[id]; RefreshImage(id); if (image.IsDefinitelyCpuDirty()) { EXIT("TextureCache: image copy source remained CPU-dirty after refresh\n"); } } bool TextureCache::CopyD16(Image& destination, Image& source) { // Converts guest D16 between a four-byte host depth aspect and two-byte color or D16 depth. const bool source_wide = DepthAspectTransferBytes(source.backing.format) == sizeof(uint32_t); if (source_wide == (DepthAspectTransferBytes(destination.backing.format) == sizeof(uint32_t))) { return false; } auto& depth = source_wide ? source : destination; auto& narrow = source_wide ? destination : source; if (depth.info.bytes_per_block != sizeof(uint16_t) || narrow.info.bytes_per_block != sizeof(uint16_t)) { return false; } EXIT_IF(source.backing.samples != 1 || destination.backing.samples != 1 || source.info.resources.levels != 1 || destination.info.resources.levels != 1 || source.info.extent != destination.info.extent || source.info.resources.layers != destination.info.resources.layers); const auto layers = depth.info.resources.layers; const uint64_t depth_slice = static_cast(depth.info.pitch) * depth.info.extent.height * sizeof(uint32_t); const uint64_t narrow_slice = static_cast(narrow.info.pitch) * narrow.info.extent.height * sizeof(uint16_t); EXIT_IF(layers == 0 || depth_slice > UINT64_MAX / layers || narrow_slice > UINT64_MAX / layers); const std::array depth_copies { vk::BufferImageCopy {0, depth.info.pitch, depth.info.extent.height, {vk::ImageAspectFlagBits::eDepth, 0, 0, layers}, {}, depth.info.extent}}; const std::array narrow_copies {vk::BufferImageCopy { 0, narrow.info.pitch, narrow.info.extent.height, {narrow.info.IsDepth() ? vk::ImageAspectFlagBits::eDepth : vk::ImageAspectFlagBits::eColor, 0, 0, layers}, {}, narrow.info.extent}}; auto depth_buffer = m_tiler.GetScratchBuffer(depth_slice * layers); auto narrow_buffer = m_tiler.GetScratchBuffer(narrow_slice * layers, depth_buffer.buffer); const TileManager::D16Layout promote_layout { .width = depth.info.extent.width, .height = depth.info.extent.height, .layers = layers, .source_row_stride = static_cast(narrow.info.pitch) * sizeof(uint16_t), .target_row_stride = static_cast(depth.info.pitch) * sizeof(uint32_t), .source_slice_stride = narrow_slice, .target_slice_stride = depth_slice, }; const bool d32 = DepthAspectTransferFormat(depth.backing.format) == vk::Format::eD32Sfloat; if (source_wide) { source.Download(depth_copies, depth_buffer.buffer, depth_buffer.offset, depth_buffer.size); m_tiler.ConvertD16(depth_buffer, narrow_buffer, TileManager::D16Direction::Demote, d32, {.width = promote_layout.width, .height = promote_layout.height, .layers = promote_layout.layers, .source_row_stride = promote_layout.target_row_stride, .target_row_stride = promote_layout.source_row_stride, .source_slice_stride = promote_layout.target_slice_stride, .target_slice_stride = promote_layout.source_slice_stride}); destination.Upload(narrow_copies, narrow_buffer.buffer, narrow_buffer.offset, narrow_buffer.size); } else { source.Download(narrow_copies, narrow_buffer.buffer, narrow_buffer.offset, narrow_buffer.size); m_tiler.ConvertD16(narrow_buffer, depth_buffer, TileManager::D16Direction::Promote, d32, promote_layout); destination.Upload(depth_copies, depth_buffer.buffer, depth_buffer.offset, depth_buffer.size); } return true; } void TextureCache::CopyImage(ImageId destination_id, ImageId source_id) { RefreshCopySource(source_id); auto& destination = m_slot_images[destination_id]; auto& source = m_slot_images[source_id]; TrackImage(destination_id); if (source.backing.samples != destination.backing.samples) { EXIT("TextureCache: cannot issue an unequal-sample image copy\n"); } destination.RefreshComplete(); if (source.IsBufferModified()) { if (source.info.data == destination.info.data) { // A source range mark is passed on as a whole mark, which is correct but conservative. destination.MarkBufferModified(); } return; } const bool source_depth = source.info.IsDepth(); const bool dest_depth = destination.info.IsDepth(); const bool direct_copy = source.info.GetColorTransform() == destination.info.GetColorTransform() && (source.backing.format == destination.backing.format || (!source_depth && !dest_depth && vk::blockSize(source.backing.format) == vk::blockSize(destination.backing.format))); if (direct_copy) { destination.CopyImage(source); } else if (!CopyD16(destination, source)) { if (source.backing.samples != 1 || destination.backing.samples != 1) { EXIT("TextureCache: cross-format multisample image copy is unsupported\n"); } auto& copy_buffer = m_buffer_cache.GetUtilityBuffer(MemoryUsage::DeviceLocal); destination.CopyImageWithBuffer(source, copy_buffer, m_tiler); } if (source.IsGpuModified()) { destination.MarkGpuModified(); } destination.ClearBufferModified(); } void TextureCache::CopyStencil(ImageId destination_id, ImageId source_id) { auto& source = m_slot_images[source_id]; const auto found = std::ranges::find_if(source.stencil_ids, [&](ImageId id) { return m_slot_images[id].info.data == source.info.stencil; }); // Without a bound stencil plane, guest memory is current. if (found == source.stencil_ids.end()) { return; } const auto source_stencil_id = *found; RefreshImage(source_stencil_id); auto& destination = m_slot_images[destination_id]; destination.stencil_subresources = source.stencil_subresources; const auto stencil_id = AssociateStencil(destination_id, source.info.stencil); // The copy covers only the source extent; the rest comes from guest memory. RefreshImage(stencil_id); destination.CopyImage(source, true); if (m_slot_images[source_stencil_id].IsGpuModified()) { TrackImage(stencil_id); CommitGpuWrite(m_slot_images[stencil_id]); } } void TextureCache::CopyImageMip(ImageId destination_id, ImageId source_id, uint32_t mip, uint32_t layer) { RefreshCopySource(source_id); if (m_slot_images[destination_id].IsBufferModified()) { RefreshImage(destination_id); } auto& destination = m_slot_images[destination_id]; auto& source = m_slot_images[source_id]; TrackImage(destination_id); if (source.IsBufferModified() || source.backing.samples != destination.backing.samples) { EXIT("TextureCache: invalid mip-copy ownership or sample count\n"); } destination.CopyMip(source, mip, layer); if (source.IsGpuModified()) { destination.MarkGpuModified(); } } ImageId TextureCache::ResolveDepthOverlap(const ImageInfo& requested, BindingType binding, ImageId cached_id) { auto& cached = m_slot_images[cached_id]; if ((!cached.info.IsDepth() && !requested.IsDepth()) || cached.info.tile_mode != requested.tile_mode) { return {}; } const bool stencil_match = requested.HasStencil() == cached.info.HasStencil(); const bool bpp_match = requested.bytes_per_block == cached.info.bytes_per_block; // PPSA04264, PPSA04288 // A partial view retains the entire matching array layout. HTile belongs to // the depth source, independently of the data slices copied into color storage. const bool retain_cached_layout = requested.samples == 1 && cached.info.samples == 1 && cached.backing.samples == 1 && requested.bytes_per_block == cached.info.bytes_per_block && requested.data.address == cached.info.data.address && requested.data.size < cached.info.data.size && requested.extent == cached.info.extent && requested.resources.levels == 1 && cached.info.resources.levels == 1 && requested.resources.layers != 0 && cached.info.resources.layers != 0 && requested.resources.layers < cached.info.resources.layers && requested.type == cached.info.type && requested.pitch == cached.info.pitch && requested.mip_layout[0].offset == 0 && cached.info.mip_layout[0].offset == 0 && requested.mip_layout[0].size == requested.data.size && cached.info.mip_layout[0].size == cached.info.data.size && requested.data.size % requested.resources.layers == 0 && cached.info.data.size % cached.info.resources.layers == 0 && requested.data.size / requested.resources.layers == cached.info.data.size / cached.info.resources.layers && !requested.HasStencil() && !cached.info.HasStencil() && !requested.HasMetadata() && (cached.info.metadata.kind == ImageMetadataKind::None || cached.info.metadata.kind == ImageMetadataKind::Htile); // Depth bytes sampled through a color format no depth view provides (16_UINT, 8_8_UNORM) // need a color copy of the whole single-sample depth layout. const bool raw_depth_texture = cached.info.IsDepth() && !requested.IsDepth() && !cached.info.HasStencil() && !requested.HasMetadata() && cached.backing.samples == 1 && requested.samples == 1 && requested.pitch == cached.info.pitch && (requested.resources == cached.info.resources || retain_cached_layout) && !IsSupportedSampledDepthFormat(cached.info.pixel_format, requested.pixel_format); bool recreate = !cached.info.resources.Contains(requested.resources) || requested.IsVolume() != cached.info.IsVolume(); switch (binding) { case BindingType::Texture: recreate |= requested.IsDepth() && !cached.info.IsDepth(); recreate |= raw_depth_texture; break; case BindingType::Storage: recreate |= cached.info.IsDepth(); break; case BindingType::RenderTarget: recreate |= cached.info.IsDepth(); break; case BindingType::DepthTarget: recreate |= !cached.info.IsDepth(); recreate |= cached.info.IsDepth() && !(stencil_match && bpp_match); // PPSA24156: narrow depth targets of different widths share one address and pitch, so // the cached image can be narrower than the render area; drawing past it faults on the // host GPU (NVIDIA: "3D WIDTH ZT Violation"). A target view cannot grow its image. recreate |= requested.extent.width > cached.info.extent.width || requested.extent.height > cached.info.extent.height; break; case BindingType::VideoOut: recreate |= cached.info.IsDepth(); break; } if (!recreate) { return cached_id; } RefreshImage(cached_id); auto info = requested; if (retain_cached_layout) { info.data = cached.info.data; info.resources = cached.info.resources; info.mip_layout = cached.info.mip_layout; info.tiling = cached.info.tiling; info.tiled_slice_stride = cached.info.tiled_slice_stride; info.first_tail_level = cached.info.first_tail_level; } info.htile_initial_clear = false; const auto replacement_id = InsertImage(info); auto& replacement = m_slot_images[replacement_id]; replacement.usage = cached.usage; if (cached.binding.is_bound || cached.binding.is_target) { cached.binding.needs_rebind = true; } if (RetireThroughGuestMemory(replacement_id, cached_id)) { return replacement_id; } if (!cached.info.resources.Contains(info.resources)) { InitializeImage(replacement_id); } if (cached.backing.samples == replacement.backing.samples) { const bool copy_supported = cached.backing.samples == 1 || cached.backing.format == replacement.backing.format || (!cached.info.IsDepth() && !replacement.info.IsDepth() && ImageViewOps::FormatsCompatible(cached.backing.format, replacement.backing.format)); if (copy_supported) { // The copy covers only the cached extent. A larger replacement first loads the guest // bytes, so texels outside the overlap hold guest contents rather than undefined data. if (replacement.info.extent.width > cached.info.extent.width || replacement.info.extent.height > cached.info.extent.height) { InitializeImage(replacement_id); } CopyImage(replacement_id, cached_id); // Draws write stencil into the depth image only; it is lost when the image is freed. if (binding == BindingType::DepthTarget && cached.info.IsDepth() && cached.info.HasStencil() && requested.HasStencil() && requested.stencil == cached.info.stencil && cached.backing.format == replacement.backing.format) { CopyStencil(replacement_id, cached_id); } } else { LOGF_COLOR(Log::Color::BrightYellow, "TextureCache: unsupported cross-format multisample depth copy\n"); } } else if (cached.backing.samples == 1 && replacement.backing.samples > 1 && replacement.info.IsDepth()) { RefreshCopySource(cached_id); if (cached.IsBufferModified() || cached.IsDefinitelyCpuDirty()) { EXIT("TextureCache: multisample depth conversion source is not native-current\n"); } m_blit_helper.ReinterpretColorAsMsDepth(cached, replacement); CommitGpuWrite(replacement); } else { LOGF_COLOR(Log::Color::BrightYellow, "TextureCache: unsupported unequal-sample depth overlap copy (%u -> %u)\n", cached.backing.samples, replacement.backing.samples); } // Deleting the owner of an HTile range erases its clear state. When the replacement uses the // same range, it takes ownership first, so a pending fast clear still reaches its next pass. if (cached.info.metadata.kind == ImageMetadataKind::Htile && replacement.info.metadata.kind == ImageMetadataKind::Htile && replacement.info.metadata.range.address == cached.info.metadata.range.address) { const auto metadata = m_surface_metas.find(cached.info.metadata.range.address); if (metadata != m_surface_metas.end() && metadata->second.owner == cached_id) { metadata->second.owner = replacement_id; } } FreeImage(cached_id); return replacement_id; } namespace BcAlias { bool Matches(const ImageInfo& requested, const ImageInfo& cached) { return requested.guest_format != cached.guest_format && requested.IsBlock() != cached.IsBlock() && requested.tile_mode == cached.tile_mode && requested.bytes_per_block == cached.bytes_per_block && requested.samples == 1 && cached.samples == 1 && (requested.data != cached.data || requested.resources != cached.resources || requested.BlockExtent() != cached.BlockExtent()) && !TextureCache::SameBacking(cached, requested, false); } bool Publish(TextureCache& cache, Image& image) { if (!cache.CanDownload(image)) { return false; } // ObtainBuffer preserves padding and records ownership before the GPU-only transfer. auto [buffer, offset] = cache.m_buffer_cache.ObtainBuffer(image.info.data.address, image.info.data.size, true); cache.DownloadImage(image, *buffer, offset, image.info.data.size, image.info.resources.levels); image.ClearGpuModified(); image.MarkBufferModified(); return true; } void Resolve(TextureCache& cache, ImageId cached_id, ImageId merged_id) { auto& cached = cache.m_slot_images[cached_id]; auto* merged = merged_id ? &cache.m_slot_images[merged_id] : nullptr; // PS5 raw block images can span several packed BC mips. Transfer their complete // guest bytes, including tail padding, before retiring the incompatible backing. if (cached.SafeToDownload()) { if (merged && merged->SafeToDownload() && !Publish(cache, *merged)) { return; } if (!Publish(cache, cached)) { return; } if (merged) { merged->MarkBufferModified(); } } cached.binding.needs_rebind |= cached.binding.is_bound || cached.binding.is_target; cache.FreeImage(cached_id); } } // namespace BcAlias // Frees a cached image that a request with a different guest layout replaces. Its GPU-written // contents are published to the buffer cache first, unless that could overwrite newer data. void TextureCache::RetireReplacedLayout(ImageId cached_id, ImageId merged_id) { auto& cached = m_slot_images[cached_id]; auto* merged = merged_id ? &m_slot_images[merged_id] : nullptr; if (cached.SafeToDownload()) { // The idle replaced image is usually older than merged, so it publishes first and merged // publishes over it. A buffer-modified merged already has newer bytes waiting in the // buffer, and an undownloadable merged couldn't publish over the old ones. const bool merged_wins_overlap = merged == nullptr || (!merged->IsBufferModified() && (!merged->SafeToDownload() || CanDownload(*merged))); if (merged_wins_overlap && BcAlias::Publish(*this, cached)) { if (merged != nullptr) { if (merged->SafeToDownload()) { (void)BcAlias::Publish(*this, *merged); } merged->MarkBufferModified(); } } else { LOGF_COLOR(Log::Color::BrightYellow, "TextureCache: dropping GPU contents of replaced image at 0x%016" PRIx64 ", the replacing image has newer pending bytes or can't be downloaded\n", cached.info.data.address); } } cached.binding.needs_rebind |= cached.binding.is_bound || cached.binding.is_target; FreeImage(cached_id); } bool TextureCache::AccessedLongAgo(const Image& image) const { if (m_scheduler.SubmitCadenceEnabled()) { // The cadence submits many times per frame, so scheduler ticks no longer measure frames. const uint64_t gc_tick = m_gc_tick; return gc_tick - std::min(gc_tick, image.gc_tick_accessed_last) > NumGcTicksBeforeRemoval; } const auto current_tick = m_scheduler.CurrentTick(); return current_tick - std::min(current_tick, image.tick_accessed_last) > NumFramesBeforeRemoval; } TextureCache::OverlapResult TextureCache::ResolveOverlap(const ImageInfo& requested, BindingType binding, ImageId cached_id, ImageId merged_id) { auto& cached = m_slot_images[cached_id]; if (!cached.registered) { return {merged_id}; } // PS5: image heaps keep BC images and raw block views of their layers resident together, so a // raw read of a layer subset with the same levels views the BC image instead of evicting it. const bool raw_view = binding == BindingType::Texture && !requested.IsBlock() && requested.type == cached.info.type && requested.data.address == cached.info.data.address && requested.BlockExtent() == cached.info.BlockExtent() && requested.resources.levels == cached.info.resources.levels && requested.resources.layers < cached.info.resources.layers; if (!raw_view && BcAlias::Matches(requested, cached.info) && !cached.IsCpuDirty()) { BcAlias::Resolve(*this, cached_id, merged_id); return {merged_id}; } const bool safe_to_delete = AccessedLongAgo(cached) && cached.heap_refs.load(std::memory_order_relaxed) == 0u; const uint32_t requested_block = requested.bytes_per_block * requested.samples; const uint32_t cached_block = cached.info.bytes_per_block * cached.info.samples; if (requested.data.address == cached.info.data.address && requested.BlockExtent() == cached.info.BlockExtent() && requested_block == cached_block) { // If any level both layouts have is placed differently, the cached image cannot serve // the request, even when the mip counts differ. const bool shared_levels_differ = requested.resources.levels != cached.info.resources.levels && !SharedLevelsMatch(requested, cached.info); // The depth path may convert the cached image into a new one, which copies its contents // across. Handing back the cached image itself is only right when its levels sit where // the request expects them. if (const auto depth_id = ResolveDepthOverlap(requested, binding, cached_id)) { if (depth_id != cached_id || !shared_levels_differ) { return {depth_id}; } } // Equal pitch does not imply equal mip placement: a changed extent can move // a level into or out of the mip tail. These are separate guest layouts. if (requested.tile_mode != cached.info.tile_mode || (requested.resources == cached.info.resources && !std::equal(requested.mip_layout.begin(), requested.mip_layout.end(), cached.info.mip_layout.begin(), SameMipPlacement)) || shared_levels_differ) { if (safe_to_delete) { RetireReplacedLayout(cached_id, merged_id); } return {merged_id}; } if (requested.GetColorTransform() != cached.info.GetColorTransform()) { return {ExpandImage(requested, cached_id)}; } if (requested.IsBlock() && !cached.info.IsBlock()) { return {ExpandImage(requested, cached_id)}; } // Volume depth is not an array-layer count. A larger depth can retain the // same block-slice layout while requiring a larger native image. if ((requested.IsVolume() || cached.info.IsVolume()) && (requested.data.size == cached.info.data.size || (requested.type == cached.info.type && requested.resources == cached.info.resources && requested.extent.width == cached.info.extent.width && requested.extent.height == cached.info.extent.height && requested.extent.depth > cached.info.extent.depth))) { return {ExpandImage(requested, cached_id)}; } // PPSA08394 // A view cannot change the native image type or grow its extent. if (requested.data.size == cached.info.data.size && requested.resources == cached.info.resources && ImageViewOps::FormatsCompatible(cached.info.pixel_format, requested.pixel_format) && (requested.type != cached.info.type ? requested.extent == cached.info.extent : requested.extent.width > cached.info.extent.width && requested.extent.height >= cached.info.extent.height && requested.extent.depth >= cached.info.extent.depth)) { return {ExpandImage(requested, cached_id)}; } // PS5 mip tails can expose more levels without increasing the guest allocation. if (requested.pixel_format == cached.info.pixel_format && requested.type == cached.info.type && !cached.info.resources.Contains(requested.resources) && (requested.data.size > cached.info.data.size || (requested.data.size == cached.info.data.size && requested.extent == cached.info.extent && cached.info.resources.levels > 1 && requested.resources.layers == cached.info.resources.layers))) { return {ExpandImage(requested, cached_id)}; } if (requested.type != cached.info.type) { return {merged_id}; } if (requested.pixel_format != cached.info.pixel_format || requested.data.size <= cached.info.data.size) { const auto result_id = merged_id ? merged_id : cached_id; return {ImageViewOps::FormatsCompatible(m_slot_images[result_id].info.pixel_format, requested.pixel_format) ? result_id : ImageId {}}; } EXIT("TextureCache: unresolvable equal-address image overlap, address=0x%016" PRIx64 " requested=%ux%u " "cached=%ux%u requested_size=0x%016" PRIx64 " cached_size=0x%016" PRIx64 " type=%u/%u tile=%u/%u\n", requested.data.address, requested.resources.levels, requested.resources.layers, cached.info.resources.levels, cached.info.resources.layers, requested.data.size, cached.info.data.size, static_cast(requested.type), static_cast(cached.info.type), static_cast(requested.tile_mode), static_cast(cached.info.tile_mode)); } const int32_t requested_mip = requested.MipOf(cached.info); if (requested_mip >= 0) { const int32_t layer = requested.SliceOf(cached.info, requested_mip); return {cached_id, requested_mip, layer}; } const int32_t mip = cached.info.MipOf(requested); if (mip >= 0) { const int32_t layer = cached.info.SliceOf(requested, mip); if (!merged_id) { return {ExpandImage(requested, cached_id)}; } cached.binding.needs_rebind |= cached.binding.is_bound || cached.binding.is_target; m_slot_images[merged_id].binding.is_target |= cached.binding.is_target; CopyImageMip(merged_id, cached_id, static_cast(mip), static_cast(layer)); FreeImage(cached_id); return {merged_id}; } if (requested.data.address >= cached.info.data.address && safe_to_delete) { FreeImage(cached_id); } return {merged_id}; } ImageId TextureCache::ExpandImage(const ImageInfo& info, ImageId source_id) { RefreshCopySource(source_id); const auto expanded_id = InsertImage(info); auto& source = m_slot_images[source_id]; if (source.binding.is_bound || source.binding.is_target) { source.binding.needs_rebind = true; } if (RetireThroughGuestMemory(expanded_id, source_id)) { return expanded_id; } InitializeImage(expanded_id); const int32_t mip = source.info.MipOf(info); const int32_t layer = source.info.SliceOf(info, mip); if (layer >= 0) { CopyImageMip(expanded_id, source_id, static_cast(mip), static_cast(layer)); } else { CopyImage(expanded_id, source_id); } FreeImage(source_id); return expanded_id; } bool TextureCache::RetireThroughGuestMemory(ImageId replacement_id, ImageId retired_id) { const auto& replacement = m_slot_images[replacement_id].info; auto& retired = m_slot_images[retired_id]; if (replacement.type != retired.info.type || replacement.resources.Contains(retired.info.resources) || replacement.samples != 1 || replacement.metadata.compression != VideoOutCompression::Uncompressed || !retired.SafeToDownload() || !BcAlias::Publish(*this, retired)) { return false; } InitializeImage(replacement_id); FreeImage(retired_id); return true; } bool TextureCache::CanDownload(const Image& image) const { const auto& info = image.info; if (info.samples != 1 || image.backing.samples != 1 || info.resources.layers == 0 || info.data.size % info.resources.layers != 0) { return false; } if (UploadBinding(image) == BindingType::DepthTarget) { return IsSupportedDepthPlaneReadback(info) && Prospero::NumBytesPerElement(info.guest_format) == info.bytes_per_block; } return info.metadata.compression == VideoOutCompression::Uncompressed && (!info.IsTiled() || !Prospero::IsFmaskTextureFormat(info.guest_format)) && info.LinearSize() != 0; } bool TextureCache::IsValidColorAttachmentUpload(const Image& image, BindingType binding) { if (binding != BindingType::RenderTarget && binding != BindingType::VideoOut) { return true; } const auto& info = image.info; return info.resources.layers != 0 && info.data.size % info.resources.layers == 0 && info.samples == 1 && image.backing.samples == 1; } void TextureCache::UploadImage(Image& image, Buffer& source, uint64_t source_offset) { auto& destination = image.depth_id ? m_slot_images[image.depth_id] : image; const auto& info = image.info; const auto binding = image.depth_id ? BindingType::DepthTarget : UploadBinding(image); if (binding != BindingType::DepthTarget) { if (!IsValidColorAttachmentUpload(image, binding)) { EXIT("TextureCache: invalid color-attachment upload\n"); } const auto linear = m_tiler.Detile(source.Handle(), source_offset, info); const auto copies = info.BufferCopies(linear.offset); destination.Upload(copies, linear.buffer, linear.offset, linear.size); Common::DebugCounters::Add(Common::DebugCounters::Counter::TextureUploadBytes, linear.size); return; } if (destination.backing.samples != 1 || info.resources.layers == 0 || info.data.size % info.resources.layers != 0 || Prospero::NumBytesPerElement(info.guest_format) != info.bytes_per_block) { EXIT("TextureCache: invalid depth upload\n"); } const auto layers = info.resources.layers; const auto full_slice_size = info.LinearLayout().slice_stride; auto linear = m_tiler.Detile(source.Handle(), source_offset, info); auto copies = info.BufferCopies(linear.offset); if (image.depth_id) { for (auto& copy: copies) { copy.imageSubresource.baseArrayLayer += image.stencil_subresources.base_layer; } } const auto transfer_bytes = image.depth_id ? 1u : DepthAspectTransferBytes(info.pixel_format); if (transfer_bytes != info.bytes_per_block) { const uint64_t texels_per_slice = static_cast(info.pitch) * info.extent.height; EXIT_NOT_IMPLEMENTED(info.bytes_per_block != sizeof(uint16_t) || transfer_bytes != sizeof(uint32_t) || texels_per_slice > UINT32_MAX || texels_per_slice > UINT64_MAX / transfer_bytes); const uint64_t transfer_slice = texels_per_slice * transfer_bytes; EXIT_NOT_IMPLEMENTED(transfer_slice > UINT64_MAX / layers); auto promoted = m_tiler.GetScratchBuffer(transfer_slice * layers, linear.buffer); m_tiler.ConvertD16( linear, promoted, TileManager::D16Direction::Promote, info.pixel_format == vk::Format::eD32SfloatS8Uint, {.width = info.extent.width, .height = info.extent.height, .layers = layers, .source_row_stride = static_cast(info.pitch) * sizeof(uint16_t), .target_row_stride = static_cast(info.pitch) * sizeof(uint32_t), .source_slice_stride = full_slice_size, .target_slice_stride = transfer_slice}); linear = promoted; copies.resize(1); copies[0].bufferOffset = linear.offset; copies[0].bufferRowLength = info.pitch; copies[0].bufferImageHeight = info.extent.height; copies[0].imageSubresource = {vk::ImageAspectFlagBits::eDepth, 0, 0, layers}; copies[0].imageExtent = info.extent; } destination.Upload(copies, linear.buffer, linear.offset, linear.size); Common::DebugCounters::Add(Common::DebugCounters::Counter::TextureUploadBytes, linear.size); } // Refreshes an image from only the bytes a buffer wrote into it, keeping the rest of the image // as the GPU left it. gpu_mod stays set, because the image is still newer than the buffer outside // that range. Returns false for anything this path cannot do exactly, so the caller falls back to // the full upload. bool TextureCache::TryPartialRefresh(Image& image) { const auto range = image.BufferModifiedRange(); if (!m_partial_buffer_refresh || !range) { return false; } namespace Counters = Common::DebugCounters; // A hull of several writes can pass the limit that each write alone respected. const bool usable = IsPartialRefreshEligible(image) && !image.IsCpuDirty() && WithinPartialLimit(image, range->size); if (usable && !image.info.IsTiled()) { RefreshLinearRange(image, *range); return true; } if (usable && RefreshTiledRange(image, *range)) { return true; } Counters::Add(Counters::Counter::TexturePartialFallbacks); return false; } // Copies the rounded written range of a linear image from its source buffer, one rectangle per // region from LinearRefreshRegions, and then drops the buffer mark. The image's other texels are // not touched, since Upload transitions from the current layout rather than from undefined. void TextureCache::RefreshLinearRange(Image& image, GuestRange range) { namespace Counters = Common::DebugCounters; const auto& info = image.info; const auto first = range.address - info.data.address; const auto rounded = RoundRefreshRange(info, first, first + range.size); const auto regions = LinearRefreshRegions(info, rounded.lo, rounded.hi); if (!regions.empty()) { const uint64_t size = rounded.hi - rounded.lo; const auto [source, source_offset] = m_buffer_cache.ObtainBufferForImage(info.data.address + rounded.lo, size); if (source == nullptr) { EXIT("TextureCache: failed to obtain partial image upload source\n"); } // The copies address bytes by their offset into the image data, but the buffer starts at // the rounded range, so the base is shifted back by that start. The subtraction can wrap // when source_offset is smaller than rounded.lo. That is fine, because every region starts // at or after rounded.lo and uint64 arithmetic is modular, so each final bufferOffset is // right. Do not clamp it. const auto copies = RegionCopies(info, regions, source_offset - rounded.lo); image.Upload(copies, source->Handle(), source_offset, size); const uint64_t bytes = RegionBytes(info, regions); Counters::Add(Counters::Counter::TexturePartialUploadBytes, bytes); Counters::Add(Counters::Counter::TextureUploadBytes, bytes); } Counters::Add(Counters::Counter::TexturePartialRefreshes); image.ClearBufferModified(); } // Decides what a tiled partial refresh touches, or nothing when the full upload has to run. The // colour attachment checks are the ones UploadImage makes, so an invalid image still reaches them. std::optional TextureCache::PlanTiledRefresh(const Image& image, GuestRange range) { const auto& info = image.info; if (!info.IsTiled() || info.tiling.block.family == TileBlockFamily::Depth64KB || info.data.size > UINT32_MAX || info.LinearSize() > UINT32_MAX || !IsValidColorAttachmentUpload(image, UploadBinding(image))) { return std::nullopt; } const auto first = range.address - info.data.address; TiledRefreshPlan plan; plan.range = RoundRefreshRange(info, first, first + range.size); plan.regions = TiledRefreshRegions(info, plan.range.lo, plan.range.hi); return plan; } // Brings the image's current texels for the touched rectangles into the linear scratch, so the // texels of a touched block that lie outside the written window keep the image's own values. void TextureCache::DownloadForMerge(Image& image, const TileManager::Result& scratch, std::span regions) { image.Download(RegionCopies(image.info, regions, scratch.offset), scratch.buffer, scratch.offset, scratch.size); } // Writes the merged rectangles of the linear scratch back into the image. void TextureCache::UploadMerged(Image& image, const TileManager::Result& scratch, std::span regions) { image.Upload(RegionCopies(image.info, regions, scratch.offset), scratch.buffer, scratch.offset, scratch.size); } // Download, masked detile and upload run in that order on the GPU. Each step's barriers cover the // scratch, and the scratch is never shared with the window source, so nothing reuses it between. void TextureCache::MergeTiledRegions(Image& image, const TiledRefreshPlan& plan) { namespace Counters = Common::DebugCounters; const auto& info = image.info; const auto [source, source_offset] = m_buffer_cache.ObtainBufferForImage( info.data.address + plan.range.lo, plan.range.hi - plan.range.lo); if (source == nullptr) { EXIT("TextureCache: failed to obtain partial image upload source\n"); } const auto scratch = m_tiler.GetScratchBuffer(info.LinearSize(), source->Handle()); DownloadForMerge(image, scratch, plan.regions); m_tiler.DetileRegions({source->Handle(), source_offset, plan.range.lo, plan.range.hi}, info, plan.regions, scratch); UploadMerged(image, scratch, plan.regions); const uint64_t bytes = RegionBytes(info, plan.regions); Counters::Add(Counters::Counter::TexturePartialUploadBytes, bytes); Counters::Add(Counters::Counter::TextureUploadBytes, bytes); } // Refreshes a tiled image from only the blocks its written range touches, then drops the buffer // mark and keeps gpu_mod. Returns false when the plan does not apply. bool TextureCache::RefreshTiledRange(Image& image, GuestRange range) { const auto plan = PlanTiledRefresh(image, range); if (!plan) { return false; } if (!plan->regions.empty()) { MergeTiledRegions(image, *plan); } Common::DebugCounters::Add(Common::DebugCounters::Counter::TexturePartialRefreshes); image.ClearBufferModified(); return true; } void TextureCache::InitializeImage(ImageId id) { auto& image = m_slot_images[id]; TrackImage(id); if (image.info.metadata.compression != VideoOutCompression::Uncompressed) { image.RefreshComplete(); return; } if (image.info.samples > 1) { return; } const bool upload = image.IsBufferModified() || image.IsCpuDirty(); if (upload && !TryPartialRefresh(image)) { if (image.BufferModifiedRange()) { // The upload below is still a full one, so the image must stop counting as newer than // the buffer, as it would after a whole mark. image.ClearGpuModified(); } const auto [source, source_offset] = m_buffer_cache.ObtainBufferForImage(image.info.data.address, image.info.data.size); if (source == nullptr) { EXIT("TextureCache: failed to obtain image upload source\n"); } UploadImage(image, *source, source_offset); image.ClearBufferModified(); } image.RefreshComplete(); } // Whether every viewed metadata slice is already checked for the keys, as one range lookup when // the slices touch. bool TextureCache::IsColorClearChecked(uint64_t address, uint64_t slice_size, uint64_t mip_size, uint32_t count, uint32_t keys) const { // Touching checked ranges merge, so one range lookup equals checking every slice. if (ColorClearSlicesContiguous(mip_size, slice_size, count)) { return m_buffer_cache.IsColorMetadataChecked(address, slice_size * count, keys); } for (uint32_t slice = 0; slice < count; slice++) { if (!m_buffer_cache.IsColorMetadataChecked(address + slice_size * slice, mip_size, keys)) { return false; } } return true; } // Marks every viewed metadata slice checked for the keys, as one range when the slices touch. void TextureCache::MarkColorClearChecked(uint64_t address, uint64_t slice_size, uint64_t mip_size, uint32_t count, uint32_t keys) { if (ColorClearSlicesContiguous(mip_size, slice_size, count)) { m_buffer_cache.MarkColorMetadataChecked(address, slice_size * count, keys); return; } for (uint32_t slice = 0; slice < count; slice++) { m_buffer_cache.MarkColorMetadataChecked(address + slice_size * slice, mip_size, keys); } } void TextureCache::MaterializeColorClear(ImageId id, const ImageDesc& desc, uint32_t metadata_base_layer) { if (desc.info.metadata.kind != ImageMetadataKind::Dcc && desc.info.metadata.kind != ImageMetadataKind::Cmask) { return; } const auto range = desc.info.metadata.range; const auto& view = desc.view_info; { std::scoped_lock lock {m_lock}; auto& image = m_slot_images[id]; image.info.metadata = desc.info.metadata; // Native color metadata must not retain a reused HTile clear flag. m_surface_metas.erase(range.address); if (range.size == 0 || view.level_count != 1) { return; } } const auto layers = desc.info.TransferLayers(); // Color metadata slices consist of complete 4 KiB blocks. constexpr uint64_t MetadataBlockSize = 0x1000; if (!range.Valid() || range.address % MetadataBlockSize != 0 || layers == 0 || range.size % layers != 0 || (range.size / layers) % MetadataBlockSize != 0) { EXIT("TextureCache: color metadata slices must contain aligned 4 KiB blocks\n"); } const bool volume_texture = desc.info.IsVolume() && view.type == vk::ImageViewType::e3D; const auto first = volume_texture ? 0u : metadata_base_layer; const auto image_first = volume_texture ? 0u : view.base_layer; const auto count = volume_texture ? std::max(desc.info.extent.depth >> view.base_level, 1u) : view.layer_count; if (first >= layers || count > layers - first) { EXIT("TextureCache: color view exceeds its native metadata slices\n"); } const auto slice_size = range.size / layers; // Each slice holds the viewed mip's metadata in one run; DCC mips past the first tail mip // have none. FindImage moves base_level only for one-mip descriptors, which keep the slice. TileSizeOffset mip {.size = static_cast(slice_size)}; if (desc.info.metadata.kind == ImageMetadataKind::Dcc && desc.info.resources.levels > 1) { std::array mips {}; TileSizeAlign total {}; (void)TileGetDccSize(desc.info.extent.width, desc.info.extent.height, layers, desc.info.bytes_per_block, desc.info.resources.levels, desc.info.tile_mode, total, 0, mips.data()); mip = mips[view.base_level]; } if (mip.size == 0) { return; } const GuestRange viewed {range.address + slice_size * first + mip.offset, slice_size * (count - 1) + mip.size}; const auto run = [&](uint32_t slice) { return viewed.address + slice_size * slice; }; if (m_buffer_cache.IsRegionGpuModified(viewed.address, viewed.size)) { const auto keys = ColorClearKeys(desc); // No selected key to clear, or none left since the last check. if (IsColorClearChecked(viewed.address, slice_size, mip.size, count, keys)) { return; } { std::scoped_lock lock {m_lock}; auto& image = m_slot_images[id]; // Compressed images cannot upload, so they must already hold native contents. const bool native_current = (image.usage.render_target || image.IsGpuModified()) && !image.IsBufferModified() && !image.IsCpuDirty(); // 2D-array attachment views select 2D layers or, of a volume, depth slices. if (m_graphics.conditional_rendering_enabled && count <= m_graphics.GetPhysicalDeviceProperties().limits.maxFramebufferLayers && (image.backing.usage & vk::ImageUsageFlagBits::eColorAttachment) && (m_graphics.GetFormatProperties(view.format).optimalTilingFeatures & vk::FormatFeatureFlagBits::eColorAttachment) && (desc.info.metadata.compression == VideoOutCompression::Uncompressed || native_current)) { // The GPU selects each slice's clear, so the CPU never waits for the metadata. Common::DebugCounters::Add(Common::DebugCounters::Counter::ColorMetadataChecks); InitializeImage(id); const bool expand = desc.type != BindingType::VideoOut; const auto [buffer, offset] = m_buffer_cache.ObtainBuffer(viewed.address, viewed.size, expand); const auto predicates = m_tiler.CheckColorClear( {buffer->Handle(), offset, viewed.size}, slice_size, count, keys, expand); if (expand) { MarkColorClearChecked(viewed.address, slice_size, mip.size, count, keys); } const auto clears = BuildColorClears(desc); const auto command = m_scheduler.Current().Handle(); const auto area = BeginColorRendering(image, view.format, view.base_level, image_first, count, nullptr, command); vk::ClearRect rect {.rect = area, .layerCount = 1}; for (uint32_t slice = 0; slice < count; slice++) { rect.baseArrayLayer = slice; for (uint32_t key = 0; key < clears.size(); key++) { if ((keys & (1u << key)) != 0) { const vk::ConditionalRenderingBeginInfoEXT predicate { .buffer = predicates, .offset = (slice * clears.size() + key) * sizeof(uint32_t)}; command.beginConditionalRenderingEXT(&predicate); command.clearAttachments(1, &clears[key], 1, &rect); command.endConditionalRenderingEXT(); } } } command.endRendering(); CommitGpuWrite(image); return; } } // Finish native metadata writes before reading backing bytes. This can submit the // scheduler, so discovery runs before final draw uploads and never holds the texture // lock across it. Common::DebugCounters::ScopedTimer timer( Common::DebugCounters::Counter::ColorMetadataReadbacks, Common::DebugCounters::Counter::ColorMetadataReadbackNs); m_buffer_cache.ReadMemory(viewed.address, viewed.size, false); } const ColorClearCodes codes(run(0), slice_size, count); for (uint32_t slice = 0; slice < count; slice++) { const auto address = run(slice); const auto code = codes[slice]; if ((code & ColorClearCodeLowBits) != 0) { continue; } vk::ClearValue clear {}; if (!DecodeColorClear(desc, code, clear.color)) { continue; } std::vector bytes(mip.size); if (!LibKernel::Memory::TryReadBacking(address, bytes.data(), bytes.size())) { EXIT("TextureCache: failed to read color metadata slice\n"); } if (!std::all_of(bytes.begin(), bytes.end(), [code](uint8_t byte) { return byte == code; })) { continue; } { std::scoped_lock lock {m_lock}; const auto& image = m_slot_images[id]; const bool depth = image.info.IsDepth(); if (depth) { const auto value = clear.color.float32[0]; clear.depthStencil = {value, 0u}; } ClearImage(m_scheduler.Current(), id, depth ? image.backing.format : view.format, {depth ? vk::ImageAspectFlagBits::eDepth : vk::ImageAspectFlagBits::eColor, view.base_level, view.level_count, image_first + slice, 1}, clear); } // Publish the conversion's expanded keys without treating them as guest writes // to overlapping image data. Invalidate the buffer before updating its backing. if (desc.type != BindingType::VideoOut) { std::fill(bytes.begin(), bytes.end(), uint8_t {0xff}); m_buffer_cache.InvalidateMemory(address, bytes.size()); LibKernel::Memory::WriteBacking(address, bytes.data(), bytes.size()); } } } void TextureCache::RefreshImage(ImageId id) { auto& image = m_slot_images[id]; if ((image.depth_id && (m_slot_images[image.depth_id].info.metadata.stencil_compressed || m_slot_images[image.depth_id].info.samples != 1)) || (image.info.pixel_format == vk::Format::eS8Uint && image.info.metadata.stencil_compressed)) { return; } TrackImage(id); if (image.IsMaybeCpuDirty()) { image.ResolveMaybeCpuHash(image.HashGuestEdges()); } bool cpu_dirty = image.IsBufferModified() || image.IsDefinitelyCpuDirty(); if (image.info.metadata.compression != VideoOutCompression::Uncompressed) { if (cpu_dirty) { EXIT("TextureCache: compressed guest image refresh is unsupported\n"); } return; } if (!cpu_dirty) { return; } InitializeImage(id); } ImageId TextureCache::FindStencilPlane(const Image& depth, GuestRange range) const { for (const auto id: depth.stencil_ids) { if (m_slot_images[id].info.data == range) { return id; } } return {}; } ImageId TextureCache::AssociateStencil(ImageId depth_id, GuestRange stencil) { if (!stencil.Valid()) { EXIT("TextureCache: invalid stencil association range\n"); } auto& depth = m_slot_images[depth_id]; if (!depth.info.IsDepth() || !depth.info.HasStencil()) { EXIT("TextureCache: stencil association requires a depth/stencil image\n"); } ImageId association = FindStencilPlane(depth, stencil); if (!association) { ForEachImageWithAddress(stencil.address, [&](ImageId id, Image& owner) { // Small depth and stencil planes are one 64 KiB block each, so another depth surface // can occupy this exact range. Adopting it would orphan its own stencil associations. if (!owner.info.IsDepth() && owner.info.data == stencil && owner.info.extent == depth.info.extent) { association = id; } }); } if (!association) { ImageInfo info {}; info.data = stencil; info.extent = depth.info.extent; association = InsertImage(info); } auto& record = m_slot_images[association]; TouchImage(record); if (record.depth_id != depth_id || record.stencil_subresources != depth.stencil_subresources) { ImageInfo plane {}; plane.data = stencil; plane.pixel_format = vk::Format::eS8Uint; plane.guest_format = Prospero::BufferFormat::k8UInt; plane.type = depth.info.type; plane.extent = depth.info.extent; plane.resources = {depth.stencil_subresources.level_count, depth.stencil_subresources.layer_count}; plane.tile_mode = depth.info.tile_mode; plane.pitch = plane.IsTiled() ? TileGetRenderTargetPitch(plane.extent.width, 1) : depth.info.pitch; plane.bytes_per_block = 1; plane.UpdateSize(); if (record.depth_id != depth_id) { if (record.depth_id) { std::erase(m_slot_images[record.depth_id].stencil_ids, association); } depth.stencil_ids.push_back(association); } ReleaseHtileOwner(association, record.info.metadata); // A resident image heap may sample the adopted image, for example an R8 texture at // the stencil range. Its references still belong to that image, so queue the change. record.HeapChanged(); record.info = plane; record.depth_id = depth_id; record.stencil_subresources = depth.stencil_subresources; } return association; } ImageId TextureCache::FindImage(ImageDesc& desc, bool exact_format) { ValidateImageDesc(desc); EXIT_IF(desc.info.data.Empty()); const auto metadata_base_layer = desc.view_info.base_layer; ImageId result {}; { std::scoped_lock lock {m_lock}; Common::SmallVector candidates; ForEachImageInRegion(desc.info.data.address, desc.info.data.size, [&](ImageId id, Image&) { candidates.push_back(id); }); bool block_alias = false; for (const auto id: candidates) { const auto& image = m_slot_images[id]; // Stencil descriptors name the associated plane; its depth owner supplies // the native image and the canonical guest tiling. if ((desc.type == BindingType::Texture || desc.type == BindingType::Storage) && image.depth_id && image.info.data == desc.info.data && m_slot_images[image.depth_id].info.samples == desc.info.samples && image.info.extent == desc.info.extent && image.info.type == desc.info.type && image.info.resources.levels >= desc.info.resources.levels && image.info.resources.layers >= desc.info.resources.layers && desc.info.bytes_per_block == 1 && desc.info.guest_format == Prospero::BufferFormat::k8UInt) { result = id; break; } // Equal size and a longer chain are not enough: the levels the request uses must sit // where the cached image keeps them. if (SameBacking(image.info, desc.info, exact_format) && (image.info.resources.levels == desc.info.resources.levels || SharedLevelsMatch(image.info, desc.info))) { result = id; } else if (image.SafeToDownload() && BcAlias::Matches(desc.info, image.info)) { block_alias = true; } } int32_t view_mip = -1; int32_t view_layer = -1; if (!result) { for (const auto candidate: candidates) { view_mip = -1; view_layer = -1; const auto& merged_info = result ? m_slot_images[result].info : desc.info; const auto overlap = ResolveOverlap(merged_info, desc.type, candidate, result); if (overlap.image) { result = overlap.image; view_mip = overlap.mip; view_layer = overlap.layer; } } // PS5: image heaps hold a descriptor per dynamic-resolution extent of a render target, // and only one extent at an address holds data, so heap lookups create no second one. if (!result && desc.heap && std::any_of(candidates.begin(), candidates.end(), [&](ImageId id) { const auto* image = m_slot_images.try_get(id); return image != nullptr && image->registered && image->heap_refs.load(std::memory_order_relaxed) != 0u && image->info.data.address == desc.info.data.address && image->info.type == desc.info.type && image->info.extent != desc.info.extent; })) { return {}; } } else if (block_alias) { for (const auto candidate: candidates) { const auto& owner = m_slot_images[candidate]; if (candidate != result && owner.registered && !owner.IsCpuDirty() && BcAlias::Matches(m_slot_images[result].info, owner.info)) { BcAlias::Resolve(*this, candidate, result); } } } if (result && !m_slot_images[result].depth_id) { auto& resolved = m_slot_images[result]; if (exact_format && resolved.info.pixel_format != desc.info.pixel_format) { result = {}; } else if (!resolved.info.resources.Contains(desc.info.resources)) { if (CanDownload(resolved)) { RefreshImage(result); if (resolved.SafeToDownload()) { (void)BcAlias::Publish(*this, resolved); } } FreeImage(result); result = {}; } } if (!result) { result = InsertImage(desc.info); auto& inserted = m_slot_images[result]; if (m_buffer_cache.HasGpuDirtyBytes(inserted.info.data.address, inserted.info.data.size)) { inserted.MarkBufferModified(); } } auto& image = m_slot_images[result]; if (view_mip >= 0) { desc.view_info.base_level = static_cast(view_mip); } if (view_layer >= 0) { desc.view_info.base_layer = static_cast(view_layer); } image.tick_accessed_last = m_scheduler.CurrentTick(); image.gc_tick_accessed_last = m_gc_tick; TouchImage(image); } MaterializeColorClear(result, desc, metadata_base_layer); if (desc.type == BindingType::VideoOut && desc.info.metadata.compression != VideoOutCompression::Uncompressed) { std::scoped_lock lock {m_lock}; const auto& image = m_slot_images[result]; const bool guest_dirty = image.IsBufferModified() || image.IsCpuDirty(); const bool native_current = (image.usage.render_target || image.IsGpuModified()) && !guest_dirty; if (!native_current) { EXIT("TextureCache: compressed video-out read requires clean native GPU " "contents\n"); } } return result; } void TextureCache::UpdateImage(ImageId id) { std::scoped_lock lock {m_lock}; auto& image = m_slot_images[id]; TouchImage(image); RefreshImage(id); } ImageId TextureCache::FindImageFromRange(uint64_t address, uint64_t size, bool ensure_valid) { std::scoped_lock lock {m_lock}; Common::SmallVector matches; ForEachImageWithAddress(address, [&](ImageId id, Image& image) { const auto* owner = ℑ if (ensure_valid && owner->depth_id) { owner = &m_slot_images[owner->depth_id]; } if (ensure_valid && !owner->SafeToDownload()) { return; } matches.push_back(id); }); ImageId selected {}; if (matches.size() == 1) { selected = matches.front(); } else { for (const auto id: matches) { const auto& image = m_slot_images[id]; if (image.info.data.size == size) { selected = id; break; } } } if (selected && ensure_valid && m_slot_images[selected].depth_id) { selected = m_slot_images[selected].depth_id; } return selected; } vk::ImageView TextureCache::FindTexture(ImageId id, const ImageDesc& desc) { std::scoped_lock lock {m_lock}; auto& image = m_slot_images[id]; TouchImage(image); if (!image.registered || image.depth_id || image.binding.needs_rebind) { EXIT("TextureCache: texture requires rediscovery before final acquisition\n"); } // Storage readback also queues the first GPU write since the CPU last wrote the image: an // image rewritten every frame would otherwise be downloaded at every GL2 writeback. GPU data // in the buffer cache over the whole image is not a CPU write. Read before RefreshImage // uploads the CPU write. const bool first_write = m_readback_storage_images && (!image.IsGpuModified() || image.IsDefinitelyCpuDirty()) && !m_buffer_cache.HasOnlyGpuDirtyBytes(image.info.data.address, image.info.data.size); RefreshImage(id); if (image.info.HasStencil() && desc.info.data.address >= image.info.stencil.address && desc.info.data.End() <= image.info.stencil.End()) { if (const auto stencil_id = FindStencilPlane(image, image.info.stencil)) { RefreshImage(stencil_id); } } switch (desc.type) { case BindingType::Texture: break; case BindingType::Storage: CommitGpuWrite(image); TrackImageDownload(id, image); if (first_write) { m_download_images.insert(id); } break; default: EXIT("TextureCache: invalid texture binding\n"); } return image.FindView(desc.view_info); } vk::ImageView TextureCache::FindRenderTarget(ImageId id, const ImageDesc& desc) { std::scoped_lock lock {m_lock}; auto& image = m_slot_images[id]; if (!image.registered || image.depth_id || image.binding.needs_rebind) { EXIT("TextureCache: color target requires rediscovery before final acquisition\n"); } TouchImage(image); image.usage.render_target = true; RefreshImage(id); CommitGpuWrite(image); TrackImageDownload(id, image); return image.FindView(desc.view_info); } vk::ImageView TextureCache::FindDepthTarget(ImageId id, const ImageDesc& desc) { std::scoped_lock lock {m_lock}; auto& image = m_slot_images[id]; if (!image.registered || image.depth_id || image.binding.needs_rebind) { EXIT("TextureCache: depth target requires rediscovery before final acquisition\n"); } TouchImage(image); if (desc.info.HasStencil()) { const auto layers = image.info.resources.layers; EXIT_IF(layers == 0 || image.info.data.size % layers != 0 || desc.info.data.address < image.info.data.address); const auto slice_size = image.info.data.size / layers; const auto offset = desc.info.data.address - image.info.data.address; EXIT_IF(slice_size == 0 || offset % slice_size != 0 || offset / slice_size >= layers || desc.info.resources.layers > layers - offset / slice_size); image.stencil_subresources = {0, desc.info.resources.levels, static_cast(offset / slice_size), desc.info.resources.layers}; } image.info.stencil = desc.info.stencil; if (image.info.metadata.range.address != desc.info.metadata.range.address) { ReleaseHtileOwner(id, image.info.metadata); } image.info.metadata = desc.info.metadata; if (desc.info.HasMetadata()) { const auto [metadata, inserted] = m_surface_metas.try_emplace(desc.info.metadata.range.address); if (inserted || metadata->second.depth_address != image.info.data.address) { metadata->second.clear_mask.reset(); metadata->second.stencil_clear_mask.reset(); if (image.info.htile_initial_clear) { metadata->second.clear_mask.set(); metadata->second.stencil_clear_mask.set(); } metadata->second.depth_address = image.info.data.address; } metadata->second.owner = id; } RefreshImage(id); CommitGpuWrite(image); if (desc.info.HasStencil()) { RefreshImage(AssociateStencil(id, desc.info.stencil)); } return image.FindView(desc.view_info); } void TextureCache::MarkGpuWritten(ImageId id) { std::scoped_lock lock {m_lock}; auto& image = m_slot_images[id]; if (!image.registered || image.depth_id) { EXIT("TextureCache: cannot mark an unavailable image GPU-written\n"); } TrackImage(id); CommitGpuWrite(image); if (image.info.HasStencil()) { const auto stencil_id = AssociateStencil(id, image.info.stencil); TrackImage(stencil_id); CommitGpuWrite(m_slot_images[stencil_id]); } } void TextureCache::CommitGpuWrite(Image& image) { if (!image.depth_id && image.backing.image == nullptr) { EXIT("TextureCache: GPU writes require a native image or stencil association\n"); } m_buffer_cache.SupersedePublishes(image.info.data.address, image.info.data.size); image.ClearBufferModified(); image.RefreshComplete(); image.MarkGpuModified(); } bool TextureCache::ClearImageFromBuffer(CommandBuffer& command, uint64_t address, uint64_t size, uint32_t packed_clear) { if (command.IsInvalid() || !GuestRange {address, size}.Valid()) { EXIT("TextureCache: invalid image clear\n"); } std::scoped_lock lock {m_lock}; ImageId selected {}; ImageId stencil_id {}; vk::ImageAspectFlags aspect {}; ImageSubresourceRange subresources; Common::SmallVector image_ids; ForEachImageInRegion(address, size, [&](ImageId id, Image&) { image_ids.push_back(id); }); for (const auto id: image_ids) { const auto& owner = m_slot_images[id]; vk::ImageAspectFlags candidate {}; ImageId candidate_id = id; ImageSubresourceRange candidate_subresources {0, owner.info.resources.levels, 0, owner.info.TransferLayers()}; if (owner.depth_id && owner.info.data.address == address && owner.info.data.size == size) { candidate = vk::ImageAspectFlagBits::eStencil; candidate_id = owner.depth_id; candidate_subresources = owner.stencil_subresources; const auto& depth = m_slot_images[candidate_id]; if (depth.backing.image == nullptr || !depth.info.HasStencil()) { continue; } } else if (!owner.depth_id && owner.info.data.address == address && owner.info.data.size == size) { candidate = owner.info.IsDepth() ? vk::ImageAspectFlagBits::eDepth : vk::ImageAspectFlagBits::eColor; } if (!candidate) { continue; } if (selected && (selected != candidate_id || subresources != candidate_subresources)) { return false; } selected = candidate_id; stencil_id = candidate == vk::ImageAspectFlagBits::eStencil ? id : ImageId {}; aspect = candidate; subresources = candidate_subresources; } if (!selected) { return false; } auto& image = m_slot_images[selected]; vk::ClearValue clear {}; if (aspect == vk::ImageAspectFlagBits::eColor) { if (!DecodeColorDwordFill(image.info.pixel_format, packed_clear, clear.color)) { return false; } } else { uint8_t stencil_clear = 0; if ((aspect == vk::ImageAspectFlagBits::eDepth && !DecodePackedDepthClear(image.info.pixel_format, packed_clear, clear.depthStencil.depth)) || (aspect == vk::ImageAspectFlagBits::eStencil && !DecodePackedStencilClear(packed_clear, stencil_clear))) { return false; } clear.depthStencil.stencil = stencil_clear; } ClearImage(command, selected, image.backing.format, {aspect, subresources.base_level, subresources.level_count, subresources.base_layer, subresources.layer_count}, clear); if (stencil_id) { TrackImage(stencil_id); CommitGpuWrite(m_slot_images[stencil_id]); } return true; } void TextureCache::ClearImage(CommandBuffer& command, ImageId id, vk::Format format, const vk::ImageSubresourceRange& range, const vk::ClearValue& clear) { auto& image = m_slot_images[id]; const auto aspects = image.info.IsDepth() ? ImageViewOps::DepthAspectMask(image.backing.format) : vk::ImageAspectFlagBits::eColor; EXIT_IF(range.baseMipLevel >= image.info.resources.levels); const auto layers = image.info.IsVolume() ? std::max(image.info.extent.depth >> range.baseMipLevel, 1u) : image.backing.layers; EXIT_IF(command.IsInvalid() || image.depth_id || !range.aspectMask || range.levelCount == 0 || range.levelCount > image.info.resources.levels - range.baseMipLevel || range.layerCount == 0 || range.baseArrayLayer >= layers || range.layerCount > layers - range.baseArrayLayer || (range.aspectMask & aspects) != range.aspectMask); const bool full_subresources = range.baseMipLevel == 0 && range.levelCount == image.info.resources.levels && range.baseArrayLayer == 0 && range.layerCount == layers; const bool full_image = range.aspectMask == aspects && full_subresources; TrackImage(id); if (!full_image && (image.IsBufferModified() || image.IsCpuDirty())) { InitializeImage(id); if (image.info.samples == 1 && (image.IsBufferModified() || image.IsCpuDirty())) { EXIT("TextureCache: image clear retained guest ownership\n"); } } if (image.info.HasStencil() && (range.aspectMask & vk::ImageAspectFlagBits::eStencil)) { const auto stencil_id = AssociateStencil(id, image.info.stencil); if (!full_subresources) { RefreshImage(stencil_id); } else { TrackImage(stencil_id); CommitGpuWrite(m_slot_images[stencil_id]); } } command.EndRendering(); // Transfer clears use the backing format; aliased clears must encode through their view. if (format != image.backing.format || (image.info.IsVolume() && !full_image)) { EXIT_NOT_IMPLEMENTED(range.aspectMask != vk::ImageAspectFlagBits::eColor || range.levelCount != 1); BeginColorRendering(image, format, range.baseMipLevel, range.baseArrayLayer, range.layerCount, &clear, command.Handle()); command.Handle().endRendering(); CommitGpuWrite(image); return; } image.Transit(vk::ImageLayout::eTransferDstOptimal, vk::AccessFlagBits2::eTransferWrite, {}, command.Handle()); auto native_range = range; if (image.info.IsVolume()) { native_range.baseArrayLayer = 0; native_range.layerCount = 1; } if (range.aspectMask == vk::ImageAspectFlagBits::eColor) { command.Handle().clearColorImage(image.backing.image, vk::ImageLayout::eTransferDstOptimal, &clear.color, 1, &native_range); } else { command.Handle().clearDepthStencilImage(image.backing.image, vk::ImageLayout::eTransferDstOptimal, &clear.depthStencil, 1, &native_range); } CommitGpuWrite(image); } vk::Rect2D TextureCache::BeginColorRendering(Image& image, vk::Format format, uint32_t level, uint32_t layer, uint32_t layers, const vk::ClearValue* clear, vk::CommandBuffer command) { ImageViewInfo view {}; view.format = format; view.type = layers == 1 ? vk::ImageViewType::e2D : vk::ImageViewType::e2DArray; view.base_level = level; view.base_layer = layer; view.layer_count = layers; view.usage = vk::ImageUsageFlagBits::eColorAttachment; image.Transit(vk::ImageLayout::eColorAttachmentOptimal, vk::AccessFlagBits2::eColorAttachmentRead | vk::AccessFlagBits2::eColorAttachmentWrite, {}, command); vk::RenderingAttachmentInfo attachment {}; attachment.imageView = image.FindView(view); attachment.imageLayout = vk::ImageLayout::eColorAttachmentOptimal; attachment.loadOp = vk::AttachmentLoadOp::eLoad; attachment.storeOp = vk::AttachmentStoreOp::eStore; if (clear != nullptr) { attachment.loadOp = vk::AttachmentLoadOp::eClear; attachment.clearValue = *clear; } vk::RenderingInfo rendering {}; rendering.renderArea.extent = {std::max(image.info.extent.width >> level, 1u), std::max(image.info.extent.height >> level, 1u)}; rendering.layerCount = layers; rendering.colorAttachmentCount = 1; rendering.pColorAttachments = &attachment; command.beginRendering(&rendering); return rendering.renderArea; } void TextureCache::InvalidateMemory(uint64_t address, uint64_t size) { if (!GuestRange {address, size}.Valid()) { EXIT("TextureCache: invalid memory-invalidation range\n"); } std::scoped_lock lock {m_lock}; InvalidateCpuAliases(address, size); } void TextureCache::InvalidateSequentialWrite(uint64_t address, uint64_t size) { if (!GuestRange {address, size}.Valid()) { EXIT("TextureCache: invalid sequential-write range\n"); } std::scoped_lock lock {m_lock}; InvalidateCpuAliases(address, size, true); } void TextureCache::DownloadDepth(Image& image, Buffer& destination, uint64_t destination_offset) { const auto& info = image.info; const auto layers = info.resources.layers; const auto full_slice_size = info.LinearLayout().slice_stride; const auto transfer_bytes = DepthAspectTransferBytes(info.pixel_format); const uint64_t texels_per_slice = static_cast(info.pitch) * info.extent.height; EXIT_NOT_IMPLEMENTED(transfer_bytes == 0 || texels_per_slice > UINT32_MAX || texels_per_slice > UINT64_MAX / transfer_bytes || texels_per_slice > UINT64_MAX / info.bytes_per_block); const uint64_t transfer_slice = texels_per_slice * transfer_bytes; const uint64_t guest_slice = texels_per_slice * info.bytes_per_block; EXIT_NOT_IMPLEMENTED(transfer_slice > UINT64_MAX / layers); const uint64_t transfer_size = transfer_slice * layers; EXIT_NOT_IMPLEMENTED(guest_slice > full_slice_size); if (transfer_bytes == info.bytes_per_block) { if (!info.IsTiled()) { const auto copies = info.BufferCopies(destination_offset); image.Download(copies, destination.Handle(), destination_offset, info.data.size); } else { const auto copies = info.BufferCopies(); m_tiler.TileImage(image, copies, destination.Handle(), destination_offset, info.data.size); } return; } EXIT_NOT_IMPLEMENTED(info.bytes_per_block != sizeof(uint16_t) || transfer_bytes != sizeof(uint32_t)); const std::array copies {vk::BufferImageCopy {0, info.pitch, info.extent.height, {vk::ImageAspectFlagBits::eDepth, 0, 0, layers}, {}, info.extent}}; auto host_linear = m_tiler.GetScratchBuffer(transfer_size); image.Download(copies, host_linear.buffer, 0, host_linear.size); const bool tiled = info.IsTiled(); auto guest_linear = tiled ? m_tiler.GetScratchBuffer(info.LinearSize(), host_linear.buffer) : TileManager::Result {destination.Handle(), destination_offset, destination.Size() - destination_offset}; m_tiler.ConvertD16(host_linear, guest_linear, TileManager::D16Direction::Demote, DepthAspectTransferFormat(info.pixel_format) == vk::Format::eD32Sfloat, {.width = info.extent.width, .height = info.extent.height, .layers = layers, .source_row_stride = static_cast(info.pitch) * sizeof(uint32_t), .target_row_stride = static_cast(info.pitch) * sizeof(uint16_t), .source_slice_stride = transfer_slice, .target_slice_stride = full_slice_size}); if (tiled) { m_tiler.Tile(guest_linear.buffer, guest_linear.offset, guest_linear.size, destination.Handle(), destination_offset, info.data.size, info); } } void TextureCache::DownloadImage(Image& image, Buffer& destination, uint64_t destination_offset, uint64_t destination_size, uint32_t levels) { if (UploadBinding(image) == BindingType::DepthTarget) { EXIT_IF(destination_size != image.info.data.size || levels != image.info.resources.levels); DownloadDepth(image, destination, destination_offset); return; } const auto& info = image.info; const auto transform = info.GetColorTransform(); if (info.IsTiled()) { const auto copies = info.BufferCopies(0, levels); m_tiler.TileImage(image, copies, destination.Handle(), destination_offset, destination_size, levels); } else if (transform != ColorTransform::None) { auto linear = m_tiler.GetScratchBuffer(destination_size); const auto copies = info.BufferCopies(0, levels); image.Download(copies, linear.buffer, 0, linear.size); m_tiler.TransformColor(linear, {destination.Handle(), destination_offset, destination_size}, transform, false); } else { const auto copies = info.BufferCopies(destination_offset, levels); image.Download(copies, destination.Handle(), destination_offset, destination_size); } } bool BufferCache::SynchronizeBufferFromImage(Buffer& buffer, ImageId id) { std::scoped_lock lock {m_texture_cache.m_lock}; auto& image = m_texture_cache.m_slot_images[id]; // The GPU thread owns image retirement; CPU invalidation can dirty this image after lookup. if (!image.SafeToDownload()) { return false; } if (!buffer.IsInBounds(image.info.data.address, 1)) { return false; } const auto buf_offset = buffer.Offset(image.info.data.address); const auto available = buffer.Size() - buf_offset; uint32_t levels = 0; uint64_t copy_size = 0; if (buffer.IsInBounds(image.info.data.address, image.info.data.size)) { levels = image.info.resources.levels; copy_size = image.info.data.size; } else if (image.info.IsVolume() || image.info.resources.layers > 1) { // Array and volume slices are strided across the full mip chain. return false; } else { for (; levels < image.info.resources.levels; ++levels) { const auto& mip = image.info.mip_layout[levels]; if (mip.size == 0 || mip.offset > available || mip.size > available - mip.offset) { break; } copy_size = std::max(copy_size, mip.offset + mip.size); } } if (copy_size == 0) { return false; } if (!m_texture_cache.CanDownload(image) || (TextureCache::UploadBinding(image) == TextureCache::BindingType::DepthTarget && copy_size != image.info.data.size)) { return false; } ForgetColorMetadataChecks(image.info.data.address, copy_size); m_texture_cache.DownloadImage(image, buffer, buf_offset, copy_size, levels); return true; } bool TextureCache::DownloadImageMemory(ImageId id, bool unlocked_copy) { auto* image = &m_slot_images[id]; if (image->depth_id) { return false; } if (!image->SafeToDownload() || !CanDownload(*image)) { return false; } const auto range = image->info.data; auto download = m_buffer_cache.GetUtilityBuffer(MemoryUsage::Download) .MapDownload(range.size, std::max(image->info.bytes_per_block, 4)); if (unlocked_copy) { // Guest write faults wait for m_lock in InvalidateMemory and would spin for the whole copy. // A write that lands meanwhile marks the image CPU dirty, and a freed slot can be reused, // so look the image up again before recording the download. const auto serial = image->serial; m_lock.unlock(); const bool read = LibKernel::Memory::TryReadBacking(range.address, download.mapped, range.size); m_lock.lock(); image = m_slot_images.try_get(id); if (!read || image == nullptr || image->serial != serial || !image->registered || !image->SafeToDownload()) { return false; } } else if (!LibKernel::Memory::TryReadBacking(range.address, download.mapped, range.size)) { return false; } download.buffer->Flush(download.offset, range.size); DownloadImage(*image, *download.buffer, download.offset, range.size, image->info.resources.levels); Common::DebugCounters::Add(Common::DebugCounters::Counter::TextureDownloadBytes, range.size); vk::BufferMemoryBarrier barrier {}; barrier.srcAccessMask = vk::AccessFlagBits::eMemoryWrite | vk::AccessFlagBits::eTransferWrite | vk::AccessFlagBits::eShaderWrite; barrier.dstAccessMask = vk::AccessFlagBits::eHostRead; barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; barrier.buffer = download.buffer->Handle(); barrier.offset = download.offset; barrier.size = range.size; m_scheduler.EndRendering(); m_scheduler.Current().Handle().pipelineBarrier(vk::PipelineStageFlagBits::eAllCommands, vk::PipelineStageFlagBits::eHost, {}, 0, nullptr, 1, &barrier, 0, nullptr); // With storage readback, guest accesses to its pages wait until the stored data lands. if (m_readback_storage_images) { { std::scoped_lock write_back_lock {m_write_back_mutex}; m_write_backs.push_back({range, m_scheduler.CurrentTick()}); } m_page_manager.UpdatePageWatchers(range.address, range.size); } m_scheduler.DeferPriorityOperation( [this, download = std::move(download), range, trapped = m_readback_storage_images] { download.buffer->Invalidate(download.offset, range.size); LibKernel::Memory::WriteBacking(range.address, download.mapped, range.size); if (trapped) { m_page_manager.UpdatePageWatchers(range.address, range.size); // Priority operations run in queue order, so this write-back is the oldest. std::scoped_lock write_back_lock {m_write_back_mutex}; m_write_backs.erase(m_write_backs.begin()); } }); return true; } uint64_t TextureCache::WriteBackTick(uint64_t address, uint64_t size) { if (!m_readback_storage_images) { return 0; } const auto begin = Common::AlignDown(address, TRACKER_PAGE_SIZE); const auto end = Common::AlignUp(address + size, TRACKER_PAGE_SIZE); uint64_t tick = 0; std::scoped_lock write_back_lock {m_write_back_mutex}; for (const auto& write_back: m_write_backs) { if (write_back.range.address < end && begin < write_back.range.End()) { tick = std::max(tick, write_back.tick); } } return tick; } // Records a storage-buffer write over an image. Without the opt-in flag this is the whole mark. // With it, a small write on an eligible image records only its byte range and leaves gpu_mod set, // since the image is still newer than the buffer outside that range. Everything else falls back // to the whole mark and clears gpu_mod first, exactly as InvalidateMemoryFromGPU does. void TextureCache::InvalidateBufferWrite(uint64_t address, uint64_t size) { if (!m_partial_buffer_refresh) { InvalidateMemoryFromGPU(address, size); return; } if (!GuestRange {address, size}.Valid()) { return; } std::scoped_lock lock {m_lock}; ForEachImageInRegion(address, size, [&](ImageId, Image& image) { if (image.info.data.address != address) { return; } const bool partial = IsPartialRefreshEligible(image) && WithinPartialLimit(image, size); if (partial) { image.MarkBufferModifiedRange(0, size); return; } MarkWholeBufferWrite(image); }); } void TextureCache::InvalidateMemoryFromGPU(uint64_t address, uint64_t size) { std::scoped_lock lock {m_lock}; ForEachImageInRegion(address, size, [&](ImageId, Image& image) { if (image.info.data.address != address) { return; } image.ClearGpuModified(); image.MarkBufferModified(); }); } bool TextureCache::CopyToImage(uint64_t address, uint64_t source, uint64_t size) { std::scoped_lock lock {m_lock}; Common::SmallVector targets; ForEachImageInRegion(address, size, [&](ImageId id, Image&) { targets.push_back(id); }); if (targets.size() != 1) { return false; } auto& image = m_slot_images[targets.front()]; const auto& info = image.info; bool source_modified = false; ForEachImageInRegion(source, size, [&](ImageId, Image& owner) { source_modified = owner.IsGpuModified(); return source_modified; }); if (image.depth_id || !image.SafeToDownload() || !CanDownload(image) || !info.IsTiled() || info.IsVolume() || info.IsDepth() || info.HasMetadata() || address < info.data.address || source_modified) { return false; } // Each layer holds its levels from the smallest up, and the tail levels share one block. const auto layers = info.resources.layers; const auto stride = info.data.size / layers; const auto offset = address - info.data.address; const auto begin = offset % stride; const auto end = begin + size; uint64_t covered = begin; uint32_t first = 0; uint32_t count = 0; for (uint32_t level = info.resources.levels; level-- > 0;) { const auto& mip = info.mip_layout[level]; const auto mip_end = mip.offset + mip.size / layers; if (mip_end <= begin || mip.offset >= end) { continue; } if (mip.offset < begin) { return false; } covered = mip_end; first = level; count++; } if (covered != end) { return false; } ImageInfo part = info; const auto extent = info.MipExtent(first); part.data.size = size; part.extent = {extent.width, extent.height, 1}; part.resources = {count, 1}; part.pitch = std::max(info.pitch >> first, 1u); part.first_tail_level -= std::min(first, info.first_tail_level); for (uint32_t level = 0; level < count; level++) { auto& mip = part.mip_layout[level] = info.mip_layout[first + level]; mip.offset -= begin; mip.size /= layers; } const auto [buffer, source_offset] = m_buffer_cache.ObtainBuffer(source, size, false); const auto texels = m_tiler.Detile(buffer->Handle(), source_offset, part); auto copies = part.BufferCopies(texels.offset); for (auto& copy: copies) { copy.imageSubresource.mipLevel += first; copy.imageSubresource.baseArrayLayer = static_cast(offset / stride); } image.Upload(copies, texels.buffer, texels.offset, texels.size); return true; } void TextureCache::InvalidateCpuAliases(uint64_t address, uint64_t size, bool sequential_write) { const auto page_begin = Common::AlignDown(address, TRACKER_PAGE_SIZE); const auto page_end = Common::AlignUp(address + size, TRACKER_PAGE_SIZE); Common::SmallVector image_ids; ForEachImageInRegion(page_begin, page_end - page_begin, [&](ImageId id, Image&) { image_ids.push_back(id); }); for (const auto id: image_ids) { auto& owner = m_slot_images[id]; const bool written = sequential_write ? SequentialWriteReachesImage(owner, address, size) : owner.Overlaps(address, size); if (written) { owner.MarkCpuDirty(); UntrackImage(id); continue; } const auto image_begin = owner.info.data.address; const auto image_end = owner.info.data.End(); if (page_end < image_end) { UntrackImageHead(id); } else if (image_begin < page_begin) { UntrackImageTail(id); } else { MarkAsMaybeDirty(id, owner); } } } bool TextureCache::IsMeta(uint64_t address) { std::scoped_lock lock {m_lock}; const auto found = m_surface_metas.find(address); return found != m_surface_metas.end(); } bool TextureCache::IsMetaCleared(uint64_t address, uint32_t slice) { std::scoped_lock lock {m_lock}; const auto found = m_surface_metas.find(address); if (found == m_surface_metas.end() || slice >= found->second.clear_mask.size()) { return false; } return found->second.clear_mask.test(slice); } bool TextureCache::ClearMeta(uint64_t address) { std::scoped_lock lock {m_lock}; const auto found = m_surface_metas.find(address); if (found == m_surface_metas.end()) { return false; } found->second.clear_mask.set(); found->second.stencil_clear_mask.set(); return true; } bool TextureCache::TouchMeta(uint64_t address, uint32_t slice, bool is_clear) { std::scoped_lock lock {m_lock}; const auto found = m_surface_metas.find(address); if (found == m_surface_metas.end() || slice >= found->second.clear_mask.size()) { return false; } found->second.clear_mask.set(slice, is_clear); found->second.stencil_clear_mask.set(slice, is_clear); return true; } vk::ImageAspectFlags TextureCache::TakeMetaClear(uint64_t address, uint32_t slice, vk::ImageAspectFlags aspects) { std::scoped_lock lock {m_lock}; const auto found = m_surface_metas.find(address); if (found == m_surface_metas.end() || slice >= found->second.clear_mask.size()) { return {}; } vk::ImageAspectFlags cleared; auto& meta = found->second; if ((aspects & vk::ImageAspectFlagBits::eDepth) && meta.clear_mask.test(slice)) { meta.clear_mask.reset(slice); cleared |= vk::ImageAspectFlagBits::eDepth; } if ((aspects & vk::ImageAspectFlagBits::eStencil) && meta.stencil_clear_mask.test(slice)) { meta.stencil_clear_mask.reset(slice); cleared |= vk::ImageAspectFlagBits::eStencil; } return cleared; } bool TextureCache::IsRegionRegistered(uint64_t address, uint64_t size) { std::scoped_lock lock {m_lock}; bool registered = false; ForEachImageInRegion(address, size, [&](ImageId, Image&) { registered = true; return true; }); return registered; } void TextureCache::UnmapMemory(uint64_t address, uint64_t size) { std::scoped_lock lock {m_lock}; m_surface_metas.erase(m_surface_metas.lower_bound(address), m_surface_metas.lower_bound(address + size)); Common::SmallVector deleted_images; ForEachImageInRegion(address, size, [&](ImageId id, Image&) { deleted_images.push_back(id); }); for (const auto id: deleted_images) { auto owner = m_slot_images.try_get(id); if (owner == nullptr) { continue; } FreeImage(id); } } void TextureCache::RunGarbageCollector() { std::scoped_lock lock {m_lock}; const uint64_t tick = m_gc_tick++; if (m_graphics.CanReportMemoryUsage()) { m_total_used_memory = m_graphics.GetDeviceMemoryUsage(); } if (m_total_used_memory < m_trigger_gc_memory) { return; } const auto collect = [&](bool allow_aggressive) { bool pressured = m_total_used_memory >= m_pressure_gc_memory; bool aggressive = allow_aggressive && m_total_used_memory >= m_critical_gc_memory; uint64_t age = 16; size_t deletions = 10; if (aggressive) { age = 160; deletions = 40; } else if (pressured) { age = 80; deletions = 20; } age = std::min(age, tick); std::vector candidates; // Deleting depth recursively deletes its stencil association, so finish LRU traversal // first. m_lru_cache.ForEachItemBelow(tick - age, [&](ImageId id) { candidates.push_back(id); }); for (const auto id: candidates) { if (deletions == 0) { break; } auto owner = m_slot_images.try_get(id); if (owner == nullptr || !owner->registered || owner->depth_id) { continue; } if (owner->heap_refs.load(std::memory_order_relaxed) != 0u) { // Resident heaps sample it without touching it. TouchImage(*owner); continue; } if (owner->SafeToDownload() && (!pressured || owner->info.HasStencil() || !DownloadImageMemory(id, true))) { continue; } --deletions; FreeImage(id); Common::DebugCounters::Add(Common::DebugCounters::Counter::TextureEvictions); if (m_total_used_memory < m_critical_gc_memory && aggressive) { deletions >>= 2; aggressive = false; } if (m_total_used_memory < m_pressure_gc_memory && pressured) { deletions >>= 1; pressured = false; } } }; collect(false); if (m_total_used_memory >= m_critical_gc_memory) { collect(true); } } void TextureCache::ProcessDownloadImages() { if (!m_readback_linear_images && !m_readback_tiled_images) { return; } (void)DownloadQueuedImages(); } bool TextureCache::WriteBackImages() { return m_readback_storage_images && DownloadQueuedImages(); } bool TextureCache::DownloadQueuedImages() { std::scoped_lock lock {m_lock}; bool downloaded = false; std::erase_if(m_download_images, [this, &downloaded](ImageId id) { const auto& image = m_slot_images[id]; if (!image.IsGpuModified()) { return true; } // A range mark makes the image unsafe to download until its next bind refreshes it, but // the image is still newer than guest memory outside that range. Dropping the id here // would lose the readback, so it stays pending for the next pass. if (image.BufferModifiedRange()) { return false; } downloaded |= DownloadImageMemory(id); return true; }); return downloaded; } } // namespace Libs::Graphics