diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/DepthSurface.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/DepthSurface.hpp index 4aef2f7de7a7..b6412da5df64 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/DepthSurface.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/DepthSurface.hpp @@ -107,6 +107,7 @@ std::optional ActiveDepthExtent(VkDevice device, std::uint64_t addre std::shared_ptr DepthSurfaceFirstSample(const Context& context, std::span words, const GuestTextureResource& resource, VkComponentMapping components); std::size_t DepthPlaneCopyCount(); VkDeviceSize DepthPlaneCopyBytes(); +VkDeviceSize DepthPlaneCopyBudget(const VkPhysicalDeviceMemoryProperties& memory); VkFormat HostDepthFormat(const Context& context, VkFormat format); float HostDepthBiasConstant(const Context& context, VkFormat format, float constant); std::shared_ptr DepthSurfaceStorage(const Context& context, std::span words, const GuestTextureResource& resource, std::uint32_t mip); diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/DepthSurface.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/DepthSurface.cpp index 660eddfc0f94..b061be10f4e7 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/DepthSurface.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/DepthSurface.cpp @@ -19,6 +19,7 @@ #include "prx/libSceAgcDriver/Graphics/include/TextureFormat.hpp" #include "prx/libSceAgcDriver/Graphics/include/TextureDetiler.hpp" #include "prx/libSceAgcDriver/Graphics/include/TextureTiling.hpp" +#include "prx/libSceAgcDriver/Graphics/include/UnitShadow.hpp" #include "prx/libSceAgcDriver/Graphics/include/GuestBufferMemory.hpp" #include "prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp" #include "prx/libSceAgcDriver/Execution/include/Mutex.hpp" @@ -30,6 +31,7 @@ #include #include #include +#include #include #include #include @@ -929,6 +931,8 @@ std::pair staleStencilRange(const DepthSurface& su void noteStalePlane(std::uint64_t begin, std::uint64_t end); std::uint64_t nextPlaneSerial(); +enum class DepthMemoryUse { Bind, Sample, Store }; + class DepthSurface { public: DepthSurface(const Context& context, const DepthTarget& target, DepthSamplingState sampling = {}) : context(context), target(target), hostFormat(HostDepthFormat(context, target.format)), sampling(std::move(sampling)) { @@ -1857,10 +1861,10 @@ class DepthSurface { } } - std::vector WrittenUnits(const GuestTextureResource& resource, std::uint64_t& generation) { + std::vector WrittenUnits(const GuestTextureResource& resource, std::uint64_t& generation, DepthMemoryUse use = DepthMemoryUse::Bind) { const auto bytes = static_cast(MirrorBytes()); SizeUnits(bytes); - const auto collected = GuestMemory::CollectWrites(resource.baseAddress, bytes); + const auto collected = use == DepthMemoryUse::Sample ? GuestMemory::CollectWritesUncached(resource.baseAddress, bytes) : GuestMemory::CollectWrites(resource.baseAddress, bytes); generation = GuestMemory::TrackerGeneration(); std::vector changed; const auto mark = [&](std::size_t unit) { @@ -1910,16 +1914,16 @@ class DepthSurface { return changed; } - void SyncFromMemory(const GuestTextureResource& resource, bool storing = false) { + void SyncFromMemory(const GuestTextureResource& resource, DepthMemoryUse use = DepthMemoryUse::Bind) { std::uint64_t generation = 0; - const auto changed = WrittenUnits(resource, generation); + const auto changed = WrittenUnits(resource, generation, use); // The registry generation moves on every mapping mutation, so an unchanged value means every recorded backing is still current. Read it before the lookups: a mutation racing them leaves the stored value old and the next sync refreshes again. if (const auto registryGeneration = GuestAllocations::GuestAllocationsGeneration_nid_postfix(); registryGeneration != backingGeneration) { for (std::size_t unit = 0; unit < unitBacking.size(); ++unit) unitBacking[unit] = RegisteredBacking(target.address + unit * unitBytes); backingGeneration = registryGeneration; } const bool clearing = (pendingClear & VK_IMAGE_ASPECT_DEPTH_BIT) != 0; - if ((clearing && !storing) || !anyUnit(changed)) { + if ((clearing && use != DepthMemoryUse::Store) || !anyUnit(changed)) { unitGeneration.assign(unitGeneration.size(), generation); return; } @@ -2659,12 +2663,10 @@ class DepthPlaneCopy { DepthPlaneCopy(const DepthPlaneCopy&) = delete; DepthPlaneCopy& operator=(const DepthPlaneCopy&) = delete; - std::shared_ptr Refresh(std::span slices, const GuestTextureResource& resource, VkComponentMapping components, VkImageViewType viewType, std::uint32_t baseLayer) { + std::shared_ptr Refresh(std::span slices, const GuestTextureResource& resource, const SurfaceGeometry& geometry, VkComponentMapping components, VkImageViewType viewType, std::uint32_t baseLayer) { const auto requested = static_cast(slices.size()); Require(requested != 0 && requested <= layers, "depth plane copy slices exceed its layers"); Require(baseLayer < requested, "a depth plane copy view starts past the slices it was given"); - const auto geometry = DescribeSurface(resource); - Require(!geometry.levelMajor, "depth planes of a PS4 layered surface with several mip levels (stored level by level) are not implemented"); const bool guestFill = std::any_of(slices.begin(), slices.end(), [](const auto& slice) { return slice.image == VK_NULL_HANDLE; }); if (guestFill && (geometry.layers != requested || geometry.sliceLinearBytes < sliceBytes() || geometry.mips.empty())) { char text[320]; @@ -2674,34 +2676,47 @@ class DepthPlaneCopy { const auto stagingBytes = std::max(static_cast(geometry.sliceLinearBytes), static_cast(sliceBytes())) * requested; std::vector> uploads; std::vector uploadLayers; + std::vector uploadedGuests; std::vector copiedLayers; for (std::uint32_t layer = 0; layer < requested; ++layer) { auto& held = guestLayers[layer]; - auto& surface = surfaceLayers[layer]; + const auto& surface = surfaceLayers[layer]; if (slices[layer].image != VK_NULL_HANDLE) { - held = {}; if (slices[layer].written != 0 && surface.image == slices[layer].image && surface.written == slices[layer].written) continue; - surface = slices[layer]; copiedLayers.push_back(layer); continue; } - surface = {}; - GuestLayer current{resource.baseAddress + geometry.GuestLayerOffset(layer), geometry.layerBytes, resource.tileMode, geometry.thick, GuestMemory::CollectWrites(resource.baseAddress + geometry.GuestLayerOffset(layer), static_cast(geometry.layerBytes))}; - current.uncommitted = current.generation == 0 && GuestMemory::CommittedRanges(current.address, static_cast(current.bytes)).empty(); - const bool unchanged = current.uncommitted ? held.uncommitted : held.generation != 0 && GuestMemory::UnchangedSince(current.address, static_cast(current.bytes), held.generation); - if (held.address == current.address && held.bytes == current.bytes && held.tileMode == current.tileMode && held.thick == current.thick && !Recorder::SnapshotWriteOverlaps(current.address, static_cast(current.bytes)) && unchanged) { + const auto address = resource.baseAddress + geometry.GuestLayerOffset(layer); + const auto bytes = static_cast(geometry.layerBytes); + const auto stored = FlushDepthPlanes(address, bytes); + const auto forget = GuestMemory::ForgetStamp(address, bytes); + GuestLayer current{GuestMemory::CollectWritesUncached(address, bytes), forget}; + current.uncommitted = current.generation == 0 && GuestMemory::CommittedRanges(address, bytes).empty(); + const bool unchanged = current.uncommitted ? held.uncommitted : held.generation != 0 && GuestMemory::UnchangedSince(address, bytes, held.generation); + const std::pair range{address, address + bytes}; + if (unchanged && held.forget == forget && stored.empty() && !Recorder::SnapshotWriteOverlaps(address, bytes) + && !AnyShadowedOverlaps(address, bytes) && !StorageTexture::AnyPendingUnitsOverlap(std::span(&range, 1u))) { held.generation = current.generation; continue; } - auto upload = std::make_shared(context, static_cast(geometry.layerBytes), VK_BUFFER_USAGE_STORAGE_BUFFER_BIT); - GuestMemory::ReadCommitted(current.address, upload->Bytes().first(static_cast(geometry.layerBytes))); + auto upload = std::make_shared(context, bytes, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT); + GuestMemory::ReadCommitted(address, upload->Bytes().first(bytes)); uploads.push_back(std::move(upload)); uploadLayers.push_back(layer); - held = current; + uploadedGuests.push_back(current); } if (!copiedLayers.empty() || !uploads.empty()) { if (staging == nullptr || stagingBytes > staging->Size()) staging = std::make_shared(context, stagingBytes, VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT); record(slices, resource, geometry, copiedLayers, uploads, uploadLayers, staging); + for (const auto layer : copiedLayers) { + surfaceLayers[layer] = slices[layer]; + guestLayers[layer] = {}; + } + for (std::size_t upload = 0; upload < uploadLayers.size(); ++upload) { + const auto layer = uploadLayers[upload]; + guestLayers[layer] = uploadedGuests[upload]; + surfaceLayers[layer] = {}; + } } const auto viewLayers = viewType == VK_IMAGE_VIEW_TYPE_2D ? 1u : requested - baseLayer; const std::array key{static_cast(components.r), static_cast(components.g), static_cast(components.b), static_cast(components.a), static_cast(viewType), baseLayer, viewLayers}; @@ -2724,11 +2739,8 @@ class DepthPlaneCopy { private: struct GuestLayer { - std::uint64_t address = 0; - std::uint64_t bytes = 0; - TextureTileMode tileMode = TextureTileMode::kLinear; - bool thick = false; std::uint64_t generation = 0; + std::uint64_t forget = 0; bool uncommitted = false; }; @@ -2771,7 +2783,7 @@ class DepthPlaneCopy { RecordMemoryBarrier(context, commands, VK_PIPELINE_STAGE_HOST_BIT | VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_ACCESS_HOST_WRITE_BIT | VK_ACCESS_TRANSFER_WRITE_BIT, VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT); for (std::size_t upload = 0; upload < uploads.size(); ++upload) { const auto layer = uploadLayers[upload]; - context.detiler->Dispatch(commands, resource.tileMode, format == VK_FORMAT_D32_SFLOAT ? 4u : 2u, uploads[upload]->Handle(), 0, staging->Handle(), geometry.LinearLayerOffset(layer), geometry.mips.front(), false, layer, geometry.thick); + context.detiler->Dispatch(commands, resource.tileMode, format == VK_FORMAT_D32_SFLOAT ? 4u : 2u, uploads[upload]->Handle(), mip.tiledOffset, staging->Handle(), geometry.LinearLayerOffset(layer) + mip.linearOffset, mip, false, layer, geometry.thick, {.pipeBankXor = resource.pipeBankXor}); regions.push_back(region(layer, aspect(), layer)); } if (recorder != nullptr) { @@ -2826,8 +2838,26 @@ class DepthPlaneCopy { } }; -std::map, std::unique_ptr>& planeCopies() { - static auto* copies = new std::map, std::unique_ptr>(); +struct DepthPlaneCopyKey { + VkDevice device; + std::uint64_t address; + std::uint32_t width; + std::uint32_t height; + VkFormat imageFormat; + TextureTileMode tileMode; + std::uint32_t pipeBankXor; + std::uint64_t layerBytes; + std::uint32_t mipCount; + std::uint32_t gcnPitch; + bool gcnPow2Pad; + bool gcnLinearGeneral; + std::uint32_t linearPitch; + + auto operator<=>(const DepthPlaneCopyKey&) const = default; +}; + +std::map>& planeCopies() { + static auto* copies = new std::map>(); return *copies; } @@ -2836,22 +2866,26 @@ std::uint64_t& planeCopyClock() { return clock; } -void evictPlaneCopies(const std::tuple& keep) { - static const VkDeviceSize budget = [] { +void evictPlaneCopies(const VkPhysicalDeviceMemoryProperties& memory, const DepthPlaneCopyKey& keep) { + static const auto overrideBudget = []() -> std::optional { const char* text = std::getenv("APS5_DEPTH_PLANE_COPY_MIB"); - return static_cast(text != nullptr ? std::strtoull(text, nullptr, 10) : 256ull) << 20u; + if (text == nullptr) return std::nullopt; + return static_cast(std::strtoull(text, nullptr, 10)) << 20u; }(); + const auto budget = overrideBudget ? *overrideBudget : DepthPlaneCopyBudget(memory); if (budget == 0) return; auto& copies = planeCopies(); VkDeviceSize total = 0; - for (const auto& entry : copies) total += entry.second->HeldBytes(); + for (const auto& [key, copy] : copies) { + if (key.device == keep.device) total += copy->HeldBytes(); + } const auto present = Recorder::Presents(); const auto ceiling = budget + std::min(budget, std::numeric_limits::max() - budget); while (total > budget) { const bool over = total > ceiling; auto oldest = copies.end(); for (auto it = copies.begin(); it != copies.end(); ++it) { - if (it->first == keep || (!over && it->second->lastPresent + 1u >= present)) continue; + if (it->first.device != keep.device || it->first == keep || (!over && it->second->lastPresent + 1u >= present)) continue; if (oldest == copies.end() || it->second->lastUse < oldest->second->lastUse) oldest = it; } if (oldest == copies.end()) break; @@ -3050,13 +3084,13 @@ void takePlanes(DepthSurface& surface, bool created, VkImageAspectFlags clearAsp } DepthSurface* depthSlice(VkDevice device, std::uint64_t address, const DepthTarget& base) { - if (const auto found = depthOwners().find({device, address}); found != depthOwners().end()) { - const auto& target = found->second.surface->target; - if (found->second.surface->active->load(std::memory_order_acquire) && target.extent.width == base.extent.width && target.extent.height == base.extent.height && target.format == base.format) return found->second.surface; - } - const auto& list = surfaces(); - const auto slice = std::find_if(list.rbegin(), list.rend(), [&](const auto& surface) { return surface->active->load(std::memory_order_acquire) && surface->context.device == device && !surface->retired && surface->target.address == address && surface->target.extent.width == base.extent.width && surface->target.extent.height == base.extent.height && surface->target.format == base.format; }); - return slice == list.rend() ? nullptr : slice->get(); + const auto found = depthOwners().find({device, address}); + if (found == depthOwners().end()) return nullptr; + auto* surface = found->second.surface; + if (!surface->active->load(std::memory_order_acquire) || surface->retired) return nullptr; + const auto& target = surface->target; + if (target.samples != 1u || target.extent.width != base.extent.width || target.extent.height != base.extent.height || target.format != base.format) return nullptr; + return surface; } DepthSurface* planeSurface(VkDevice device, std::uint64_t address) { @@ -4280,7 +4314,7 @@ std::vector> FlushDepthPlanes(std::uint6 if (!surface->AnyStale()) continue; } GuestMemory::CollectWritesUncached(plane, static_cast(planeBytes)); - surface->SyncFromMemory(resource, true); + surface->SyncFromMemory(resource, DepthMemoryUse::Store); auto units = scope == DepthPlaneScope::Whole ? surface->staleUnits : surface->StaleUnitsIn(planeBytes, address, end); if (anyUnit(units)) { auto mirror = surface->StoreDepthPlane(resource, units); @@ -4571,7 +4605,7 @@ void ClearDepthSurfaces(VkDevice device) { std::erase_if(surfaces(), [&](const auto& surface) { return surface->context.device == device; }); std::erase_if(expandWrites(), [&](const auto& entry) { return entry.first.first == device; }); std::erase_if(unstoredExpands(), [&](const auto& entry) { return entry.first.first == device; }); - std::erase_if(planeCopies(), [&](const auto& entry) { return std::get<0>(entry.first) == device; }); + std::erase_if(planeCopies(), [&](const auto& entry) { return entry.first.device == device; }); std::erase_if(layeredStorages(), [&](const auto& entry) { return std::get<0>(entry.first) == device; }); { std::lock_guard passesLock(depthToStoragePassesMutex()); @@ -4601,6 +4635,15 @@ VkDeviceSize DepthPlaneCopyBytes() { return total; } +VkDeviceSize DepthPlaneCopyBudget(const VkPhysicalDeviceMemoryProperties& memory) { + constexpr VkDeviceSize step = 256ull << 20u; + constexpr VkDeviceSize heapPerStep = 16u * step; + const auto heap = LargestDeviceLocalHeap(memory); + const auto bytes = heap ? memory.memoryHeaps[*heap].size : 0; + const auto steps = bytes / heapPerStep + (bytes % heapPerStep != 0); + return std::max(1, steps) * step; +} + namespace { thread_local bool depthCopySourceActive = false; @@ -4669,9 +4712,11 @@ std::shared_ptr DepthSurfaceTexture(const Context& context, std::spanSyncFromMemory(mirrorResource(base)); - found->ApplyFastClear(); - if (sampled) return found->Sampled(words, resource, components, found == drawnDepth); + if (sampled) { + if (!stencil && mirrorable(base)) found->SyncFromMemory(mirrorResource(base)); + found->ApplyFastClear(); + return found->Sampled(words, resource, components, found == drawnDepth); + } Require(found->hostFormat == base.format, "sampling several slices or an integer view of a depth plane that the device stores in another depth format is not implemented"); const auto layers = cube ? std::max(resource.depthOrLastArray + 1u, 6u) : layered ? resource.depthOrLastArray + 1u : 1u; if (!planes) { @@ -4685,23 +4730,31 @@ std::shared_ptr DepthSurfaceTexture(const Context& context, std::spanApplyFastClear(); - if (slice == nullptr) slices.push_back({}); - else slices.push_back({slice->image, slice == drawnDepth ? 0u : slice->written}); + if (slice == nullptr) { + slices.push_back({}); + continue; + } + if (mirrorable(slice->target)) { + const auto bytes = static_cast(slice->MirrorBytes()); + if (auto* recorder = RecorderFor(context); recorder != nullptr && recorder->PendingWriteOverlaps(address, bytes)) recorder->SyncThrough(address, bytes); + slice->SyncFromMemory(mirrorResource(slice->target), DepthMemoryUse::Sample); + } + slice->ApplyFastClear(); + slices.push_back({slice->image, slice == drawnDepth ? 0u : slice->written}); } const auto imageFormat = integer ? VK_FORMAT_R16_UINT : d16 ? VK_FORMAT_D16_UNORM : VK_FORMAT_D32_SFLOAT; const VkExtent2D extent{resource.width, resource.height}; auto& copies = planeCopies(); - const std::tuple copyKey{context.device, base.address, extent.width, extent.height, imageFormat}; + const DepthPlaneCopyKey copyKey{context.device, base.address, extent.width, extent.height, imageFormat, resource.tileMode, resource.pipeBankXor, geometry.layerBytes, resource.mipCount, resource.gcnPitch, resource.gcnPow2Pad, resource.gcnLinearGeneral, resource.linearPitch}; auto& copy = copies[copyKey]; if (copy == nullptr || copy->layers < layers) copy = std::make_unique(context, extent, imageFormat, layers); copy->lastUse = ++planeCopyClock(); copy->lastPresent = Recorder::Presents(); - auto texture = copy->Refresh(slices, resource, components, cube || resource.dimension == TextureDimension::k2DArray ? VK_IMAGE_VIEW_TYPE_2D_ARRAY : VK_IMAGE_VIEW_TYPE_2D, layered && !cube ? resource.baseArray : 0u); + auto texture = copy->Refresh(slices, resource, geometry, components, cube || resource.dimension == TextureDimension::k2DArray ? VK_IMAGE_VIEW_TYPE_2D_ARRAY : VK_IMAGE_VIEW_TYPE_2D, layered && !cube ? resource.baseArray : 0u); if (DepthPlaneReuse() && !texture->HasReuseLookup()) { texture->SetReuseLookup([context, lookupWords = std::vector(words.begin(), words.end()), resource, components] { return DepthSurfaceTexture(context, lookupWords, resource, components); }); } - evictPlaneCopies(copyKey); + evictPlaneCopies(context.memory, copyKey); return texture; } diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_depth_plane_sampling_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_depth_plane_sampling_tests.cmake index de018fd7d9a1..3178abcc6249 100644 --- a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_depth_plane_sampling_tests.cmake +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_depth_plane_sampling_tests.cmake @@ -1,8 +1,15 @@ if(BUILD_TESTING) + add_test(NAME agc_driver_depth_plane_copy_budget COMMAND agc_driver_depth_plane_sampling_tests --budget) add_test(NAME agc_driver_depth_plane_sampling_evicting COMMAND agc_driver_depth_plane_sampling_tests --evicting) set_tests_properties(agc_driver_depth_plane_sampling_evicting PROPERTIES ENVIRONMENT "APS5_DEPTH_PLANE_COPY_MIB=1" SKIP_RETURN_CODE 77 TIMEOUT 120) + add_test(NAME agc_driver_depth_plane_sampling_guest_rewrite COMMAND agc_driver_depth_plane_sampling_tests --guest-rewrite) + add_test(NAME agc_driver_depth_plane_sampling_layout_reuse COMMAND agc_driver_depth_plane_sampling_tests --layout-reuse) + set_tests_properties(agc_driver_depth_plane_sampling_guest_rewrite agc_driver_depth_plane_sampling_layout_reuse + PROPERTIES ENVIRONMENT "APS5_DEPTH_PLANE_COPY_MIB=0;APS5_NO_PIPELINE_JOURNAL=1" SKIP_RETURN_CODE 77 TIMEOUT 30) + set_property(TEST agc_driver_depth_plane_sampling_guest_rewrite APPEND PROPERTY ENVIRONMENT "APS5_NO_HOST_IMPORT=1") + set_tests_properties(agc_driver_depth_plane_copy_budget PROPERTIES TIMEOUT 30) if(WIN32) - set_tests_properties(agc_driver_depth_plane_sampling_evicting PROPERTIES ENVIRONMENT_MODIFICATION + set_tests_properties(agc_driver_depth_plane_copy_budget agc_driver_depth_plane_sampling_evicting agc_driver_depth_plane_sampling_guest_rewrite agc_driver_depth_plane_sampling_layout_reuse PROPERTIES ENVIRONMENT_MODIFICATION "PATH=path_list_prepend:$") endif() endif() diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/DepthPlaneSampling.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/DepthPlaneSampling.cpp index 050881e8e2bc..cc7206e3c147 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/DepthPlaneSampling.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/DepthPlaneSampling.cpp @@ -344,19 +344,61 @@ void GuestDepthBitsCase(AgcDriver::VulkanDevice& device, GuestBlock& block, std: } } -void GuestWriteAfterDrawCase(AgcDriver::VulkanDevice& device, GuestBlock& block, std::span output) { +void GuestWriteAfterDrawCase(AgcDriver::VulkanDevice& device, GuestBlock& block, std::span output, bool layered) { auto* base = block.At(ReloadOffset); if (!AgcDriver::GuestMemory::WriteWatched() || !AgcDriver::GuestMemory::Watched(reinterpret_cast(base), SliceBytes)) { + Require(!layered, "the depth array rewrite requires write-watched guest memory"); std::puts("guest memory has no write watch: the guest write after a draw is not checked"); return; } - const Shape shape{Format32Float, 128, 128, Type2D, 0, Swizzle64KbZX}; - DrawDepth(device, reinterpret_cast(base), {128, 128}, VK_FORMAT_D32_SFLOAT, DrawnDepth, AgcDriver::Graphics::XorSwizzleMode(AgcDriver::Graphics::TextureTileMode::kZ64KBX)); + const Shape shape{Format32Float, 128, 128, layered ? Type2DArray : Type2D, layered ? 1u : 0u, Swizzle64KbZX}; + const auto swizzle = AgcDriver::Graphics::XorSwizzleMode(AgcDriver::Graphics::TextureTileMode::kZ64KBX); + DrawDepth(device, reinterpret_cast(base), {128, 128}, VK_FORMAT_D32_SFLOAT, DrawnDepth, swizzle); + if (layered) DrawDepth(device, reinterpret_cast(base + SliceBytes), {128, 128}, VK_FORMAT_D32_SFLOAT, DrawnDepth, swizzle); Load(device, base, shape, 0, output); Expect(output, Bits(DrawnDepth), "D32 plane sampled after a draw"); + if (layered) { + Load(device, base, shape, 1, output); + Expect(output, Bits(DrawnDepth), "second D32 plane sampled after a draw"); + AgcDriver::Graphics::Recorder::CountPresent(); + } FillSlice(base, SliceBytes, Bits(0.75f), 4u); Load(device, base, shape, 0, output); Expect(output, Bits(0.75f), "D32 plane the guest wrote after a draw, sampled before its surface is bound again"); + if (layered) { + FillSlice(base + SliceBytes, SliceBytes, Bits(0.625f), 4u); + Load(device, base, shape, 1, output); + Expect(output, Bits(0.625f), "second D32 plane the guest wrote after the depth array was copied"); + } +} + +void DepthPlaneLayoutReuseCase(AgcDriver::VulkanDevice& device, GuestBlock& block, std::span output) { + using namespace AgcDriver::Graphics; + auto* base = block.At(ReloadOffset); + constexpr VkExtent2D extent{128, 64}; + DrawDepth(device, reinterpret_cast(base), extent, VK_FORMAT_D32_SFLOAT, DrawnDepth); + const Shape tiled{Format32Float, extent.width, extent.height, Type2DArray, 1, Swizzle64KbZX}; + const Shape linear{Format32Float, extent.width, extent.height, Type2DArray, 1, 0}; + const auto tiledWords = TextureDescriptor(base, tiled); + const auto linearWords = TextureDescriptor(base, linear); + const auto tiledResource = DecodeTextureResource(tiledWords); + const auto linearResource = DecodeTextureResource(linearWords); + const auto tiledBytes = DescribeSurface(tiledResource).layerBytes; + const auto linearBytes = DescribeSurface(linearResource).layerBytes; + Require(tiledBytes >= 2u * linearBytes, "the depth array layouts must place slice 1 at disjoint guest ranges"); + FillSlice(base + tiledBytes, tiledBytes, Bits(0.75f), 4u); + FillSlice(base + linearBytes, linearBytes, Bits(0.5f), 4u); + Load(device, base, tiled, 1, output); + Expect(output, Bits(0.75f), "tiled D32 array slice 1"); + Load(device, base, linear, 1, output); + Expect(output, Bits(0.5f), "linear D32 array slice 1"); + const auto context = AgcDriver::VulkanDeviceTestAccess::ContextOf(device); + const auto tiledTexture = DepthSurfaceTexture(context, tiledWords, tiledResource, {}); + const auto linearTexture = DepthSurfaceTexture(context, linearWords, linearResource, {}); + Require(tiledTexture != nullptr && linearTexture != nullptr && tiledTexture != linearTexture, "depth arrays with different guest layouts share one sampled image"); + if (linearTexture->HasReuseLookup()) Require(linearTexture->ReuseLookupHolds(), "the linear depth array lost its reuse lookup after the tiled lookup"); + Load(device, base, linear, 1, output); + Expect(output, Bits(0.5f), "reused linear D32 array slice 1"); } void FirstSliceCase(AgcDriver::VulkanDevice& device, GuestBlock& block, std::span output) { @@ -514,15 +556,47 @@ void RefusalCase(AgcDriver::VulkanDevice& device, GuestBlock& block) { ExpectRefusal(device, block, CubeOffset, {Format32Float, 128, 128, TypeCube, 5, Swizzle64KbZX}, 1, "base slice 1 is not implemented", "a depth plane cube from base slice 1"); ExpectRefusal(device, block, ArrayOffset, {Format32Float, 128, 128, Type2D, 0, Swizzle64KbZX}, 1, "slice 1 is not implemented", "a 2D depth plane view with a base slice"); } + +void DepthPlaneBudgetCase() { + using AgcDriver::Graphics::DepthPlaneCopyBudget; + constexpr VkDeviceSize MiB = 1ull << 20u; + constexpr VkDeviceSize GiB = 1024u * MiB; + VkPhysicalDeviceMemoryProperties memory{}; + Require(DepthPlaneCopyBudget(memory) == 256u * MiB, "missing heaps must use the depth plane copy budget floor"); + memory.memoryHeapCount = 3; + memory.memoryHeaps[0] = {64u * GiB, 0}; + memory.memoryHeaps[1] = {4u * GiB, VK_MEMORY_HEAP_DEVICE_LOCAL_BIT}; + memory.memoryHeaps[2] = {2u * GiB, VK_MEMORY_HEAP_DEVICE_LOCAL_BIT}; + Require(DepthPlaneCopyBudget(memory) == 256u * MiB, "a 4 GiB device-local heap must use one budget step"); + memory.memoryHeaps[1].size += 1; + Require(DepthPlaneCopyBudget(memory) == 512u * MiB, "the budget must round up just above a heap size boundary"); + memory.memoryHeaps[2].size = 16u * GiB - 128u * MiB; + Require(DepthPlaneCopyBudget(memory) == GiB, "the largest device-local heap must set the budget below 16 GiB"); + memory.memoryHeaps[2].size = 32u * GiB; + Require(DepthPlaneCopyBudget(memory) == 2u * GiB, "the default budget must scale beyond a 16 GiB heap"); +} } int main(int argc, char** argv) { try { - const bool evicting = argc > 1 && std::string(argv[1]) == "--evicting"; + const std::string mode = argc > 1 ? argv[1] : ""; + if (mode == "--budget") { + DepthPlaneBudgetCase(); + return 0; + } + const bool evicting = mode == "--evicting"; GuestBlock block; const auto device = OpenVulkanTestDevice(); if (!device) return VulkanTestSkipped; const std::span output(reinterpret_cast(block.At(OutputOffset)), Threads); + if (mode == "--guest-rewrite") { + GuestWriteAfterDrawCase(*device, block, output, true); + return 0; + } + if (mode == "--layout-reuse") { + DepthPlaneLayoutReuseCase(*device, block, output); + return 0; + } const auto present = [&] { if (!evicting) return; AgcDriver::Graphics::Recorder::CountPresent(); @@ -540,7 +614,7 @@ int main(int argc, char** argv) { present(); GuestDepthBitsCase(*device, block, output); present(); - GuestWriteAfterDrawCase(*device, block, output); + GuestWriteAfterDrawCase(*device, block, output, false); present(); FirstSliceCase(*device, block, output); present(); diff --git a/docs/dev/ENVIRONMENT.md b/docs/dev/ENVIRONMENT.md index 58b9485c7bb8..a4fe1d0925d6 100644 --- a/docs/dev/ENVIRONMENT.md +++ b/docs/dev/ENVIRONMENT.md @@ -156,7 +156,7 @@ The code reads environment names through `getenv`, `IsEnvironmentSet`, `kibSetti | `APS5_CPU_STORES` | presence | `core/libs/prx/libSceAgcDriver/Execution/src/Driver/Packets/PacketMemory.cpp` | | writes packet stores on the CPU instead of recording them on the GPU | | `APS5_DCC_KEYS_EACH` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp` | | records every DCC key store at once instead of batching them | | `APS5_DEPTH_COPY_MIN_KIB` | integer | `core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp` | 1024 | minimum surface size in KiB for a depth target to take the depth-copy path | -| `APS5_DEPTH_PLANE_COPY_MIB` | integer | `core/libs/prx/libSceAgcDriver/Graphics/src/DepthSurface.cpp` | 256 | budget in MiB of the sampled depth-plane copies kept for reuse (least recently used copies leave first; copies sampled since the previous present stay while all copies hold at most twice the budget); `0` keeps every copy | +| `APS5_DEPTH_PLANE_COPY_MIB` | integer | `core/libs/prx/libSceAgcDriver/Graphics/src/DepthSurface.cpp` | 1/16 of the largest device-local heap, rounded up to 256 MiB steps with a 256 MiB minimum | overrides the per-device budget in MiB for sampled depth-plane copies kept for reuse. Least recently used copies leave first. Copies sampled since the previous present stay while all copies hold at most twice the budget. `0` keeps every copy | | `APS5_DEPTH_PLANE_WHOLE_STORE` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/DepthSurface.cpp` | | stores a stale depth plane whole when memory over it is read, instead of only the 64 KiB units the read overlaps | | `APS5_DISPATCH_CACHE_BYTES` | integer | `core/libs/prx/libSceAgcDriver/Execution/src/Driver/Dispatch/DispatchCache.cpp` | 1073741824 | size of the dispatch cache in bytes (0 keeps the default of 1 GiB) | | `APS5_DISPATCH_CACHE_ENTRIES` | integer | `core/libs/prx/libSceAgcDriver/Execution/src/Driver/Dispatch/DispatchCache.cpp` | 8192 | number of dispatch cache entries; 0 picks a default from the variant count: 8192 with the default 4 variants, 16384 with 2 or fewer, 4096 under `APS5_DISPATCH_STAMP_VALIDATE` |