diff --git a/core/kyty/graphics/host_gpu/renderer/cache/bufferCache.cpp b/core/kyty/graphics/host_gpu/renderer/cache/bufferCache.cpp index 2e6e38998c..54276fb3b3 100644 --- a/core/kyty/graphics/host_gpu/renderer/cache/bufferCache.cpp +++ b/core/kyty/graphics/host_gpu/renderer/cache/bufferCache.cpp @@ -2059,7 +2059,7 @@ void BufferCache::FillBuffer(uint64_t vaddr, uint64_t size, uint32_t value, bool if (vaddr == 0) { EXIT("BufferCache: invalid fill memory address\n"); } - (void)m_texture_cache.ClearMeta(vaddr); + const bool meta = m_texture_cache.ClearMeta(vaddr); if (!IsRegionGpuModified(vaddr, size) && !ServesInPlace(vaddr, size) && !DeferredLabelPending(vaddr, size)) { InvalidateMemory(vaddr, size); m_texture_cache.InvalidateMemory(vaddr, size); @@ -2067,6 +2067,9 @@ void BufferCache::FillBuffer(uint64_t vaddr, uint64_t size, uint32_t value, bool auto* destination = reinterpret_cast(vaddr); std::fill(destination, destination + size / sizeof(uint32_t), value); LibKernel::Memory::NoteEmulatorWrite(vaddr, size); + if (!meta) { + m_texture_cache.NoteMetaFill(vaddr, size, value, true); + } return; } @@ -2076,6 +2079,9 @@ void BufferCache::FillBuffer(uint64_t vaddr, uint64_t size, uint32_t value, bool m_in_place_write = InPlaceMemory::WriteKind::Binding; m_texture_cache.ProtectPendingImageWriteBacks(vaddr, size); dst->Fill(dst_offset, size, value); + if (!meta) { + m_texture_cache.NoteMetaFill(vaddr, size, value, false); + } } bool BufferCache::ReplicateBuffer(uint64_t destination, uint64_t count, uint64_t source, diff --git a/core/kyty/graphics/host_gpu/renderer/cache/textureCache.cpp b/core/kyty/graphics/host_gpu/renderer/cache/textureCache.cpp index 3893b55589..76dd76806c 100644 --- a/core/kyty/graphics/host_gpu/renderer/cache/textureCache.cpp +++ b/core/kyty/graphics/host_gpu/renderer/cache/textureCache.cpp @@ -177,6 +177,10 @@ TextureCache::TextureCache(GraphicContext& graphics, CommandScheduler& scheduler } TextureCache::~TextureCache() { + { + Common::ScopedLock pending {m_pending_meta_lock}; + ErasePendingMetaClearsLocked(m_pending_meta_clears.begin(), m_pending_meta_clears.end()); + } m_slot_images.ForEach([&](ImageId id, const Image& image) KYTY_NO_THREAD_SAFETY_ANALYSIS { if (image.registered) { UnregisterImage(id); @@ -2799,6 +2803,10 @@ vk::ImageView TextureCache::FindRenderTarget(ImageId id, const ImageDesc& desc) vk::ImageView TextureCache::FindDepthTarget(ImageId id, const ImageDesc& desc, ImageId* stencil) { CollectHotPagesOf(id); + if (desc.info.HasMetadata() && m_pending_meta_count.load(std::memory_order_acquire) != 0 && + m_page_manager.HasHotPages()) { + m_scheduler.Context().CollectHotPageWrites(desc.info.metadata.range.address, desc.info.metadata.range.size); + } Common::ScopedLock lock {m_lock}; auto& image = m_slot_images[id]; if (!image.registered || image.depth_id || image.binding.needs_rebind) { @@ -2827,6 +2835,9 @@ vk::ImageView TextureCache::FindDepthTarget(ImageId id, const ImageDesc& desc, I 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) { + ApplyPendingMetaClears(image.info, metadata->second); + } if (inserted && image.info.htile_initial_clear) { metadata->second.clear_mask.set(); } @@ -2894,6 +2905,7 @@ void TextureCache::CommitGpuWrite(Image& image) { image.MarkGpuModified(); image.gpu_write_sequence = Image::gpu_write_sequences.fetch_add(1u, std::memory_order_relaxed) + 1u; + DropPendingMetaClears(image.info.data.address, image.info.data.size); } bool TextureCache::ClearImageFromBuffer(CommandBuffer& command, uint64_t address, uint64_t size, @@ -3461,6 +3473,7 @@ void TextureCache::ProtectPendingImageWriteBacks(uint64_t address, uint64_t size } void TextureCache::InvalidateMemoryFromGPU(uint64_t address, uint64_t size) { + DropPendingMetaClears(address, size); Common::ScopedLock lock {m_lock}; ForEachImageInRegion(address, size, [&](ImageId, Image& image) { if (image.info.data.address != address) { @@ -3576,6 +3589,7 @@ bool TextureCache::CopyToImage(uint64_t address, uint64_t source, uint64_t size) copy.imageSubresource.baseArrayLayer = static_cast(offset / stride); } image.Upload(copies, texels.buffer, texels.offset, texels.size); + DropPendingMetaClears(address, size); return true; } @@ -3594,6 +3608,7 @@ bool TextureCache::IsRegionGpuModified(uint64_t address, uint64_t size, bool inc } bool TextureCache::InvalidateMemory(uint64_t address, uint64_t size) { + DropPendingMetaClearsAround(address, size); ImagePageTable::PageRange pages {}; if (ImagePageTable::TryGetPageRange(address, size, pages) && !m_registered_pages.Any(pages.first, pages.last_exclusive)) { @@ -3700,6 +3715,236 @@ bool TextureCache::CoversMeta(uint64_t address, uint64_t size) { return size >= info.metadata.range.size / std::max(info.resources.layers, 1u) && size <= info.metadata.range.size; } +bool TextureCache::OverlapsSurfaceMetaLocked(uint64_t address, uint64_t size) const { + const uint64_t end = size > UINT64_MAX - address ? UINT64_MAX : address + size; + auto found = m_surface_metas.lower_bound(address); + if (found != m_surface_metas.end() && found->first < end) { + return true; + } + if (found == m_surface_metas.begin()) { + return false; + } + --found; + const auto* owner = m_slot_images.try_get(found->second.owner); + return owner == nullptr || owner->info.metadata.range.address != found->first || + owner->info.metadata.range.End() > address; +} + +void TextureCache::NoteMetaFill(uint64_t address, uint64_t size, uint32_t value, bool in_memory) { + if ((value & 0xfu) != 0 || size == 0 || (!in_memory && !GuestRange {address, size}.Valid())) { + return; + } + Common::ScopedLock lock {m_lock}; + if (OverlapsSurfaceMetaLocked(address, size)) { + return; + } + Common::ScopedLock pending {m_pending_meta_lock}; + DropPendingMetaClearsLocked(address, size); + m_pending_meta_clears[address] = {size, m_gc_tick, value, in_memory}; + std::array granules {}; + AddPendingMetaGranules(granules, address, size); + for (size_t word = 0; word < granules.size(); ++word) { + if (granules[word] != 0) { + m_pending_meta_granules[word].fetch_or(granules[word], std::memory_order_relaxed); + } + } + UpdatePendingMetaBoundsLocked(); + if (!in_memory) { + HoldPendingMetaPagesLocked(address, size, true); + } +} + +void TextureCache::HoldPendingMetaPagesLocked(uint64_t address, uint64_t size, bool hold) { + const auto first = Common::AlignDown(address, TRACKER_PAGE_SIZE); + const auto last = Common::AlignDown(address + size - 1, TRACKER_PAGE_SIZE); + const auto watch = [&](uint64_t begin, uint64_t end) { + if (begin >= end) { + return; + } + if (hold) { + m_page_manager.UpdatePageWatchers(begin, end - begin); + } else { + m_page_manager.UpdatePageWatchers(begin, end - begin); + } + }; + const auto edge = [&](uint64_t page) KYTY_REQUIRES(m_pending_meta_lock) { + if (hold) { + if (++m_pending_meta_pages[page] == 1) { + watch(page, page + TRACKER_PAGE_SIZE); + } + } else if (const auto found = m_pending_meta_pages.find(page); + found != m_pending_meta_pages.end() && --found->second == 0) { + m_pending_meta_pages.erase(found); + watch(page, page + TRACKER_PAGE_SIZE); + } + }; + edge(first); + if (last != first) { + watch(first + TRACKER_PAGE_SIZE, last); + edge(last); + } +} + +void TextureCache::AddPendingMetaGranules(std::array& words, uint64_t address, uint64_t size) { + const auto first = address >> PendingMetaGranuleBits; + const auto last = (address + size - 1) >> PendingMetaGranuleBits; + for (auto granule = first; granule <= last && granule - first < 4096u; ++granule) { + const auto bit = granule & 4095u; + words[bit >> 6u] |= uint64_t {1} << (bit & 63u); + } +} + +void TextureCache::UpdatePendingMetaBoundsLocked() { + if (m_pending_meta_clears.empty()) { + m_pending_meta_begin.store(UINT64_MAX, std::memory_order_relaxed); + m_pending_meta_end.store(0, std::memory_order_relaxed); + for (auto& word: m_pending_meta_granules) { + word.store(0, std::memory_order_relaxed); + } + } else { + const auto& [last_address, last] = *m_pending_meta_clears.rbegin(); + m_pending_meta_begin.store(m_pending_meta_clears.begin()->first, std::memory_order_relaxed); + m_pending_meta_end.store(last_address + last.size, std::memory_order_relaxed); + } + m_pending_meta_count.store(m_pending_meta_clears.size(), std::memory_order_release); +} + +void TextureCache::DropPendingMetaClears(uint64_t address, uint64_t size) { + if (size == 0 || m_pending_meta_count.load(std::memory_order_acquire) == 0) { + return; + } + const uint64_t end = size > UINT64_MAX - address ? UINT64_MAX : address + size; + if (end <= m_pending_meta_begin.load(std::memory_order_relaxed) || + address >= m_pending_meta_end.load(std::memory_order_relaxed) || !MaybePendingMeta(address, end)) { + return; + } + Common::ScopedLock lock {m_pending_meta_lock}; + DropPendingMetaClearsLocked(address, size); +} + +bool TextureCache::MaybePendingMeta(uint64_t address, uint64_t end) const { + const auto first = address >> PendingMetaGranuleBits; + const auto last = (end - 1) >> PendingMetaGranuleBits; + if (last - first >= 64u) { + return true; + } + for (auto granule = first; granule <= last; ++granule) { + const auto bit = granule & 4095u; + if (((m_pending_meta_granules[bit >> 6u].load(std::memory_order_relaxed) >> (bit & 63u)) & 1u) != 0) { + return true; + } + } + return false; +} + +void TextureCache::DropPendingMetaClearsLocked(uint64_t address, uint64_t size) { + if (size == 0) { + return; + } + auto first = m_pending_meta_clears.lower_bound(address); + if (first != m_pending_meta_clears.begin()) { + const auto previous = std::prev(first); + if (previous->first + previous->second.size > address) { + first = previous; + } + } + const auto last = + size > UINT64_MAX - address ? m_pending_meta_clears.end() : m_pending_meta_clears.lower_bound(address + size); + if (first == last) { + return; + } + ErasePendingMetaClearsLocked(first, last); + UpdatePendingMetaBoundsLocked(); +} + +void TextureCache::ErasePendingMetaClearsLocked(PendingMetaClears::iterator first, PendingMetaClears::iterator last) { + for (auto it = first; it != last; ++it) { + if (!it->second.in_memory) { + HoldPendingMetaPagesLocked(it->first, it->second.size, false); + } + } + m_pending_meta_clears.erase(first, last); +} + +void TextureCache::DropPendingMetaClearsAround(uint64_t address, uint64_t size) { + if (size == 0 || m_pending_meta_count.load(std::memory_order_acquire) == 0) { + return; + } + const uint64_t end = size > UINT64_MAX - address ? UINT64_MAX : address + size; + const uint64_t page_begin = Common::AlignDown(address, TRACKER_PAGE_SIZE); + const uint64_t page_end = end > UINT64_MAX - TRACKER_PAGE_SIZE ? UINT64_MAX : Common::AlignUp(end, TRACKER_PAGE_SIZE); + if (page_end <= m_pending_meta_begin.load(std::memory_order_relaxed) || + page_begin >= m_pending_meta_end.load(std::memory_order_relaxed) || !MaybePendingMeta(page_begin, page_end)) { + return; + } + Common::ScopedLock pending {m_pending_meta_lock}; + auto it = m_pending_meta_clears.lower_bound(page_begin); + if (it != m_pending_meta_clears.begin()) { + const auto previous = std::prev(it); + if (previous->first + previous->second.size > page_begin) { + it = previous; + } + } + bool erased = false; + while (it != m_pending_meta_clears.end() && it->first < page_end) { + const auto next = std::next(it); + if (!it->second.in_memory || (it->first < end && address < it->first + it->second.size)) { + ErasePendingMetaClearsLocked(it, next); + erased = true; + } + it = next; + } + if (erased) { + UpdatePendingMetaBoundsLocked(); + } +} + +static bool HoldsFill(uint64_t address, uint64_t size, uint32_t value) { + std::array words {}; + for (uint64_t offset = 0; offset + sizeof(uint32_t) <= size;) { + const auto count = std::min(words.size(), (size - offset) / sizeof(uint32_t)); + if (!LibKernel::Memory::TryReadBacking(address + offset, words.data(), count * sizeof(uint32_t)) || + !std::all_of(words.begin(), words.begin() + count, [value](uint32_t word) { return word == value; })) { + return false; + } + offset += count * sizeof(uint32_t); + } + return true; +} + +void TextureCache::ApplyPendingMetaClears(const ImageInfo& info, MetaDataInfo& meta) { + if (m_pending_meta_count.load(std::memory_order_acquire) == 0) { + return; + } + const auto range = info.metadata.range; + const uint64_t layers = std::max(info.resources.layers, 1u); + const uint64_t slice = range.size / layers; + Common::ScopedLock lock {m_pending_meta_lock}; + auto first = m_pending_meta_clears.lower_bound(range.address); + if (first != m_pending_meta_clears.begin()) { + const auto previous = std::prev(first); + if (previous->first + previous->second.size > range.address) { + first = previous; + } + } + const auto last = m_pending_meta_clears.lower_bound(range.End()); + for (auto it = first; slice != 0 && it != last; ++it) { + const auto [address, pending] = *it; + if (m_gc_tick - pending.tick > 1 || (info.metadata.stencil_compressed && ((pending.value >> 8u) & 0x3u) != 0)) { + continue; + } + for (uint64_t layer = 0; layer < layers && layer < meta.clear_mask.size(); ++layer) { + const auto begin = range.address + layer * slice; + if (begin >= address && begin + slice <= address + pending.size && + (!pending.in_memory || HoldsFill(begin, slice, pending.value))) { + meta.clear_mask.set(layer); + } + } + } + ErasePendingMetaClearsLocked(first, last); + UpdatePendingMetaBoundsLocked(); +} + bool TextureCache::TouchMeta(uint64_t address, uint32_t slice, bool is_clear) { Common::ScopedLock lock {m_lock}; const auto found = m_surface_metas.find(address); @@ -3737,6 +3982,7 @@ void TextureCache::UnmapMemory(uint64_t address, uint64_t size) { DiscardParkedImages(address, size); m_surface_metas.erase(m_surface_metas.lower_bound(address), m_surface_metas.lower_bound(address + size)); + DropPendingMetaClears(address, size); m_meta_epoch.fetch_add(1, std::memory_order_relaxed); Common::SmallVector deleted_images; ForEachImageInRegion(address, size, [&](ImageId id, Image&) { deleted_images.push_back(id); }); @@ -3775,6 +4021,24 @@ void TextureCache::MapMemory(uint64_t address, uint64_t size) { void TextureCache::RunGarbageCollector() { Common::ScopedLock lock {m_lock}; const uint64_t tick = m_gc_tick++; + { + Common::ScopedLock pending {m_pending_meta_lock}; + for (auto it = m_pending_meta_clears.begin(); it != m_pending_meta_clears.end();) { + const auto next = std::next(it); + if (m_gc_tick - it->second.tick > 1) { + ErasePendingMetaClearsLocked(it, next); + } + it = next; + } + std::array granules {}; + for (const auto& [address, record]: m_pending_meta_clears) { + AddPendingMetaGranules(granules, address, record.size); + } + for (size_t word = 0; word < granules.size(); ++word) { + m_pending_meta_granules[word].store(granules[word], std::memory_order_relaxed); + } + UpdatePendingMetaBoundsLocked(); + } DiscardParkedImages(0, 0); if (m_graphics.CanReportMemoryUsage()) { m_total_used_memory = m_graphics.GetDeviceMemoryUsage(); diff --git a/core/kyty/graphics/host_gpu/renderer/cache/textureCache.h b/core/kyty/graphics/host_gpu/renderer/cache/textureCache.h index 877470354a..0cafe3d222 100644 --- a/core/kyty/graphics/host_gpu/renderer/cache/textureCache.h +++ b/core/kyty/graphics/host_gpu/renderer/cache/textureCache.h @@ -98,6 +98,7 @@ class TextureCache { [[nodiscard]] bool IsMetaCleared(uint64_t address, uint32_t slice); [[nodiscard]] bool ClearMeta(uint64_t address); [[nodiscard]] bool CoversMeta(uint64_t address, uint64_t size); + void NoteMetaFill(uint64_t address, uint64_t size, uint32_t value, bool in_memory); [[nodiscard]] bool TouchMeta(uint64_t address, uint32_t slice, bool is_clear); void UnmapMemory(uint64_t address, uint64_t size); @@ -161,6 +162,7 @@ class TextureCache { return settled; } void NoteMetadataWrite(uint64_t vaddr, uint64_t size) { + DropPendingMetaClears(vaddr, size); if (vaddr < m_settled_end.load(std::memory_order_acquire) && vaddr + size > m_settled_begin.load(std::memory_order_acquire) && MaybeSettled(vaddr, size)) { ForgetSettledMetadata(vaddr, size); @@ -197,6 +199,14 @@ class TextureCache { void RunGarbageCollector(); private: + struct PendingMetaClear { + uint64_t size = 0; + uint64_t tick = 0; + uint32_t value = 0; + bool in_memory = false; + }; + using PendingMetaClears = std::map; + struct MetaDataInfo { std::bitset<8192> clear_mask; ImageId owner; @@ -351,6 +361,18 @@ class TextureCache { void DeleteImage(ImageId id) KYTY_REQUIRES(m_lock); void ReleaseDepthFeedbackCopy(ImageId depth_id); void FreeImage(ImageId id) KYTY_REQUIRES(m_lock); + void ApplyPendingMetaClears(const ImageInfo& info, MetaDataInfo& meta) KYTY_REQUIRES(m_lock); + void DropPendingMetaClears(uint64_t address, uint64_t size); + void DropPendingMetaClearsLocked(uint64_t address, uint64_t size) + KYTY_REQUIRES(m_pending_meta_lock); + void UpdatePendingMetaBoundsLocked() KYTY_REQUIRES(m_pending_meta_lock); + void ErasePendingMetaClearsLocked(PendingMetaClears::iterator first, PendingMetaClears::iterator last) + KYTY_REQUIRES(m_pending_meta_lock); + void HoldPendingMetaPagesLocked(uint64_t address, uint64_t size, bool hold) KYTY_REQUIRES(m_pending_meta_lock); + void DropPendingMetaClearsAround(uint64_t address, uint64_t size); + [[nodiscard]] bool OverlapsSurfaceMetaLocked(uint64_t address, uint64_t size) const KYTY_REQUIRES(m_lock); + [[nodiscard]] bool MaybePendingMeta(uint64_t address, uint64_t end) const; + static void AddPendingMetaGranules(std::array& words, uint64_t address, uint64_t size); void TouchImage(Image& image) KYTY_NO_THREAD_SAFETY_ANALYSIS; void TrackImage(ImageId id); void TrackImageHead(ImageId id); @@ -475,6 +497,14 @@ class TextureCache { std::unordered_map> m_stencil_copies; std::vector> m_parked_images; std::map m_surface_metas; + Common::AnnotatedMutex m_pending_meta_lock; + PendingMetaClears m_pending_meta_clears KYTY_GUARDED_BY(m_pending_meta_lock); + std::map m_pending_meta_pages KYTY_GUARDED_BY(m_pending_meta_lock); + std::atomic m_pending_meta_count {0}; + std::atomic m_pending_meta_begin {UINT64_MAX}; + std::atomic m_pending_meta_end {0}; + static constexpr uint32_t PendingMetaGranuleBits = 16; + std::array, 64> m_pending_meta_granules {}; uint64_t m_total_used_memory = 0; uint64_t m_trigger_gc_memory = 0; uint64_t m_pressure_gc_memory = 1536ull * 1024 * 1024; diff --git a/core/kyty/graphics/host_gpu/renderer/render.h b/core/kyty/graphics/host_gpu/renderer/render.h index 86c5412612..bfae47d8d3 100644 --- a/core/kyty/graphics/host_gpu/renderer/render.h +++ b/core/kyty/graphics/host_gpu/renderer/render.h @@ -648,6 +648,12 @@ class RenderExecutor { uint64_t m_linear_copy_generation = 0; uint32_t m_linear_copy_uses = 0; std::array m_replicated {}; + struct RefusedFill { + uint64_t address = 0; + uint64_t size = 0; + uint32_t value = 0; + }; + RefusedFill m_refused_fill {}; std::unique_ptr m_draw_state {nullptr, nullptr}; std::unique_ptr m_resolved_ring {nullptr, diff --git a/core/kyty/graphics/host_gpu/renderer/renderCompute.cpp b/core/kyty/graphics/host_gpu/renderer/renderCompute.cpp index a793b2d25f..8a9627d653 100644 --- a/core/kyty/graphics/host_gpu/renderer/renderCompute.cpp +++ b/core/kyty/graphics/host_gpu/renderer/renderCompute.cpp @@ -324,9 +324,11 @@ bool RenderExecutor::TryConsumeComputeFill(const ShaderComputeInputInfo& input, const bool image_clear = cache.ClearImageFromBuffer(command, descriptor.Base48(), size, packed_clear); if (!image_clear) { - if ((descriptor.Base48() & 3u) != 0 || - !m_context.IsMapped(descriptor.Base48(), size) || - cache.IsRegionRegistered(descriptor.Base48(), size)) { + if ((descriptor.Base48() & 3u) != 0 || !m_context.IsMapped(descriptor.Base48(), size)) { + return false; + } + if (cache.IsRegionRegistered(descriptor.Base48(), size)) { + m_refused_fill = {descriptor.Base48(), size, packed_clear}; return false; } m_context.GetBufferCache().FillBuffer(descriptor.Base48(), size, packed_clear, false); @@ -513,6 +515,7 @@ void RenderExecutor::DispatchDirect(CommandBuffer& buffer, uint32_t thread_group const auto& resources = *input_info.stage.resources; m_replicated[2] = 0; + m_refused_fill = {}; if (resources.specialization_reads.empty() && (TryConsumeComputeMetaClear(input_info, buffer) || TryConsumeComputeFill(input_info, buffer, thread_group_x, thread_group_y, @@ -695,6 +698,10 @@ void RenderExecutor::DispatchDirect(CommandBuffer& buffer, uint32_t thread_group m_deferred_barrier = true; m_deferred_barrier_queue = m_guest_queue; ResetBindings(); + if (m_refused_fill.address != 0) { + m_context.GetTextureCache().NoteMetaFill(m_refused_fill.address, m_refused_fill.size, + m_refused_fill.value, false); + } }; if (RtCheck().Sample(*compute_module, buffer)) { const auto hash = compute_module->info.shader_hash; diff --git a/core/libs/prx/libSceAgcDriver/KytyShim/tests/CMakeLists.txt b/core/libs/prx/libSceAgcDriver/KytyShim/tests/CMakeLists.txt index 7948d3399b..c45ff737fb 100644 --- a/core/libs/prx/libSceAgcDriver/KytyShim/tests/CMakeLists.txt +++ b/core/libs/prx/libSceAgcDriver/KytyShim/tests/CMakeLists.txt @@ -621,6 +621,21 @@ if(WIN32) ENVIRONMENT_MODIFICATION "PATH=path_list_prepend:$") endif() +add_test_executable(kyty_shim_depth_meta_fill_tests ${CMAKE_CURRENT_SOURCE_DIR}/DepthMetaFillReplay.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/../../Execution/src/FrameCapture.cpp) +target_include_directories(kyty_shim_depth_meta_fill_tests PRIVATE ${LIBS_INCLUDE_DIR} ${CMAKE_SOURCE_DIR}/3rdparty/zstd/lib) +target_link_libraries(kyty_shim_depth_meta_fill_tests PRIVATE libzstd_static) +set_target_properties(kyty_shim_depth_meta_fill_tests PROPERTIES CXX_EXTENSIONS OFF) +configure_host_test_executable(kyty_shim_depth_meta_fill_tests) +add_dependencies(kyty_shim_depth_meta_fill_tests agc_frame_replay) +add_test(NAME kyty_shim_depth_meta_fill COMMAND kyty_shim_depth_meta_fill_tests $) +set_tests_properties(kyty_shim_depth_meta_fill PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77 + PASS_REGULAR_EXPRESSION "kyty_shim_depth_meta_fill: ok") +if(WIN32) + set_property(TEST kyty_shim_depth_meta_fill APPEND PROPERTY + ENVIRONMENT_MODIFICATION "PATH=path_list_prepend:$") +endif() + add_test_executable(kyty_shim_buffer_null_range_tests ${CMAKE_CURRENT_SOURCE_DIR}/BufferNullRange.cpp ${CMAKE_CURRENT_SOURCE_DIR}/../../Execution/src/FrameCapture.cpp) target_include_directories(kyty_shim_buffer_null_range_tests PRIVATE ${LIBS_INCLUDE_DIR} ${CMAKE_SOURCE_DIR}/3rdparty/zstd/lib) diff --git a/core/libs/prx/libSceAgcDriver/KytyShim/tests/DepthMetaFillReplay.cpp b/core/libs/prx/libSceAgcDriver/KytyShim/tests/DepthMetaFillReplay.cpp new file mode 100644 index 0000000000..abd216fa5b --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/KytyShim/tests/DepthMetaFillReplay.cpp @@ -0,0 +1,409 @@ +#include "prx/libSceAgcDriver/Execution/include/FrameCapture.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +constexpr std::uint64_t GuestBase = 0x200800000; +constexpr std::uint64_t Block = 0x10000; +constexpr std::uint64_t VertexHeader = GuestBase + 0x100; +constexpr std::uint64_t PixelHeader = GuestBase + 0x300; +constexpr std::uint64_t ImageHeader = GuestBase + 0x500; +constexpr std::uint64_t FillHeader = GuestBase + 0x700; +constexpr std::uint64_t VertexCode = GuestBase + 0x800; +constexpr std::uint64_t PixelCode = GuestBase + 0x900; +constexpr std::uint64_t ImageCode = GuestBase + 0xa00; +constexpr std::uint64_t FillCode = GuestBase + 0xb00; +constexpr std::uint64_t Commands = GuestBase + 0x1000; +constexpr std::uint64_t Depth = GuestBase + Block; +constexpr std::uint64_t Htile = GuestBase + 3 * Block; +constexpr std::uint64_t Color = GuestBase + 4 * Block; +constexpr std::uint64_t GuestBytes = 8 * Block; +constexpr std::uint32_t Width = 64; +constexpr std::uint32_t Height = 4; +constexpr std::uint32_t Layers = 2; +constexpr std::uint64_t HtileSliceBytes = 0x8000; +constexpr std::uint32_t FillLanes = 64; +constexpr std::uint32_t EndProgram = 0xbf810000; +constexpr std::uint32_t Cleared = 0; +constexpr std::uint32_t Expanded = 0xffffffffu; +constexpr std::uint32_t Format32UInt = 20; +constexpr std::uint32_t Format8UInt = 5; +constexpr std::uint32_t ViewFirst = 1u << 13u; +constexpr std::uint32_t ViewSecond = 1u | (1u << 13u); +constexpr std::uint32_t HtileEnable = 0x20000000u; +constexpr std::uint32_t ZEnableNever = 0x02; +constexpr std::uint32_t ZEnableLess = 0x12; +constexpr std::string_view ConsumedFill = "GraphicsRenderDispatchDirect: compute "; + +constexpr std::array VertexWords{ + 0x7e000d05, 0x080200f4, 0x10020300, 0x100202f4, 0x060202f3, 0x060400f3, 0x10040500, 0x060404f3, + 0x7e060280, 0x7e0802f2, 0xf80008cf, 0x04030201, EndProgram, EndProgram, EndProgram, EndProgram, +}; + +constexpr std::array PixelWords{ + 0x7e0002f2u, 0x7e020280u, 0xf800180fu, 0x00010001u, EndProgram, +}; + +constexpr std::array ImageWriteWords{ + 0x7e040300u, 0x7e060301u, 0x7e0802ffu, 0x5au, 0xf0201108u, 0x00020402u, EndProgram, +}; + +constexpr std::array FillWords{ + 0x8f068605u, 0x4a000006u, 0x7e020204u, 0xe0102000u, 0x80000100u, EndProgram, +}; + +struct Case { + const char* name; + bool image; + std::uint32_t value; + std::uint64_t bytes; + bool overwrite; +}; + +constexpr std::array Cases{ + Case{"expanded", true, Expanded, Layers * HtileSliceBytes, false}, + Case{"cleared", true, Cleared, Layers * HtileSliceBytes, false}, + Case{"first-layer", true, Cleared, HtileSliceBytes, false}, + Case{"overwritten", true, Cleared, Layers * HtileSliceBytes, true}, + Case{"consumed", false, Cleared, Layers * HtileSliceBytes, false}, +}; + +std::uint32_t low(std::uint64_t address) { + return static_cast(address >> 8u); +} + +std::uint32_t high(std::uint64_t address) { + return static_cast(address >> 40u); +} + +std::uint32_t bits(float value) { + return std::bit_cast(value); +} + +void append(std::vector& words, std::uint32_t opcode, std::initializer_list payload) { + words.push_back(0xc0000000u | (static_cast(payload.size() - 1) << 16u) | (opcode << 8u)); + words.insert(words.end(), payload); +} + +void appendImageWrite(std::vector& words) { + append(words, 0x76, {0x20c, low(ImageCode), high(ImageCode)}); + append(words, 0x76, {0x212, 0u, (16u << 1u) | (1u << 11u)}); + append(words, 0x76, {0x207, Width, Height, 1u}); + append(words, 0x76, + {0x248, low(Htile), high(Htile) | (Format8UInt << 20u) | (((Width - 1u) & 3u) << 30u), + ((Width - 1u) >> 2u) | ((Height - 1u) << 14u), 0x90500004u, 0u, 0u, 0u, 0u}); + append(words, 0x15, {1u, 1u, 1u, 0x41u}); +} + +void appendFill(std::vector& words, std::uint32_t value, std::uint64_t bytes) { + const auto elements = static_cast(bytes / sizeof(std::uint32_t)); + append(words, 0x76, {0x20c, low(FillCode), high(FillCode)}); + append(words, 0x76, {0x212, 0u, (5u << 1u) | (1u << 7u)}); + append(words, 0x76, {0x207, FillLanes, 1u, 1u}); + append(words, 0x76, + {0x240, static_cast(Htile), static_cast((Htile >> 32u) & 0xffffu) | (4u << 16u), + elements, 0xfacu | (Format32UInt << 12u) | (1u << 24u), value}); + append(words, 0x15, {elements / FillLanes, 1u, 1u, 0x41u}); +} + +void appendDraw(std::vector& words, bool htile, std::uint32_t view, std::uint32_t depth_control, + std::uint32_t left, std::uint32_t right) { + const std::pair context[]{ + {0x2d5, 0x2000}, + {0x1b3, 0x2}, {0x1b4, 0x2}, {0x1b6, 0}, {0x207, 0}, {0x200, depth_control}, {0x203, 0}, + {0x2dc, 0xaa00}, {0x2f8, 0}, {0x293, 0}, + {0x80, 0}, {0x8d, 0}, {0x83, 0xffff}, + {0x2f9, 0x2d}, {0x313, 0x6000}, {0x30e, 0xffffffff}, {0x30f, 0xffffffff}, + {0x206, 0x43f}, {0x204, 0x80000}, {0x205, 0x240}, + {0x8e, 0xf}, {0x8f, 0xf}, {0x202, 0xcc0010}, + {0x1c4, 0}, {0x1c5, 9}, {0x1c3, 4}, {0x31c, 0x28628}, + {0x31b, 0}, {0x31d, 0}, {0x3b0, ((Width - 1u) << 14u) | (Height - 1u)}, + {0x3b8, 0x906c000}, {0x1e0, 0}, + {0xc, 0}, {0xd, (Height << 16u) | Width}, + {0x81, 0x80000000}, {0x82, (Height << 16u) | Width}, + {0x90, 0x80000000u | left}, {0x91, (Height << 16u) | right}, + {0x94, 0x80000000}, {0x95, (Height << 16u) | Width}, + {0x10f, bits(Width / 2.0f)}, {0x110, bits(Width / 2.0f)}, + {0x111, bits(-(Height / 2.0f))}, {0x112, bits(Height / 2.0f)}, + {0x113, bits(0.5f)}, {0x114, bits(0.25f)}, + {0xb4, 0}, {0xb5, bits(1.0f)}, + {0x2fe, 0}, {0x302, 0}, {0x306, 0}, {0x30a, 0}, + {0x318, low(Color)}, {0x390, high(Color)}, {0x292, 2}, + {0x000, 0}, {0x002, view}, {0x007, ((Height - 1u) << 16u) | (Width - 1u)}, + {0x008, 0}, {0x009, bits(1.0f)}, {0x00a, 0}, {0x00b, bits(1.0f)}, + {0x010, 3u | (htile ? HtileEnable : 0u)}, {0x011, 0}, + {0x005, htile ? low(Htile) : 0u}, {0x01e, htile ? high(Htile) : 0u}, + {0x012, low(Depth)}, {0x014, low(Depth)}, {0x01a, high(Depth)}, {0x01c, high(Depth)}, + {0x013, 0}, {0x015, 0}, {0x01b, 0}, {0x01d, 0}, + }; + const std::pair shader[]{ + {0xc8, low(VertexCode)}, {0xc9, high(VertexCode)}, {0x8b, 1u << 1u}, {0x8c, 0}, + {0x008, low(PixelCode)}, {0x009, high(PixelCode)}, {0x00a, 0}, {0x00b, 16u << 1u}, + }; + append(words, 0x79, {0x242, 4}); + for (const auto& [offset, value] : context) append(words, 0x69, {offset, value}); + for (const auto& [offset, value] : shader) append(words, 0x76, {offset, value}); + append(words, 0x2d, {3, 2}); +} + +std::vector primeWords(const Case& test) { + std::vector words; + appendDraw(words, false, 0, ZEnableNever, 0, Width); + if (test.image) appendImageWrite(words); + return words; +} + +std::vector fillWords(const Case& test) { + std::vector words; + appendFill(words, test.value, test.bytes); + return words; +} + +std::vector bindWords() { + std::vector words; + appendDraw(words, true, ViewSecond, ZEnableLess, Width / 2u, Width); + appendDraw(words, true, ViewFirst, ZEnableLess, 0, Width / 2u); + return words; +} + +template +void write(std::span memory, std::uint64_t address, std::span items) { + const auto offset = address - GuestBase; + if (offset > memory.size() || items.size_bytes() > memory.size() - offset) { + throw std::runtime_error("fixture memory write past the guest mapping"); + } + std::memcpy(memory.data() + offset, items.data(), items.size_bytes()); +} + +void writeShader(std::span memory, std::uint64_t address, std::uint64_t code, std::uint8_t type, + std::span words) { + struct Header { + Shader shader{}; + ShaderUserData user{}; + std::array registers{}; + }; + Header header{}; + header.shader.file_header = 0x34333231; + header.shader.version = 0x18; + header.shader.header_size = sizeof(Header); + header.shader.shader_size = static_cast(words.size_bytes()); + header.shader.code = reinterpret_cast(code); + header.shader.type = type; + header.shader.user_data = reinterpret_cast(address + offsetof(Header, user)); + if (type == 1) { + header.registers = {{{0x008, low(code)}, {0x009, high(code)}, {0x00b, 16u << 1u}, {0x00a, 0}}}; + header.shader.sh_registers = reinterpret_cast(address + offsetof(Header, registers)); + header.shader.num_sh_registers = static_cast(header.registers.size()); + } + write(memory, address, std::span(&header, 1)); + write(memory, code, words); +} + +void makeCapture(const std::filesystem::path& path, const Case& test) { + using AgcDriver::FrameCallKind; + auto memory = std::vector(GuestBytes); + const std::array submits{primeWords(test), fillWords(test), bindWords()}; + std::array addresses{}; + std::uint64_t next = Commands; + for (std::size_t index = 0; index < submits.size(); ++index) { + addresses[index] = next; + write(memory, next, std::span(submits[index])); + next += (submits[index].size() * sizeof(std::uint32_t) + 0xffu) & ~std::uint64_t{0xff}; + } + if (next > Depth) throw std::runtime_error("command buffers overlap the depth target"); + writeShader(memory, VertexHeader, VertexCode, 2, VertexWords); + writeShader(memory, PixelHeader, PixelCode, 1, PixelWords); + writeShader(memory, ImageHeader, ImageCode, 0, ImageWriteWords); + writeShader(memory, FillHeader, FillCode, 0, FillWords); + std::vector expanded(Layers * HtileSliceBytes / sizeof(std::uint32_t), Expanded); + write(memory, Htile, std::span(expanded)); + + AgcDriver::FrameCaptureWriter writer(path); + writer.WriteRange(GuestBase, memory.size(), AgcDriver::FrameRangeKind::Watched, 0, 7); + const auto snapshot = writer.WriteSnapshot(GuestBase, memory); + const std::array overwrite{Expanded, Expanded, Expanded, Expanded}; + if (test.overwrite) writer.WriteDelta(1, 0, Htile + HtileSliceBytes, std::as_bytes(std::span(overwrite))); + std::uint64_t ordinal = 0; + std::uint64_t windowCalls = 0; + const auto emit = [&](AgcDriver::FrameCall call) { + call.ordinal = ++ordinal; + call.timeNs = ordinal * 1000u; + call.thread = 1; + writer.WriteCall(call); + }; + const auto windowed = [&](AgcDriver::FrameCall call) { + emit(std::move(call)); + ++windowCalls; + }; + const auto submit = [&](std::size_t index) { + windowed({.kind = FrameCallKind::Submit, .address = addresses[index], .size = submits[index].size()}); + }; + emit({.kind = FrameCallKind::RegisterShader, .address = VertexHeader}); + emit({.kind = FrameCallKind::RegisterShader, .address = PixelHeader}); + emit({.kind = FrameCallKind::RegisterShader, .address = ImageHeader}); + emit({.kind = FrameCallKind::RegisterShader, .address = FillHeader}); + emit({.kind = FrameCallKind::RegisterVideoOutput, .values = {7}}); + emit({.kind = FrameCallKind::DisplayBuffer, .address = Color, + .values = {0, 0x8000000022000000ull, Width, Height, 0, 0, 0, 0, 0}}); + emit({.kind = FrameCallKind::FrameStart, .values = {1}}); + submit(0); + submit(1); + if (test.overwrite) windowed({.kind = FrameCallKind::Memory, .values = {1}}); + submit(2); + windowed({.kind = FrameCallKind::Flip, .accepted = 1, .cpuFlip = true, .values = {7, UINT64_MAX, 1, 0}}); + emit({.kind = FrameCallKind::End, .accepted = 2}); + writer.Finish("{\"magic\":\"aps5-frame-capture 1\",\"arena_base\":65536,\"arena_bytes\":1082331693056," + "\"start_boundary\":1,\"frames\":1,\"calls\":" + std::to_string(windowCalls) + + ",\"prologue_calls\":6,\"ranges\":1,\"snapshot_bytes\":" + std::to_string(snapshot) + + ",\"unreadable_bytes\":0,\"host_only_sample_bytes\":0,\"warnings\":[]}\n"); +} + +std::string readFile(const std::filesystem::path& path) { + std::ifstream stream(path, std::ios::binary); + return {std::istreambuf_iterator(stream), std::istreambuf_iterator()}; +} + +std::string quote(const std::filesystem::path& path) { + return "\"" + path.string() + "\""; +} + +struct Replay { + bool completed = false; + std::string log; + std::string frame; +}; + +Replay replay(const std::filesystem::path& tool, const std::filesystem::path& root, const Case& test) { + const auto directory = root / test.name; + std::filesystem::create_directories(directory); + makeCapture(directory / "capture", test); + const auto log = directory / "replay.log"; + const auto frames = directory / "frames"; + const auto command = quote(tool) + " " + quote(directory / "capture") + + " --strict --no-synthesize --repeat 1 --cold-pipelines --frames " + quote(frames) + " > " + + quote(log) + " 2>&1"; + std::fflush(nullptr); +#ifdef _WIN32 + const int status = std::system(('"' + command + '"').c_str()); +#else + const int status = std::system(command.c_str()); +#endif + Replay result; + result.log = readFile(log); + result.frame = readFile(frames / "replay-0.bmp"); + result.completed = status == 0 && result.frame.size() == 54 + std::size_t{Width} * Height * 4; + return result; +} + +std::string half(const std::string& frame, bool right) { + std::string pixels; + for (std::uint32_t y = 0; y < Height; ++y) { + const auto row = 54 + std::size_t{y} * Width * 4; + pixels += frame.substr(row + (right ? Width / 2u * 4u : 0u), Width / 2u * 4u); + } + return pixels; +} + +void printTail(const std::string& log) { + constexpr std::size_t TailBytes = 4000; + std::cerr << (log.size() > TailBytes ? log.substr(log.size() - TailBytes) : log) << '\n'; +} + +void printVulkanDiagnostics(std::string_view log) { + constexpr std::string_view layer = "Insert instance layer \"VK_LAYER_KHRONOS_validation\""; + while (!log.empty()) { + const auto end = log.find('\n'); + const auto line = log.substr(0, end); + if (line.find("VUID-") != std::string_view::npos || line.find(layer) != std::string_view::npos || + line.find("was not found but was requested by env var VK_INSTANCE_LAYERS") != std::string_view::npos) { + std::cout << " " << line << '\n'; + } + if (end == std::string_view::npos) break; + log.remove_prefix(end + 1); + } +} + +} + +int main(int argc, char** argv) { + try { + if (argc != 2) throw std::runtime_error("usage: kyty_shim_depth_meta_fill_tests "); + const std::filesystem::path tool = argv[1]; + const auto root = std::filesystem::temp_directory_path() / + ("kyty-depth-meta-fill-" + std::to_string(std::chrono::steady_clock::now().time_since_epoch().count())); + std::filesystem::create_directories(root); + const bool vulkan_required = std::getenv("ANYPS5_REQUIRE_VULKAN") != nullptr; +#if defined(_WIN32) + _putenv_s("KYTY_PRINTF_DIRECTION", "Console"); +#else + setenv("KYTY_PRINTF_DIRECTION", "Console", 1); +#endif + std::array results; + for (std::size_t index = 0; index < Cases.size(); ++index) { + results[index] = replay(tool, root, Cases[index]); + printVulkanDiagnostics(results[index].log); + if (!results[index].completed) { + std::cerr << Cases[index].name << " replay did not complete" + << (index == 0 && !vulkan_required ? "; skipping (no usable Vulkan device?)" : "") << '\n'; + printTail(results[index].log); + return index == 0 && !vulkan_required ? 77 : 1; + } + } + const auto& kept = results[0].frame; + const auto lit = [&](std::size_t index, bool right) { return half(results[index].frame, right) != half(kept, right); }; + std::vector failures; + if (half(kept, false) == half(results[1].frame, false) || half(kept, true) == half(results[1].frame, true)) { + failures.emplace_back("a fill that clears the HTile of both layers did not clear both layers at the bind"); + } + if (!lit(2, false) || lit(2, true)) { + failures.emplace_back("a fill of the first layer's HTile did not clear exactly the first layer"); + } + if (lit(3, true)) { + failures.emplace_back("a host store into the second layer's HTile after the fill did not keep that layer's depth"); + } + if (lit(3, false)) { + failures.emplace_back("after a host store into its range, the fill's record still cleared the first layer, so the fill " + "was not recorded as a fill on the GPU"); + } + for (std::size_t index = 0; index < Cases.size(); ++index) { + if (Cases[index].image && results[index].log.find(ConsumedFill) != std::string::npos) { + failures.emplace_back("a fill over a registered HTile range was consumed instead of running on the GPU"); + break; + } + } + if (results[4].log.find(ConsumedFill) == std::string::npos) { + failures.emplace_back("a fill over an unregistered HTile range printed no consumed fill, so the check that the other " + "fills ran on the GPU cannot fail"); + } + for (const auto& failure : failures) std::cerr << failure << '\n'; + if (!failures.empty()) { + for (const auto& result : results) printTail(result.log); + return 1; + } + std::filesystem::remove_all(root); + std::cout << "kyty_shim_depth_meta_fill: ok\n"; + return 0; + } catch (const std::exception& error) { + std::cerr << error.what() << '\n'; + return 1; + } +} diff --git a/core/libs/prx/libSceAgcDriver/KytyShim/tests/ImageWriteBackAlias.cpp b/core/libs/prx/libSceAgcDriver/KytyShim/tests/ImageWriteBackAlias.cpp index 806d944532..7614cf7abb 100644 --- a/core/libs/prx/libSceAgcDriver/KytyShim/tests/ImageWriteBackAlias.cpp +++ b/core/libs/prx/libSceAgcDriver/KytyShim/tests/ImageWriteBackAlias.cpp @@ -35,6 +35,22 @@ struct TextureCacheTestAccess { Common::ScopedLock lock {cache.m_lock}; return cache.DownloadImageMemory(image); } + + static void CommitGpuWrite(TextureCache& cache, ImageId image) { + Common::ScopedLock lock {cache.m_lock}; + cache.CommitGpuWrite(cache.m_slot_images[image]); + } + + static bool Watched(TextureCache& cache, uint64_t address) { + return cache.m_page_manager.IsWatched(address); + } + + static std::array ApplyPendingClears(TextureCache& cache, const ImageInfo& info) { + Common::ScopedLock lock {cache.m_lock}; + TextureCache::MetaDataInfo meta {}; + cache.ApplyPendingMetaClears(info, meta); + return {meta.clear_mask.test(0), meta.clear_mask.test(1)}; + } }; } @@ -56,6 +72,292 @@ constexpr uint32_t CpuValue = 0x5aa5c33c; constexpr uint64_t MultisampleGuestBytes = 0x100000; constexpr uint64_t MultisampleAlignment = 0x10000; +constexpr uint64_t DepthGuestBytes = 0x100000; + +const char* CheckFilledMetaClearReachesBind(GraphicContext& graphics, uint64_t base) { + RenderContext renderer(graphics); + CommandProcessor producer(renderer, 0); + producer.Reset(); + auto& scheduler = renderer.GetCommandScheduler(); + auto& textures = renderer.GetTextureCache(); + auto& buffers = renderer.GetBufferCache(); + scheduler.Begin(producer.GetCtx(), producer.GetUcfg(), producer.GetShCtx()); + + constexpr uint32_t Width = 64; + constexpr uint32_t Height = 64; + constexpr uint32_t Layers = 2; + constexpr uint64_t SliceBytes = 0x400; + constexpr uint64_t MetaBytes = SliceBytes * Layers; + constexpr uint64_t Stride = 0x8000; + constexpr uint64_t MetaOffset = 0x6000; + constexpr uint64_t SourceOffset = 0x7000; + constexpr uint64_t WriteBytes = 16; + constexpr uint32_t Cases = 28; + static_assert(Stride * Cases <= DepthGuestBytes); + constexpr uint32_t Expanded = 0xffffffffu; + constexpr uint32_t StencilCleared = 0xf0u; + constexpr uint32_t StencilKept = 0x100u; + const std::vector backing(DepthGuestBytes / sizeof(uint32_t), Expanded); + if (!Libs::LibKernel::Memory::TryWriteBacking(base, backing.data(), DepthGuestBytes)) { + return "could not write the depth backing"; + } + uint64_t next = base; + const auto bind = [&](const auto& between) { + const auto depth_address = next; + const auto meta_address = next + MetaOffset; + next += Stride; + between(meta_address, depth_address + SourceOffset); + ImageInfo info; + info.data.address = depth_address; + info.pixel_format = vk::Format::eD16Unorm; + info.guest_format = Prospero::BufferFormat::k16UNorm; + info.extent = vk::Extent3D {Width, Height, 1}; + info.pitch = Width; + info.bytes_per_block = sizeof(uint16_t); + info.resources = {1, Layers}; + info.UpdateSize(); + info.metadata.kind = ImageMetadataKind::Htile; + info.metadata.range = GuestRange {meta_address, MetaBytes}; + info.htile_initial_clear = false; + const auto id = TextureCacheTestAccess::Create(textures, info); + TextureCache::ImageDesc desc {.info = info}; + desc.type = TextureCache::BindingType::DepthTarget; + desc.view_info.format = info.pixel_format; + desc.view_info.type = vk::ImageViewType::e2DArray; + desc.view_info.aspect = vk::ImageAspectFlagBits::eDepth; + desc.view_info.base_level = 0; + desc.view_info.level_count = 1; + desc.view_info.base_layer = 0; + desc.view_info.layer_count = Layers; + desc.view_info.usage = vk::ImageUsageFlagBits::eDepthStencilAttachment; + (void)textures.FindDepthTarget(id, desc, nullptr); + return std::array {textures.IsMetaCleared(meta_address, 0), textures.IsMetaCleared(meta_address, 1)}; + }; + const auto fill = [&](uint64_t address, uint64_t size, uint32_t value) { + buffers.FillBuffer(address, size, value, false); + }; + const auto gpu_write = [&](uint64_t address, uint64_t size) { + (void)buffers.ObtainBuffer(address, size, true, false); + }; + const std::array overwrite {1, 2, 3, 4}; + const auto none = std::array {false, false}; + const auto both = std::array {true, true}; + const auto first = std::array {true, false}; + const auto second = std::array {false, true}; + const char* failure = nullptr; + const auto expect = [&failure](std::array actual, std::array wanted, const char* message) { + if (failure == nullptr && actual != wanted) failure = message; + }; + expect(bind([&](uint64_t meta, uint64_t) { fill(meta, MetaBytes, 0); }), both, + "a fill that clears the HTile of both layers before the bind did not clear them"); + expect(bind([&](uint64_t meta, uint64_t) { fill(meta, SliceBytes, 0); }), first, + "a fill of the first layer's HTile did not clear exactly that layer"); + expect(bind([&](uint64_t meta, uint64_t) { fill(meta + SliceBytes, SliceBytes, 0); }), second, + "a fill of the second layer's HTile did not clear exactly that layer"); + expect(bind([&](uint64_t meta, uint64_t) { fill(meta, MetaBytes, Expanded); }), none, + "a fill that does not clear the HTile cleared it"); + expect(bind([&](uint64_t meta, uint64_t) { + fill(meta, MetaBytes, 0); + fill(meta + SliceBytes, WriteBytes, Expanded); + }), + none, "a clear overwritten by a DMA fill before the bind was kept"); + expect(bind([&](uint64_t meta, uint64_t) { + fill(meta, MetaBytes, 0); + std::memcpy(reinterpret_cast(meta), overwrite.data(), sizeof(overwrite)); + }), + second, "a clear overwritten by a host store before the bind was kept for the overwritten layer"); + expect(bind([&](uint64_t meta, uint64_t) { + gpu_write(meta, MetaBytes); + fill(meta, MetaBytes, 0); + }), + both, "a GPU-side fill that clears the HTile before the bind did not clear it"); + expect(bind([&](uint64_t meta, uint64_t) { + gpu_write(meta, MetaBytes); + fill(meta, MetaBytes, 0); + gpu_write(meta + SliceBytes, WriteBytes); + }), + none, "a clear overwritten by a written buffer binding before the bind was kept"); + expect(bind([&](uint64_t meta, uint64_t source) { + gpu_write(meta, MetaBytes); + fill(meta, MetaBytes, 0); + buffers.CopyBuffer(meta + SliceBytes, source, WriteBytes, false, false); + }), + none, "a clear overwritten by a DMA copy before the bind was kept"); + expect(bind([&](uint64_t meta, uint64_t) { + fill(meta, MetaBytes, 0); + textures.RunGarbageCollector(); + }), + both, "a clear from the previous GC tick was not kept"); + expect(bind([&](uint64_t meta, uint64_t) { + fill(meta, MetaBytes, 0); + textures.RunGarbageCollector(); + textures.RunGarbageCollector(); + }), + none, "a clear older than one GC tick was kept"); + expect(bind([&](uint64_t meta, uint64_t) { + fill(meta, MetaBytes, 0); + textures.UnmapMemory(meta, MetaBytes); + }), + none, "a clear in memory unmapped before the bind was kept"); + const auto stencil = [&](uint32_t value) { + const auto meta_address = next + MetaOffset; + next += Stride; + fill(meta_address, MetaBytes, value); + ImageInfo info; + info.resources = {1, Layers}; + info.metadata.kind = ImageMetadataKind::Htile; + info.metadata.range = GuestRange {meta_address, MetaBytes}; + info.metadata.stencil_compressed = true; + return TextureCacheTestAccess::ApplyPendingClears(textures, info); + }; + expect(stencil(StencilCleared), both, + "a fill that clears depth and stencil HTile did not clear stencil-compressed metadata"); + expect(stencil(StencilKept), none, "a fill that keeps stencil memory cleared stencil-compressed metadata"); + const auto pending = [&](uint64_t meta) { + ImageInfo info; + info.resources = {1, Layers}; + info.metadata.kind = ImageMetadataKind::Htile; + info.metadata.range = GuestRange {meta, MetaBytes}; + return TextureCacheTestAccess::ApplyPendingClears(textures, info); + }; + const auto slot = [&]() { + const auto meta = next + MetaOffset; + next += Stride; + return meta; + }; + { + const auto meta = slot(); + textures.NoteMetaFill(meta, MetaBytes, 0, false); + expect(pending(meta), both, "a record noted without a fill in memory that clears the HTile did not clear it"); + } + { + const auto meta = slot(); + textures.NoteMetaFill(meta, MetaBytes, 0, false); + ImageInfo info; + info.data.address = meta; + info.pixel_format = vk::Format::eR32Uint; + info.guest_format = Prospero::BufferFormat::k32UInt; + info.extent = vk::Extent3D {static_cast(MetaBytes / sizeof(uint32_t)), 1, 1}; + info.pitch = static_cast(MetaBytes / sizeof(uint32_t)); + info.UpdateSize(); + TextureCacheTestAccess::CommitGpuWrite(textures, TextureCacheTestAccess::Create(textures, info)); + expect(pending(meta), none, "a clear overwritten by an image write before the bind was kept"); + } + { + const auto meta = next + MetaOffset; + (void)bind([](uint64_t, uint64_t) {}); + textures.NoteMetaFill(meta - SliceBytes, MetaBytes + SliceBytes, 0, false); + expect(pending(meta), none, "a fill that overlaps a live metadata entry without starting at it was recorded"); + textures.NoteMetaFill(meta + SliceBytes, SliceBytes, 0, false); + expect(pending(meta), none, "a fill inside a live metadata entry was recorded"); + } + const auto watched = [&](uint64_t meta) { return TextureCacheTestAccess::Watched(textures, meta); }; + { + const auto meta = slot(); + textures.NoteMetaFill(meta, MetaBytes, 0, false); + textures.NoteMetaFill(meta, MetaBytes, 0, false); + const bool held = watched(meta); + expect(pending(meta), both, "a replaced record of a fill on the GPU did not clear the HTile"); + expect({held, watched(meta)}, first, + "a record of a fill on the GPU did not write-protect its range exactly until it was applied"); + } + { + const auto meta = slot(); + textures.NoteMetaFill(meta, MetaBytes, 0, true); + expect({watched(meta), false}, none, "a record of a fill done in memory write-protected its range"); + (void)pending(meta); + } + { + const auto meta = slot(); + textures.NoteMetaFill(meta, MetaBytes, 0, false); + (void)textures.InvalidateMemory(meta + MetaBytes, sizeof(uint32_t)); + expect({watched(meta), false}, none, "a write elsewhere on its page did not release a record's protection"); + expect(pending(meta), none, "a record of a fill on the GPU was kept after a write elsewhere on its page"); + } + { + const auto meta = slot(); + textures.NoteMetaFill(meta, MetaBytes, 0, false); + textures.RunGarbageCollector(); + textures.RunGarbageCollector(); + expect({watched(meta), false}, none, "a record aged out by the GC kept its protection"); + expect(pending(meta), none, "a record of a fill on the GPU older than one GC tick was kept"); + } + { + const auto meta = slot(); + textures.NoteMetaFill(meta, MetaBytes, 0, false); + textures.UnmapMemory(meta, MetaBytes); + expect({watched(meta), false}, none, "a record dropped by an unmap kept its protection"); + expect(pending(meta), none, "a record of a fill on the GPU was kept after an unmap"); + } + { + const auto meta = slot(); + textures.NoteMetaFill(meta, MetaBytes, 0, false); + textures.NoteMetadataWrite(meta + SliceBytes, WriteBytes); + expect({watched(meta), false}, none, "a record dropped by a written binding kept its protection"); + expect(pending(meta), none, "a record of a fill on the GPU was kept after a written binding over it"); + } + { + const auto meta = slot(); + textures.NoteMetaFill(meta, MetaBytes, 0, false); + (void)renderer.HandleFault(PageFaultAccess::Write, meta + MetaBytes); + expect({watched(meta), false}, none, "a write fault elsewhere on its page did not release a record's protection"); + expect(pending(meta), none, "a record of a fill on the GPU was kept after a write fault on its page"); + } + { + const auto meta = slot(); + textures.NoteMetaFill(meta, SliceBytes, 0, false); + textures.NoteMetaFill(meta + SliceBytes, SliceBytes, 0, false); + ImageInfo info; + info.resources = {1, 1}; + info.metadata.kind = ImageMetadataKind::Htile; + info.metadata.range = GuestRange {meta, SliceBytes}; + const bool applied = TextureCacheTestAccess::ApplyPendingClears(textures, info)[0]; + const bool held = watched(meta); + textures.NoteMetadataWrite(meta + SliceBytes, WriteBytes); + expect({applied, held}, both, "two records of fills on the GPU on one page did not hold it until both were gone"); + expect({watched(meta), false}, none, "two records of fills on the GPU on one page left it protected"); + } + { + constexpr uint32_t Records = 300; + const auto meta = slot(); + for (uint32_t record = 0; record < Records; ++record) { + textures.NoteMetaFill(meta + record * sizeof(uint32_t), sizeof(uint32_t), 0, false); + } + const bool held = watched(meta); + textures.NoteMetadataWrite(meta, Records * sizeof(uint32_t)); + expect({held, watched(meta)}, first, "300 records of fills on the GPU on one page did not hold it exactly until dropped"); + } + { + constexpr uint64_t SpanBytes = 0x2000; + const auto middle = slot(); + const auto start = middle - 2 * SliceBytes; + const auto tail = start + SpanBytes; + textures.NoteMetaFill(start, SpanBytes, 0, false); + textures.NoteMetaFill(tail, SliceBytes, 0, false); + expect({watched(start), watched(middle)}, both, + "a record of a fill on the GPU over three pages did not protect its first and middle pages"); + expect({watched(tail), false}, first, "a record of a fill on the GPU over three pages did not protect its last page"); + textures.NoteMetadataWrite(start, WriteBytes); + expect({watched(start), watched(middle)}, none, + "a dropped record over three pages left its first or middle page protected"); + expect({watched(tail), false}, first, + "a dropped record over three pages released its last page while another record held it"); + textures.NoteMetadataWrite(tail, WriteBytes); + expect({watched(tail), false}, none, "the last record on a shared page left it protected after it was dropped"); + } + expect(bind([&](uint64_t meta, uint64_t) { + fill(meta, SliceBytes, 0); + fill(meta + SliceBytes, SliceBytes, 0); + }), + both, "fills in memory of both layers' HTile on one page did not clear both layers"); + const auto tick = scheduler.CurrentTick(); + scheduler.Wait(tick); + scheduler.WaitPriorityOperations(tick); + BufferCacheTestAccess::DiscardGpuWrites(buffers, base, DepthGuestBytes); + (void)buffers.DropFreedRange(base, DepthGuestBytes, nullptr, nullptr); + return failure; +} + const char* CheckWriteBackOrder(GraphicContext& graphics, uint64_t address) { RenderContext renderer(graphics); CommandProcessor producer(renderer, 0); @@ -595,6 +897,18 @@ extern "C" int RunKytyImageWriteBackAliasTest() { if (failure == nullptr) { failure = CheckRangePicksLatestWrite(graphics, address + GuestBytes / 8 * 7); } + if (failure == nullptr) { + void* depth_guest = nullptr; + if (sceKernelMapFlexibleMemory(&depth_guest, DepthGuestBytes, CpuReadWrite, 0) != 0 || depth_guest == nullptr) { + failure = "could not map the depth backing"; + } else { + const auto depth_address = reinterpret_cast(depth_guest); + failure = CheckFilledMetaClearReachesBind(graphics, depth_address); + if (sceKernelMunmap(depth_address, DepthGuestBytes) != 0 && failure == nullptr) { + failure = "could not unmap the depth backing"; + } + } + } if (sceKernelMunmap(address, GuestBytes) != 0) { std::fputs("kyty_shim_image_write_back_alias: FAILED: could not unmap guest backing\n", stderr); return 1; diff --git a/tools/lavapipe_skip.txt b/tools/lavapipe_skip.txt index 77bbd5a0e8..e8aae6d9c4 100644 --- a/tools/lavapipe_skip.txt +++ b/tools/lavapipe_skip.txt @@ -18,3 +18,4 @@ kyty_shim_cross_queue_recycled_label same device requirement as kyty_shim_depth_ kyty_shim_cross_queue_early_label same device requirement as kyty_shim_depth_target_alias kyty_shim_cross_queue_recycled_label_own_tick same device requirement as kyty_shim_depth_target_alias kyty_shim_wave_split_written_reads same device requirement as kyty_shim_depth_target_alias, and the wave64 split it checks needs subgroups of 32 +kyty_shim_depth_meta_fill same device requirement as kyty_shim_depth_target_alias