diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/DepthSurface.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/DepthSurface.cpp index c39dbd74c1d3..c941e8ddab90 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/DepthSurface.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/DepthSurface.cpp @@ -1048,6 +1048,13 @@ class DepthSurface { return target.samples != 1u && uniformPlaneTarget(target) && samplingActive && sampling.refusal.empty() && !hostWritten->load(std::memory_order_acquire); } + bool PublishedUnderStorage() const { + return GuestHoldsSamples() && std::ranges::any_of(sampling.initial, [](const auto& range) { + const std::pair plane{range.address, range.address + range.bytes}; + return StorageTexture::AnyPendingUnitsOverlap(std::span(&plane, 1u)); + }); + } + void PublishToGuest(); std::uint64_t written = ++depthWrites; @@ -3316,6 +3323,13 @@ VkImageView DepthSurfaceViewWithStencilWriteIntent(const Context& context, const for (const auto& candidate : surfaces()) { if (surface == nullptr && candidate->active->load(std::memory_order_acquire) && candidate->context.device == context.device && sameLayoutWithin(candidate->target, target)) surface = candidate.get(); } + if (surface != nullptr && overwrittenStencil && surface->PublishedUnderStorage()) { + std::unique_lock guardLock(depthGuardMutex()); + surface->active->store(false, std::memory_order_release); + std::erase_if(depthGuards(), [&](const auto& range) { return range.active == surface->active; }); + anyDepthGuard().store(!depthGuards().empty(), std::memory_order_release); + surface = nullptr; + } const bool created = surface == nullptr; if (!created) surface->ProveOverwrite(); GuestAllocations::Lease creationLease; diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_native_multisample_depth_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_native_multisample_depth_tests.cmake index 543dabe8bf84..177b31ae30c0 100644 --- a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_native_multisample_depth_tests.cmake +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_native_multisample_depth_tests.cmake @@ -42,6 +42,11 @@ if(BUILD_TESTING) if(WIN32) set_tests_properties(agc_driver_native_depth_overwritten_planes PROPERTIES ENVIRONMENT_MODIFICATION "PATH=path_list_prepend:$") endif() + add_test(NAME agc_driver_native_depth_overwritten_published COMMAND agc_driver_native_multisample_depth_tests --overwritten-published) + set_tests_properties(agc_driver_native_depth_overwritten_published PROPERTIES TIMEOUT 30 ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1" SKIP_RETURN_CODE 77 WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}") + if(WIN32) + set_tests_properties(agc_driver_native_depth_overwritten_published PROPERTIES ENVIRONMENT_MODIFICATION "PATH=path_list_prepend:$") + endif() add_test(NAME agc_driver_native_depth_single_sample_view COMMAND agc_driver_native_multisample_depth_tests --single-sample-view) set_tests_properties(agc_driver_native_depth_single_sample_view PROPERTIES TIMEOUT 30 ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1" SKIP_RETURN_CODE 77 WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}") if(WIN32) diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/NativeMultisampleDepth.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/NativeMultisampleDepth.cpp index b517e785604f..9d7bdc8de77a 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/NativeMultisampleDepth.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/NativeMultisampleDepth.cpp @@ -3837,6 +3837,105 @@ void CheckOverwrittenPlanes(Context context, std::uint32_t samples, OverwrittenP std::printf("Native depth overwritten planes samples=%u mode=%u: imported after its first draw wrote every sample, sampled and published\n", samples, static_cast(mode)); } +void CheckOverwriteOverStorage(Context context, std::uint32_t samples, bool overwrites) { + constexpr VkExtent2D extent{200u, 130u}; + constexpr std::uint8_t reference = 0x21u; + const auto depthBytes = static_cast(MultisampledDepthBytes_nid_no_patch(extent, 4u, samples)); + const auto stencilBytes = static_cast(MultisampledDepthBytes_nid_no_patch(extent, 1u, samples)); + TargetMemory memory(depthBytes, true), stencil(stencilBytes, true); + const auto one = std::bit_cast(1.0f); + for (std::size_t offset = 0u; offset < depthBytes; offset += 4u) std::memcpy(memory.Data() + offset, &one, 4u); + std::memset(stencil.Data(), 0x5a, stencilBytes); + DepthTarget target{memory.Address(), stencil.Address(), extent, VK_FORMAT_D32_SFLOAT_S8_UINT, 1.0f, 0u, 0u, false, samples}; + target.depthSwizzle = 24u; + target.pipeBankXor = samples == 2u ? 0u : 0x8c00u; + Recorder recorder(context); + recorder.Activate(); + std::unique_ptr first, second; + std::shared_ptr image; + std::shared_ptr texture; + struct Cleanup { + Recorder& recorder; + Context context; + ~Cleanup() { recorder.Sync(); ClearCachedTextures(context.device); ClearDepthSurfaces(context.device); ClearMultisampleTargets(context.device); } + } cleanup{recorder, context}; + const auto view = DepthSurfaceView(context, target); + Require(view != VK_NULL_HANDLE && DepthSurfaceAt(target.address), "the published-owner fixture was not imported"); + first = std::make_unique(context, target, view, StencilUse{VK_COMPARE_OP_ALWAYS, VK_STENCIL_OP_REPLACE, reference}, false, false); + NoteDepthSurfaceWrite(context, target); + first->Run(recorder.Commands(), 0.25f); + std::array probe; + AgcDriver::GuestMemory::Read(target.stencilAddress, probe); + constexpr std::size_t skipped = 65536u; + GuestTextureResource storage{}; + storage.baseAddress = memory.Address() + skipped; + storage.width = 256u; + storage.height = static_cast((depthBytes - skipped) / 1024u); + storage.mipCount = storage.allocatedMipCount = 1u; + storage.dimension = TextureDimension::k2D; + storage.tileMode = TextureTileMode::kLinear; + storage.format = 22u; + storage.dstSelX = 4u; + storage.dstSelY = storage.dstSelZ = 0u; + storage.dstSelW = 1u; + const std::array, 1> written{{{storage.baseAddress, storage.baseAddress + depthBytes - skipped}}}; + RequireNoMultisampleTarget(storage.baseAddress, depthBytes - skipped, "a storage image access"); + RetireCoveredDepthSurfaces(context.device, written, {}); + { + std::lock_guard gpu(AgcDriver::GuestMemory::GpuMutex()); + image = StorageTexture::Create(context, *context.detiler, storage, 0u); + const auto commands = recorder.Commands(); + recorder.Keep(image); + const VkImageSubresourceRange range{VK_IMAGE_ASPECT_COLOR_BIT, 0u, 1u, 0u, 1u}; + VkClearColorValue value{}; + value.uint32[0] = 0x3c3c3c3cu; + RecordMemoryBarrier(context, commands, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_ACCESS_SHADER_WRITE_BIT | VK_ACCESS_TRANSFER_WRITE_BIT, VK_ACCESS_TRANSFER_WRITE_BIT); + context.Function("vkCmdClearColorImage")(commands, image->Image(), VK_IMAGE_LAYOUT_GENERAL, &value, 1u, &range); + RecordMemoryBarrier(context, commands, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_ACCESS_TRANSFER_WRITE_BIT, VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT | VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_TRANSFER_WRITE_BIT); + image->MarkWholeWritten(); + } + recorder.Sync(); + Require(StorageTexture::AnyPendingOverlaps(written), "the storage results over the published owner were not left pending"); + if (!overwrites) { + Require(DepthSurfaceView(context, target) == view, "a published owner under storage results was not reused by a draw that does not overwrite it"); + second = std::make_unique(context, target, view, StencilUse{VK_COMPARE_OP_ALWAYS, VK_STENCIL_OP_REPLACE, reference}, false, false); + NoteDepthSurfaceWrite(context, target); + second->Run(recorder.Commands(), 0.5f); + TargetRefuses([&] { AgcDriver::GuestMemory::Read(target.stencilAddress, probe); }, "native multisample depth publication over pending storage image writes is not implemented"); + std::printf("Native depth published owner under storage results samples=%u: a draw that does not prove an overwrite still refuses its publication\n", samples); + return; + } + const auto fresh = DepthSurfaceViewWithStencilWriteIntent(context, target, true, true, true, reference); + Require(fresh != VK_NULL_HANDLE && fresh != view && DepthSurfaceAt(target.address), "an overwriting draw over a published owner under storage results did not start a new owner"); + Require(!StorageTexture::AnyPendingOverlaps(written), "the storage results under the new owner were not stored before its import"); + second = std::make_unique(context, target, fresh, StencilUse{VK_COMPARE_OP_ALWAYS, VK_STENCIL_OP_REPLACE, reference}, false, false); + NoteDepthSurfaceWrite(context, target); + second->Run(recorder.Commands(), 0.5f); + recorder.Sync(); + auto words = DepthSampleWords(target); + words[6] &= ~((1u << 19u) | (1u << 21u)); + texture = DepthSurfaceTexture(context, words, DecodeTextureResource(words), VkComponentMapping{}); + Require(texture != nullptr && texture->View() != VK_NULL_HANDLE, "the new owner over stored storage results was not sampled natively after its overwriting draw"); + const auto count = extent.width * extent.height * samples; + Buffer output(context, (count + 2u) * 16u, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT); + { + const Fetch fetch(context, *texture, output, FetchShader(extent.width, extent.height, samples, false, true)); + CommandBatch batch(context); + fetch.Run(batch.Handle(), count); + RecordMemoryBarrier(context, batch.Handle(), VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_HOST_BIT, VK_ACCESS_SHADER_WRITE_BIT, VK_ACCESS_HOST_READ_BIT); + batch.SubmitAndWait(); + } + output.Invalidate(); + for (std::uint32_t index = 0u; index < count; ++index) { + float sampled = 0.0f; + std::memcpy(&sampled, output.Bytes().data() + (index + 1u) * 16u, 4u); + Require(sampled == 0.5f + static_cast(index % samples + 1u) / 16.0f, "the new owner does not hold the samples of its overwriting draw at element " + std::to_string(index)); + } + texture.reset(); + AgcDriver::GuestMemory::Read(target.stencilAddress, probe); + std::printf("Native depth published owner under storage results samples=%u: an overwriting draw started a new owner over the stored results\n", samples); +} + void CheckSingleSampleView(Context context, std::uint32_t samples) { constexpr VkExtent2D extent{200u, 130u}; const auto depthBytes = static_cast(MultisampledDepthBytes_nid_no_patch(extent, 4u, samples)); @@ -4366,6 +4465,19 @@ int main(int argc, char** argv) { } return checked != 0u ? 0 : VulkanTestSkipped; } + if (argc == 2 && std::string_view(argv[1]) == "--overwritten-published") { + TextureDetiler detiler(context); + auto publishing = context; + publishing.detiler = &detiler; + std::uint32_t checked = 0u; + for (const auto samples : {2u, 4u, 8u}) { + if (!DepthSupported(context, VK_FORMAT_D32_SFLOAT_S8_UINT, samples) || (context.limits.framebufferStencilSampleCounts & samples) == 0u) continue; + CheckOverwriteOverStorage(publishing, samples, false); + CheckOverwriteOverStorage(publishing, samples, true); + ++checked; + } + return checked != 0u ? 0 : VulkanTestSkipped; + } if (argc == 2 && std::string_view(argv[1]) == "--single-sample-view") { TextureDetiler detiler(context); auto publishing = context; diff --git a/docs/dev/debt/libSceAgcDriver.md b/docs/dev/debt/libSceAgcDriver.md index 418b7af35fdf..7d84c2e53e50 100644 --- a/docs/dev/debt/libSceAgcDriver.md +++ b/docs/dev/debt/libSceAgcDriver.md @@ -173,7 +173,7 @@ - [32-bit depth-bits reads of guest memory](../../../core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp) (libSceAgcDriver): a sampled 32_UINT or 32_SINT T# with a depth swizzle mode that no live depth surface matches reads the guest bytes through an R32_SFLOAT image, as the recompiler's depth-bits read expects, and the shader casts the fetched value back to the stored dword. On RX 6700 XT (gfx1031, AMD Windows driver 32.0.21045.5002) the read keeps float denormals, the sign bit alone and quiet and signaling NaN payloads bit for bit. A host that canonicalizes NaNs or flushes denormals on a 32-bit float fetch would change those dwords, and other drivers are not measured. A live depth surface whose extent or base level differs from the T# is not used; the read takes the guest bytes, as the 32-bit float and 16-bit views already do. - [Reused depth storage](../../../core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp): a storage view with another extent or a format that cannot hold the cached depth plane uses guest memory. Depth rendering is not written back to those guest bytes; this admission rule does not prove allocation reuse or preserve a depth writer through an incompatible view. A 2D storage view, or a one-layer 2D array view of layer 0, of level 0 with the plane's extent and format (32-bit float or the 32-bit depth-bits layout for the depth plane, 16-bit unorm for D16, 8-bit uint for the stencil plane) is a storage image that is [filled](../../../core/libs/prx/libSceAgcDriver/Graphics/src/DepthSurface.cpp) from the depth image before every use and, when the shader writes it, copied back after the work: a whole-plane copy through a staging buffer each way. A dispatch of the 15-word 8x8x1 image clear kernel ([`MatchStorageImageClear`](../../../core/libs/prx/libSceAgcDriver/Graphics/src/DepthSurface.cpp): one colour read from the V# in `user[8..11]` stored to every texel of the T# in `user[0..7]`) that covers the whole plane and stores 0 or 1 through a 16-bit unorm view, 0 or 0xffff through a 16-bit uint view, or 0 or a normal float in (0, 1] through a 32-bit float or integer view leaves out the copy-in and replaces the copy-out by a clear of the depth image to that value; the dispatch still writes the storage image. The colour is read again when the copy-out is replaced, and a changed value keeps the copy-out. Indirect dispatches, partial last groups, dispatches that queue on the draw pipeline, other values and formats, a plane the kernel covers only partly and stencil planes keep both copies. A written view is also left pending like any other storage image, so the plane's content, drawn depth included, reaches guest memory on the next flush of that range. A 2D array view of more than one slice of the depth plane, or of a later slice, is a storage image over the slices from 0 to its last (`LayeredDepthStorage`); only the slices from its base slice to its last are copied: a slice that has a depth surface at the plane's address plus a whole depth slice per layer (`DepthSliceBytes`, as for the depth plane copies below) is copied from that surface before every use and back to it after the work, every bound slice each time, through a staging buffer; the other slices hold guest memory like any storage image. These images are kept per address, extent, slice count, base slice, format and tile mode until the device goes away, outside the storage cache's budget. Such a view needs a layer pitch equal to that slice size, and another view of the same memory (the 2D view of its first slice, a view from another base slice, or a sampled copy) is a separate image, copied in before and out after each use, so views that are written before a flush and share a slice do not merge: the later copy-out wins, so their results are not merged. A matching view still throws when it is a cube or a 2D array of more than one layer of the stencil plane or from a later slice, when the surface is multisampled, when it names the depth plane of a 16-bit depth with stencil surface the device stores in a wider format, and when it was written after another view of the same plane (another format, tile mode, address or dimension) replaced it, as two such views bound in one dispatch are. Stored depth values outside 0..1 are not clamped, and Vulkan leaves that copy undefined without `VK_EXT_depth_range_unrestricted`. `agc_driver_depth_storage_dispatch` pins these paths; none is measured on the console. - [Collapsed color array views](../../../core/libs/prx/libSceAgcDriver/Graphics/src/State.cpp) preserve the selected slice in the XOR address equation when the view is represented as a shifted 2D surface. Native Vulkan coverage checks R_X draws, array reads, publication and re-upload for slices 1-3; Lost Soul Aside PPSA26358 validates the RGBA16F cube mip chain on Windows/NVIDIA. Other devices and console comparisons remain unverified. Full-array views retain their layer addressing. -- A [depth surface](../../../core/libs/prx/libSceAgcDriver/Graphics/src/DepthSurface.cpp) (libSceAgcDriver) is retired when a color target or a written storage image it does not serve overlaps it, or when it is sampled through a view it cannot serve and guest memory over it was written since it was last bound; lookups then skip it, so sampling reads the memory like any texture. Bound again, it keeps its own depth instead of the bytes written over it, except for the depth planes the next entry keeps in guest memory, and except for a sampling-eligible multisampled owner that was not drawn since it was published: once written storage views cover its planes it is released, and the next bind creates a new owner from guest memory, so the storage results lie under the new samples. Without write watching, a view it cannot serve still throws. A retired surface also gives up its depth and stencil planes, so another surface sharing them no longer copies from it. +- A [depth surface](../../../core/libs/prx/libSceAgcDriver/Graphics/src/DepthSurface.cpp) (libSceAgcDriver) is retired when a color target or a written storage image it does not serve overlaps it, or when it is sampled through a view it cannot serve and guest memory over it was written since it was last bound; lookups then skip it, so sampling reads the memory like any texture. Bound again, it keeps its own depth instead of the bytes written over it, except for the depth planes the next entry keeps in guest memory, and except for a sampling-eligible multisampled owner that was not drawn since it was published: once written storage views cover its planes, or a draw that writes every sample binds it over pending storage results, it is released, and a new owner is imported from guest memory with those results. Without write watching, a view it cannot serve still throws. A retired surface also gives up its depth and stencil planes, so another surface sharing them no longer copies from it. - [Depth planes in guest memory](../../../core/libs/prx/libSceAgcDriver/Graphics/src/DepthSurface.cpp) (libSceAgcDriver): only single-sample `D32_SFLOAT` and `D32_SFLOAT_S8_UINT` planes with the 64 KiB Z swizzle (`SW_MODE` 24) reach guest memory; D16, other swizzles and multisampled planes keep depth in the host image only. A plane drawn since its last store is stored, uncompressed, in 64 KiB units (128x128 tiles): a buffer upload, a `GuestBuffers` V#, an image lookup or a pending-store flush stores the units it overlaps, a color target or written storage image over the plane all of them. CPU reads and reads through address-based heaps are not caught. Guest writes are ordered when collected (bind, sample, flush, collect epoch), not when made: a collected write reloads the units it touched unless an HTILE clear is pending. A store outside a recorder waits for the GPU. The console keeps HTILE-compressed tiles compressed in memory until a decompress (Mesa `ac_descriptors.h`). - [Stencil planes in guest memory](../../../core/libs/prx/libSceAgcDriver/Graphics/src/DepthSurface.cpp) (libSceAgcDriver): the stencil plane of a single-sample surface with the 64 KiB Z swizzle is stored and reloaded as a whole plane, not in units. Binding the surface for a draw marks it drawn whether or not the draw writes stencil; a read that overlaps it stores it; a guest write collected when the surface is next bound or its stencil sampled reloads it unless a stencil clear is pending. Its layout is taken to be the depth plane's swizzle at one byte per texel; that is not measured. PPSA05684 moves stencil between depth targets with buffer copies every frame. - [Depth surfaces over compared shared memory](../../../core/libs/prx/libSceAgcDriver/Graphics/src/DepthSurface.cpp) (libSceAgcDriver): a depth surface over Windows direct memory that is compared once it is shared sees CPU writes made after the sharing no more than one over unwatched memory does. Its generations come from refused collects (0) or `TrackerGeneration()`, and nothing stamps compared memory after the one report at the sharing.