From c9987271e3405c50820d157e4bcc9f11f478df2e Mon Sep 17 00:00:00 2001 From: hugodearaujo Date: Sat, 31 Oct 2026 11:46:16 -0300 Subject: [PATCH 1/2] fix(agc): import a native multisample D32S8 target without HTILE whose planes each hold one value --- core/libs/prx/libSceAgcDriver/CMakeLists.txt | 5 +- .../Graphics/src/DepthSurface.cpp | 63 ++++++++++++++- .../execution/NativeMultisampleDepth.cpp | 79 +++++++++++++++++++ docs/dev/debt/libSceAgcDriver.md | 1 + 4 files changed, 143 insertions(+), 5 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/CMakeLists.txt b/core/libs/prx/libSceAgcDriver/CMakeLists.txt index 3618d5b7f69c..456db079881d 100644 --- a/core/libs/prx/libSceAgcDriver/CMakeLists.txt +++ b/core/libs/prx/libSceAgcDriver/CMakeLists.txt @@ -3143,10 +3143,11 @@ if(BUILD_TESTING) set_tests_properties(agc_driver_htile_mask_lifetime PROPERTIES ENVIRONMENT_MODIFICATION "PATH=path_list_prepend:$") endif() add_test(NAME agc_driver_native_depth_buffer_clear COMMAND agc_driver_native_multisample_depth_tests --buffer-clear) - set_tests_properties(agc_driver_native_depth_clears agc_driver_native_depth_clear_refusals agc_driver_native_depth_buffer_clear PROPERTIES TIMEOUT 30 ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1" SKIP_RETURN_CODE 77 WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}") + add_test(NAME agc_driver_native_depth_uniform_planes COMMAND agc_driver_native_multisample_depth_tests --uniform-planes) + set_tests_properties(agc_driver_native_depth_clears agc_driver_native_depth_clear_refusals agc_driver_native_depth_buffer_clear agc_driver_native_depth_uniform_planes 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_retirement PROPERTIES ENVIRONMENT_MODIFICATION "PATH=path_list_prepend:$") - set_tests_properties(agc_driver_native_depth_clears agc_driver_native_depth_clear_refusals agc_driver_native_depth_buffer_clear PROPERTIES ENVIRONMENT_MODIFICATION "PATH=path_list_prepend:$") + set_tests_properties(agc_driver_native_depth_clears agc_driver_native_depth_clear_refusals agc_driver_native_depth_buffer_clear agc_driver_native_depth_uniform_planes PROPERTIES ENVIRONMENT_MODIFICATION "PATH=path_list_prepend:$") endif() set_tests_properties(agc_sparse_buffer_holes PROPERTIES TIMEOUT 30) add_test(NAME agc_pipeline_journal COMMAND agc_driver_graphics_tests --pipeline-journal) diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/DepthSurface.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/DepthSurface.cpp index 73d166e5f6b0..358afa62fc1d 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/DepthSurface.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/DepthSurface.cpp @@ -97,6 +97,8 @@ std::atomic& anyDepthGuard() { struct DepthSamplingState { std::array initial{}; + std::optional initialDepth; + std::optional initialStencil; std::string refusal; void Refuse(const char* reason) { @@ -112,6 +114,58 @@ bool htileProvesClear(std::uint32_t word, bool depthOnly, float clearDepth) { return false; } +template +std::optional uniformPlaneValue(std::uint64_t address, std::size_t bytes) { + std::array chunk{}; + std::optional value; + for (std::size_t offset = 0u; offset < bytes;) { + const auto count = std::min(chunk.size(), (bytes - offset) / sizeof(Element)); + const auto elements = std::span(chunk).first(count); + GuestMemory::Read(address + offset, std::as_writable_bytes(elements)); + if (!value) value = elements.front(); + if (std::ranges::any_of(elements, [&](Element element) { return element != *value; })) return std::nullopt; + offset += count * sizeof(Element); + } + return value; +} + +DepthSamplingState prepareUniformPlaneSampling(const Context& context, const DepthTarget& target, DepthSamplingState state) { + const auto refuse = [&](const char* reason) { + state.refusal = reason; + return state; + }; + if (target.depthSwizzle != 24u || target.firstSlice != 0u || target.lastSlice != 0u) return refuse("native multisample depth arrays or non-Z_X layout are not implemented"); + if ((target.pipeBankXor & ~0xcf00u) != 0u) return refuse("unsupported native multisample depth XOR"); + if (target.address == 0u || (target.address & 65535u) != 0u || (target.stencilAddress & 65535u) != 0u) return refuse("native multisample depth base is not aligned"); + if (target.htileStencil) return refuse("native multisample stencil import is not implemented"); + state.initial = {{{target.address, static_cast(MultisampledDepthBytes_nid_no_patch(target.extent, 4u, target.samples)), 0u}, {target.stencilAddress, static_cast(MultisampledDepthBytes_nid_no_patch(target.extent, 1u, target.samples)), 0u}}}; + for (const auto& range : state.initial) { + if (range.address > std::numeric_limits::max() - range.bytes) return refuse("native depth import range overflows"); + if (!GuestMemory::Accessible(reinterpret_cast(range.address), range.bytes) || !GuestMemory::Watched(range.address, range.bytes)) return refuse("native multisample depth import requires watched accessible guest memory"); + } + const auto& depth = state.initial[0]; + const auto& stencil = state.initial[1]; + if (depth.address + depth.bytes > stencil.address && stencil.address + stencil.bytes > depth.address) return refuse("native depth and stencil initial ranges overlap"); + for (auto& range : state.initial) { + if (auto* recorder = RecorderFor(context)) recorder->SyncThrough(range.address, range.bytes); + StorageTexture::FlushPending(range.address, range.bytes); + GuestMemory::FlushGpuWrites(range.address, range.bytes); + if (!GuestMemory::Accessible(reinterpret_cast(range.address), range.bytes) || !GuestMemory::Watched(range.address, range.bytes)) return refuse("native multisample depth import requires watched accessible guest memory"); + range.generation = GuestMemory::CollectWritesUncached(range.address, range.bytes); + if (range.generation == 0u) return refuse("native multisample depth import requires tracked generations"); + } + const auto depthWord = uniformPlaneValue(depth.address, depth.bytes); + const auto depthValue = depthWord ? std::bit_cast(*depthWord) : 0.0f; + if (!depthWord || !(depthValue >= 0.0f && depthValue <= 1.0f)) return refuse("native multisample depth plane without HTILE does not hold one depth value in [0, 1]"); + const auto stencilByte = uniformPlaneValue(stencil.address, stencil.bytes); + if (!stencilByte) return refuse("native multisample stencil plane without HTILE does not hold one stencil value"); + for (const auto& range : state.initial) GuestMemory::CollectWritesUncached(range.address, range.bytes); + if (!GuestMemory::UnchangedSinceAll(state.initial)) return refuse("guest writes raced native multisample depth import"); + state.initialDepth = depthValue; + state.initialStencil = *stencilByte; + return state; +} + DepthSamplingState prepareDepthSampling(const Context& context, const DepthTarget& target) { DepthSamplingState state; const auto refuse = [&](const char* reason) { @@ -119,6 +173,7 @@ DepthSamplingState prepareDepthSampling(const Context& context, const DepthTarge return state; }; if (target.samples != 2u && target.samples != 4u && target.samples != 8u) return refuse("unsupported native depth sample count"); + if (target.format == VK_FORMAT_D32_SFLOAT_S8_UINT && target.stencilAddress != 0u && target.htileAddress == 0u) return prepareUniformPlaneSampling(context, target, std::move(state)); if (target.format != VK_FORMAT_D16_UNORM && target.format != VK_FORMAT_D32_SFLOAT) return refuse("native multisample stencil or depth format import is not implemented"); if (target.depthSwizzle != 24u || target.firstSlice != 0u || target.lastSlice != 0u) return refuse("native multisample depth arrays or non-Z_X layout are not implemented"); if ((target.pipeBankXor & ~0xcf00u) != 0u) return refuse("unsupported native multisample depth XOR"); @@ -338,7 +393,7 @@ class DepthSurface { toGeneral.subresourceRange = viewInfo.subresourceRange; const auto barrier = context.Resolved(&DeviceFunctions::cmdPipelineBarrier, "vkCmdPipelineBarrier"); barrier(commands, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, nullptr, 0, nullptr, 1, &toGeneral); - const VkClearDepthStencilValue clear{target.clearDepth, target.clearStencil}; + const VkClearDepthStencilValue clear{this->sampling.initialDepth.value_or(target.clearDepth), this->sampling.initialStencil.value_or(target.clearStencil)}; context.Function("vkCmdClearDepthStencilImage")(commands, image, VK_IMAGE_LAYOUT_GENERAL, &clear, 1, &toGeneral.subresourceRange); RecordMemoryBarrier(context, commands, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT, VK_ACCESS_TRANSFER_WRITE_BIT, VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT); if (batch) batch->SubmitAndWait(); @@ -391,7 +446,8 @@ class DepthSurface { if (target.samples == 1u) return; Require(resource.baseAddress == target.address && resource.width == target.extent.width && resource.height == target.extent.height && resource.samples == target.samples && resource.format == (target.format == VK_FORMAT_D16_UNORM ? 7u : 22u), "native multisample depth sampled identity or format mismatch"); Require(resource.dimension == TextureDimension::k2DMsaa && resource.tileMode == TextureTileMode::kZ64KBX && resource.depthOrLastArray == 0u && resource.baseArray == 0u && resource.baseLevel == 0u && resource.lastLevel == 0u && resource.mipCount == 1u && resource.allocatedMipCount == 1u && resource.minLod == 0u, "native multisample depth sampled array, mip or layout is not implemented"); - Require(resource.pipeBankXor == target.pipeBankXor && resource.dccAddress == target.htileAddress && resource.iterate256 == target.iterate256 && resource.dccPipeAligned == target.htilePipeAligned && !resource.dccAlphaOnMsb, "native multisample depth sampled metadata or XOR mismatch"); + const bool metadataMatches = target.htileAddress == 0u ? resource.dccAddress == 0u : resource.dccAddress == target.htileAddress && resource.iterate256 == target.iterate256 && resource.dccPipeAligned == target.htilePipeAligned; + Require(resource.pipeBankXor == target.pipeBankXor && metadataMatches && !resource.dccAlphaOnMsb, "native multisample depth sampled metadata or XOR mismatch"); } void ApplyFastClear() { @@ -1109,7 +1165,8 @@ class DepthSurface { barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; barrier.image = sampleShadow->image; - barrier.subresourceRange = {VK_IMAGE_ASPECT_DEPTH_BIT, 0, 1, 0, 1}; + const bool stencil = hostFormat == VK_FORMAT_D16_UNORM_S8_UINT || hostFormat == VK_FORMAT_D24_UNORM_S8_UINT || hostFormat == VK_FORMAT_D32_SFLOAT_S8_UINT; + barrier.subresourceRange = {VK_IMAGE_ASPECT_DEPTH_BIT | (stencil ? VK_IMAGE_ASPECT_STENCIL_BIT : 0u), 0, 1, 0, 1}; context.Resolved(&DeviceFunctions::cmdPipelineBarrier, "vkCmdPipelineBarrier")(commands, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, nullptr, 0, nullptr, 1, &barrier); if (batch) batch->SubmitAndWait(); else Recorder::CountBarriers(Recorder::CommandClass::Draw, 1); diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/NativeMultisampleDepth.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/NativeMultisampleDepth.cpp index 7144710b9902..4ce57469c94d 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/NativeMultisampleDepth.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/NativeMultisampleDepth.cpp @@ -1545,6 +1545,75 @@ void CheckRetirement(Context context, VkFormat format, std::uint32_t samples, st } +void CheckUniformPlanesWithoutHtile(Context context, std::uint32_t samples) { + constexpr VkExtent2D extent{129u, 67u}; + 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), stencil(stencilBytes); + const auto fill = [&](float depth, std::uint8_t value) { + const auto word = std::bit_cast(depth); + for (std::size_t offset = 0u; offset < depthBytes; offset += 4u) std::memcpy(memory.Data() + offset, &word, 4u); + std::memset(stencil.Data(), value, stencilBytes); + }; + DepthTarget target{memory.Address(), stencil.Address(), extent, VK_FORMAT_D32_SFLOAT_S8_UINT, 1.0f, 0u, 0u, false, samples}; + target.depthSwizzle = 24u; + Recorder recorder(context); + recorder.Activate(); + auto words = DepthSampleWords(target); + words[6] &= ~((1u << 19u) | (1u << 21u)); + const auto lookup = [&] { return DepthSurfaceTexture(context, words, DecodeTextureResource(words), VkComponentMapping{}); }; + const auto clear = [&] { + recorder.Sync(); + ClearCachedTextures(context.device); + ClearDepthSurfaces(context.device); + }; + struct Cleanup { + decltype(clear)& action; + ~Cleanup() { action(); } + } cleanup{clear}; + for (std::uint32_t field = 0u; field < 5u; ++field) { + fill(0.25f, 0x5au); + auto invalid = target; + std::string_view reason; + switch (field) { + case 0u: memory.Data()[depthBytes - 1u] = std::byte{0x3f}; reason = "does not hold one depth value"; break; + case 1u: fill(2.0f, 0x5au); reason = "does not hold one depth value"; break; + case 2u: stencil.Data()[stencilBytes - 1u] = std::byte{0x5b}; reason = "does not hold one stencil value"; break; + case 3u: invalid.htileStencil = true; reason = "stencil import"; break; + case 4u: invalid.stencilAddress = memory.Address() + 65536u; reason = "overlap"; break; + } + Require(DepthSurfaceView(context, invalid) != VK_NULL_HANDLE, "a refused uniform-plane import must preserve attachment rendering"); + TargetRefuses([&] { DepthSurfaceTexture(context, words, DecodeTextureResource(words), VkComponentMapping{}); }, reason); + clear(); + } + for (const auto& [depth, value] : std::array{std::pair{0.0f, std::uint8_t{0u}}, std::pair{0.25f, std::uint8_t{0x5au}}}) { + fill(depth, value); + Require(DepthSurfaceView(context, target) != VK_NULL_HANDLE, "a uniform-plane D32S8 target without HTILE has no attachment view"); + auto texture = lookup(); + Require(texture != nullptr && texture->View() != VK_NULL_HANDLE, "a uniform-plane D32S8 target without HTILE was not sampled natively"); + Buffer output(context, (extent.width * extent.height * samples + 2u) * 16u, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT); + std::memset(output.Bytes().data(), 0xa5, output.Bytes().size()); + { + const Fetch fetch(context, *texture, output, FetchShader(extent.width, extent.height, samples, false, true)); + CommandBatch batch(context); + fetch.Run(batch.Handle(), extent.width * extent.height * samples); + 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 i = 0u; i < extent.width * extent.height * samples; ++i) { + std::array sampled{}; + std::memcpy(sampled.data(), output.Bytes().data() + (i + 1u) * 16u, 16u); + Require(sampled == std::array{depth, 0.0f, 0.0f, 1.0f}, "a uniform depth plane without HTILE was not imported into every sample"); + } + } + texture.reset(); + stencil.Data()[0] = std::byte{static_cast(value + 1u)}; + TargetRefuses([&] { lookup(); }, "guest writes"); + clear(); + } + std::printf("Native D32S8 without HTILE, samples=%u: uniform planes imported and sampled, other planes refused\n", samples); +} + int main(int argc, char** argv) { try { #ifdef __linux__ @@ -1578,6 +1647,16 @@ int main(int argc, char** argv) { } return 0; } + if (argc == 2 && std::string_view(argv[1]) == "--uniform-planes") { + std::uint32_t checked = 0u, unavailable = 0u; + for (const auto samples : {2u, 4u, 8u}) { + if (!DepthSupported(context, HostDepthFormat(context, VK_FORMAT_D32_SFLOAT_S8_UINT), samples)) { ++unavailable; continue; } + CheckUniformPlanesWithoutHtile(context, samples); + ++checked; + } + std::printf("Native depth uniform-plane cases checked=%u unavailable=%u\n", checked, unavailable); + return checked != 0u ? 0 : VulkanTestSkipped; + } if (argc == 2 && std::string_view(argv[1]) == "--clears") { CheckClearDispatch(); std::uint32_t checked = 0u, unavailable = 0u; diff --git a/docs/dev/debt/libSceAgcDriver.md b/docs/dev/debt/libSceAgcDriver.md index c3b4b1c98b7a..ff362beb8361 100644 --- a/docs/dev/debt/libSceAgcDriver.md +++ b/docs/dev/debt/libSceAgcDriver.md @@ -60,6 +60,7 @@ - [Native depth allocation retirement](../../../core/libs/prx/libSceAgcDriver/Graphics/src/DepthSurface.cpp) covers sampling-eligible multisampled owners only. Successful release notifications must cumulatively cover both complete depth and HTILE ranges; protection changes, failed releases and partial coverage keep the original guards. Retired owners leave lookup and metadata routing, while held views and recorded work retain their images. Retirement of single-sample or sampling-ineligible depth attachments and console equivalence remain unimplemented or unmeasured. The regression uses real allocation-registry operations with a no-op host-release callback, so it does not validate the host unmap backend. - [Native MSAA depth attachment feedback](../../../core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp) is not implemented. A draw sampling a native multisampled depth view while attaching its source image throws before pipeline creation or render-pass recording, including read-only attachment feedback. Sampling that image in a separate draw or dispatch remains supported. The refusal compares the held native image views and their device and attachment identity; single-sample depth behavior is retained. - [Native multisampled depth sampling](../../../core/libs/prx/libSceAgcDriver/Graphics/src/DepthSurface.cpp) accepts numeric D16 or D32, two/four/eight samples, one Z_X slice and mip, and pipe-aligned HTILE without stencil or VRS, with ITERATE_256 on or off: the initial import reads no compressed Z planes, and Mesa's HTILE clear words (`radv_get_htile_fast_clear_value`) and Addrlib's HTILE footprint do not depend on ITERATE_256, which `ac_descriptors.c` ties to TC reads of compressed MSAA HTILE. Sampling eligibility is recorded before the attachment's first host clear: every HTILE word must prove the same initial clear of zero or one, and the complete sample-aware depth and HTILE ranges must be accessible and write-watched. Unsupported initial state or device sampling support retains attachment rendering but sampling throws; eligibility is never retried. Sampling rejects later guest writes, queued external GPU writes, and unproven HTILE clear/fill transitions. A guest read over the depth or HTILE range of a surface the host has not written since import (draws with depth or stencil writes, depth/stencil copies, storage write-back; not clears after a proven HTILE clear) retires it instead of throwing; that a draw without those writes leaves the console's Z planes and HTILE unchanged is inferred, not measured. Guest publication of a written surface, arbitrary guest depth import, stencil/raw-bit sampling, arrays and storage access remain unimplemented. The block footprint follows main's AMD Addrlib thin-block rule; the accepted HTILE clear words and PS5 equivalence are not measured on console hardware. PPSA99902's historical resident eight-sample D32 reader is documented in [#419](https://github.com/boykopovar/AnyPS5/pull/419#issuecomment-6105597729). +- [Native multisampled D32S8 depth without HTILE](../../../core/libs/prx/libSceAgcDriver/Graphics/src/DepthSurface.cpp) is imported only when its depth plane repeats one float in [0, 1] and its separate stencil plane repeats one byte; the host image starts at those values and the sampled descriptor must name no metadata. That every sample then holds them is inferred from the uncompressed layout, not measured on the console. Planes holding more than one value, D16 or D32 without HTILE, and D32S8 with HTILE still throw. - [sceAgcDriverSetSubmitValidationMode, sceAgcDriverGetSubmitValidationMode, sceAgcDriverSetSubmitValidationConfig, sceAgcDriverGetSubmitValidationConfig, sceAgcDriverSetValidationErrorOutputFrequency, sceAgcDriverGetShaderDebuggingStatus](../../../core/libs/prx/libSceAgcDriver/Unimplemented.cpp) (libSceAgcDriver) - the five validation calls return `0x8A6C1000` without reading their arguments or writing caller memory, and `sceAgcDriverGetShaderDebuggingStatus` returns 1, as [OpenAGC](https://github.com/OpenAGC/OpenAGC/blob/3c7e8072f0d7684e930454794fd5c02056946d73/src/game_compat.c#L250-L291) reads them from Sony's libSceAgcDriver.sprx: each validation export is `mov eax, 0x8a6c1000; ret` in the copy Dragon Quest VII Reimagined bundles (0x7bb0-0x7bf0), and the debugging status is 1 in the firmware 5.50 library (0x6740). The parameters (a 32-bit mode or frequency, a mode output, a configuration pointer) follow OpenAGC and are never read. Whether later retail firmware enables submit validation or shader debugging is unverified; no title in this repository is known to call them - [sceAgcDriver retail constant results](../../../core/libs/prx/libSceAgcDriver/Unimplemented.cpp) (libSceAgcDriver) - the debug, capture, GPU printf, register access, GPU reset, suspend point and user data exports taken from the retail `libSceAgcDriver.sprx`, and `sceAgcDriverRegisterOwnerForSystem`, `sceAgcDriverInitResourceRegistrationInterface` and `sceAgcDriverSetResourceRegistrationInfo` in [Registration.cpp](../../../core/libs/prx/libSceAgcDriver/Resource/src/Registration.cpp), are declared without parameters: the console bodies return a constant without reading any argument, so their signatures are unknown. `sceAgcDriverAllocateToolMemoryForGpuReset` and `sceAgcDriverGetAllocatedToolMemoryForGpuReset` read only the output pointer (fourth and second argument, a 12-byte range the console zeroes); the other arguments are declared as `uint64_t`. - [Indices far past every vertex fetch](../../../core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp) (libSceAgcDriver) - when a draw's highest index is at least 64Ki vertices past the largest per-vertex record count, every index past that count is moved to it in a copy of the indices, so the zero-padded vertex copies are not sized to the original index (PPSA04159 draws a list of `0xffffffff` with primitive restart off, which asked for 160 GiB). Each attribute fetched by vertex index reads zeros there as at the original index (out-of-bounds select 0 or 1); a draw with another out-of-bounds select keeps its indices. The vertex index the shader sees changes for the moved indices, which a shader that reads it directly would notice From f7841c78d58b7ec1e6c498157b6e4238bb882fc5 Mon Sep 17 00:00:00 2001 From: hugodearaujo Date: Sat, 31 Oct 2026 13:20:23 -0300 Subject: [PATCH 2/2] fix(agc): sample the stencil plane of a uniform-plane native multisample D32S8 import The stencil plane of a native multisample D32S8 target imported from uniform planes can be sampled as an 8-bit uint at its own address: the sampled descriptor check accepts it, and the sample shadow copies the stencil aspect with the depth. --uniform-planes reads both planes back with a non-zero stencil in each fill, so a host stencil cleared to DB_STENCIL_CLEAR instead of the plane's byte fails. --- .../Graphics/src/DepthSurface.cpp | 9 ++++--- .../execution/NativeMultisampleDepth.cpp | 24 ++++++++++++++++++- docs/dev/debt/libSceAgcDriver.md | 2 +- 3 files changed, 30 insertions(+), 5 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/DepthSurface.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/DepthSurface.cpp index 358afa62fc1d..2c471da273eb 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/DepthSurface.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/DepthSurface.cpp @@ -5,6 +5,7 @@ #include "prx/libSceAgcDriver/Graphics/include/Recorder.hpp" #include "prx/libSceAgcDriver/Graphics/include/GuestBufferMemory.hpp" #include "prx/libSceAgcDriver/Graphics/include/MultisampleTarget.hpp" +#include "prx/libSceAgcDriver/Graphics/include/Pipeline.hpp" #include "prx/libSceAgcDriver/Graphics/include/Resources.hpp" #include "prx/libSceAgcDriver/Graphics/include/Texture.hpp" #include "prx/libSceAgcDriver/Graphics/include/TextureFormat.hpp" @@ -444,7 +445,9 @@ class DepthSurface { void CheckResource(const GuestTextureResource& resource) const { if (target.samples == 1u) return; - Require(resource.baseAddress == target.address && resource.width == target.extent.width && resource.height == target.extent.height && resource.samples == target.samples && resource.format == (target.format == VK_FORMAT_D16_UNORM ? 7u : 22u), "native multisample depth sampled identity or format mismatch"); + const bool stencil = target.stencilAddress != 0u && resource.baseAddress == target.stencilAddress; + const bool plane = stencil ? ResolveTextureFormat(resource.format) == VK_FORMAT_R8_UINT : resource.baseAddress == target.address && resource.format == (target.format == VK_FORMAT_D16_UNORM ? 7u : 22u); + Require(plane && resource.width == target.extent.width && resource.height == target.extent.height && resource.samples == target.samples, "native multisample depth sampled identity or format mismatch"); Require(resource.dimension == TextureDimension::k2DMsaa && resource.tileMode == TextureTileMode::kZ64KBX && resource.depthOrLastArray == 0u && resource.baseArray == 0u && resource.baseLevel == 0u && resource.lastLevel == 0u && resource.mipCount == 1u && resource.allocatedMipCount == 1u && resource.minLod == 0u, "native multisample depth sampled array, mip or layout is not implemented"); const bool metadataMatches = target.htileAddress == 0u ? resource.dccAddress == 0u : resource.dccAddress == target.htileAddress && resource.iterate256 == target.iterate256 && resource.dccPipeAligned == target.htilePipeAligned; Require(resource.pipeBankXor == target.pipeBankXor && metadataMatches && !resource.dccAlphaOnMsb, "native multisample depth sampled metadata or XOR mismatch"); @@ -519,7 +522,7 @@ class DepthSurface { const auto expected = stencil ? VK_FORMAT_R8_UINT : d16 ? VK_FORMAT_R16_UNORM : VK_FORMAT_R32_SFLOAT; const bool depthBits = !stencil && words.size() >= 4 && ShaderRecompiler::DepthBitsTextureWidth(words[1], words[3]) == (d16 ? 16u : 32u); if (multisampled) { - Require(!stencil && !depthBits && format == expected, "native multisampled depth sampling needs a numeric depth-plane format"); + Require(!depthBits && format == expected, "native multisampled depth sampling needs a numeric plane format"); Require(resource.samples == target.samples, "the sampled depth descriptor's sample count differs from its native target"); Require(hostFormat == target.format, "sampling a native multisampled depth plane that the device stores in another depth format is not implemented"); } @@ -1188,7 +1191,7 @@ class DepthSurface { constexpr VkAccessFlags accesses = VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_TRANSFER_WRITE_BIT | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT; RecordMemoryBarrier(context, commands, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, accesses, VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_TRANSFER_WRITE_BIT); VkImageCopy region{}; - region.srcSubresource = {VK_IMAGE_ASPECT_DEPTH_BIT, 0, 0, 1}; + region.srcSubresource = {static_cast(VK_IMAGE_ASPECT_DEPTH_BIT | (HasStencil(hostFormat) ? VK_IMAGE_ASPECT_STENCIL_BIT : 0u)), 0, 0, 1}; region.dstSubresource = region.srcSubresource; region.extent = {target.extent.width, target.extent.height, 1}; context.Function("vkCmdCopyImage")(commands, image, VK_IMAGE_LAYOUT_GENERAL, sampleShadow->image, VK_IMAGE_LAYOUT_GENERAL, 1, ®ion); diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/NativeMultisampleDepth.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/NativeMultisampleDepth.cpp index 4ce57469c94d..91baff806b04 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/NativeMultisampleDepth.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/NativeMultisampleDepth.cpp @@ -1561,6 +1561,11 @@ void CheckUniformPlanesWithoutHtile(Context context, std::uint32_t samples) { recorder.Activate(); auto words = DepthSampleWords(target); words[6] &= ~((1u << 19u) | (1u << 21u)); + auto stencilTarget = target; + stencilTarget.address = target.stencilAddress; + auto stencilWords = DepthSampleWords(stencilTarget); + stencilWords[1] = (stencilWords[1] & ~(0x1ffu << 20u)) | (5u << 20u); + stencilWords[6] &= ~((1u << 19u) | (1u << 21u)); const auto lookup = [&] { return DepthSurfaceTexture(context, words, DecodeTextureResource(words), VkComponentMapping{}); }; const auto clear = [&] { recorder.Sync(); @@ -1586,7 +1591,7 @@ void CheckUniformPlanesWithoutHtile(Context context, std::uint32_t samples) { TargetRefuses([&] { DepthSurfaceTexture(context, words, DecodeTextureResource(words), VkComponentMapping{}); }, reason); clear(); } - for (const auto& [depth, value] : std::array{std::pair{0.0f, std::uint8_t{0u}}, std::pair{0.25f, std::uint8_t{0x5au}}}) { + for (const auto& [depth, value] : std::array{std::pair{0.0f, std::uint8_t{0xc3u}}, std::pair{0.25f, std::uint8_t{0x5au}}}) { fill(depth, value); Require(DepthSurfaceView(context, target) != VK_NULL_HANDLE, "a uniform-plane D32S8 target without HTILE has no attachment view"); auto texture = lookup(); @@ -1606,6 +1611,23 @@ void CheckUniformPlanesWithoutHtile(Context context, std::uint32_t samples) { Require(sampled == std::array{depth, 0.0f, 0.0f, 1.0f}, "a uniform depth plane without HTILE was not imported into every sample"); } } + auto stencilTexture = DepthSurfaceTexture(context, stencilWords, DecodeTextureResource(stencilWords), VkComponentMapping{}); + Require(stencilTexture != nullptr && stencilTexture->View() != VK_NULL_HANDLE, "the stencil plane of a uniform-plane D32S8 target without HTILE was not sampled natively"); + { + std::memset(output.Bytes().data(), 0xa5, output.Bytes().size()); + const Fetch fetch(context, *stencilTexture, output, FetchShader(extent.width, extent.height, samples, false, false)); + CommandBatch batch(context); + fetch.Run(batch.Handle(), extent.width * extent.height * samples); + 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 i = 0u; i < extent.width * extent.height * samples; ++i) { + std::array sampled{}; + std::memcpy(sampled.data(), output.Bytes().data() + (i + 1u) * 16u, 16u); + Require(sampled[0] == value, "a uniform stencil plane without HTILE was not imported into every sample: sample " + std::to_string(i) + " holds " + std::to_string(sampled[0]) + ", the plane " + std::to_string(value)); + } + } + stencilTexture.reset(); texture.reset(); stencil.Data()[0] = std::byte{static_cast(value + 1u)}; TargetRefuses([&] { lookup(); }, "guest writes"); diff --git a/docs/dev/debt/libSceAgcDriver.md b/docs/dev/debt/libSceAgcDriver.md index ff362beb8361..f4f32e7db85e 100644 --- a/docs/dev/debt/libSceAgcDriver.md +++ b/docs/dev/debt/libSceAgcDriver.md @@ -60,7 +60,7 @@ - [Native depth allocation retirement](../../../core/libs/prx/libSceAgcDriver/Graphics/src/DepthSurface.cpp) covers sampling-eligible multisampled owners only. Successful release notifications must cumulatively cover both complete depth and HTILE ranges; protection changes, failed releases and partial coverage keep the original guards. Retired owners leave lookup and metadata routing, while held views and recorded work retain their images. Retirement of single-sample or sampling-ineligible depth attachments and console equivalence remain unimplemented or unmeasured. The regression uses real allocation-registry operations with a no-op host-release callback, so it does not validate the host unmap backend. - [Native MSAA depth attachment feedback](../../../core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp) is not implemented. A draw sampling a native multisampled depth view while attaching its source image throws before pipeline creation or render-pass recording, including read-only attachment feedback. Sampling that image in a separate draw or dispatch remains supported. The refusal compares the held native image views and their device and attachment identity; single-sample depth behavior is retained. - [Native multisampled depth sampling](../../../core/libs/prx/libSceAgcDriver/Graphics/src/DepthSurface.cpp) accepts numeric D16 or D32, two/four/eight samples, one Z_X slice and mip, and pipe-aligned HTILE without stencil or VRS, with ITERATE_256 on or off: the initial import reads no compressed Z planes, and Mesa's HTILE clear words (`radv_get_htile_fast_clear_value`) and Addrlib's HTILE footprint do not depend on ITERATE_256, which `ac_descriptors.c` ties to TC reads of compressed MSAA HTILE. Sampling eligibility is recorded before the attachment's first host clear: every HTILE word must prove the same initial clear of zero or one, and the complete sample-aware depth and HTILE ranges must be accessible and write-watched. Unsupported initial state or device sampling support retains attachment rendering but sampling throws; eligibility is never retried. Sampling rejects later guest writes, queued external GPU writes, and unproven HTILE clear/fill transitions. A guest read over the depth or HTILE range of a surface the host has not written since import (draws with depth or stencil writes, depth/stencil copies, storage write-back; not clears after a proven HTILE clear) retires it instead of throwing; that a draw without those writes leaves the console's Z planes and HTILE unchanged is inferred, not measured. Guest publication of a written surface, arbitrary guest depth import, stencil/raw-bit sampling, arrays and storage access remain unimplemented. The block footprint follows main's AMD Addrlib thin-block rule; the accepted HTILE clear words and PS5 equivalence are not measured on console hardware. PPSA99902's historical resident eight-sample D32 reader is documented in [#419](https://github.com/boykopovar/AnyPS5/pull/419#issuecomment-6105597729). -- [Native multisampled D32S8 depth without HTILE](../../../core/libs/prx/libSceAgcDriver/Graphics/src/DepthSurface.cpp) is imported only when its depth plane repeats one float in [0, 1] and its separate stencil plane repeats one byte; the host image starts at those values and the sampled descriptor must name no metadata. That every sample then holds them is inferred from the uncompressed layout, not measured on the console. Planes holding more than one value, D16 or D32 without HTILE, and D32S8 with HTILE still throw. +- [Native multisampled D32S8 depth without HTILE](../../../core/libs/prx/libSceAgcDriver/Graphics/src/DepthSurface.cpp) is imported only when its depth plane repeats one float in [0, 1] and its separate stencil plane repeats one byte; the host image starts at those values and the sampled descriptor must name no metadata. The depth plane is sampled as a 32-bit float and the stencil plane as an 8-bit uint at its own address. That every sample then holds them is inferred from the uncompressed layout, not measured on the console. Planes holding more than one value, D16 or D32 without HTILE, and D32S8 with HTILE still throw. - [sceAgcDriverSetSubmitValidationMode, sceAgcDriverGetSubmitValidationMode, sceAgcDriverSetSubmitValidationConfig, sceAgcDriverGetSubmitValidationConfig, sceAgcDriverSetValidationErrorOutputFrequency, sceAgcDriverGetShaderDebuggingStatus](../../../core/libs/prx/libSceAgcDriver/Unimplemented.cpp) (libSceAgcDriver) - the five validation calls return `0x8A6C1000` without reading their arguments or writing caller memory, and `sceAgcDriverGetShaderDebuggingStatus` returns 1, as [OpenAGC](https://github.com/OpenAGC/OpenAGC/blob/3c7e8072f0d7684e930454794fd5c02056946d73/src/game_compat.c#L250-L291) reads them from Sony's libSceAgcDriver.sprx: each validation export is `mov eax, 0x8a6c1000; ret` in the copy Dragon Quest VII Reimagined bundles (0x7bb0-0x7bf0), and the debugging status is 1 in the firmware 5.50 library (0x6740). The parameters (a 32-bit mode or frequency, a mode output, a configuration pointer) follow OpenAGC and are never read. Whether later retail firmware enables submit validation or shader debugging is unverified; no title in this repository is known to call them - [sceAgcDriver retail constant results](../../../core/libs/prx/libSceAgcDriver/Unimplemented.cpp) (libSceAgcDriver) - the debug, capture, GPU printf, register access, GPU reset, suspend point and user data exports taken from the retail `libSceAgcDriver.sprx`, and `sceAgcDriverRegisterOwnerForSystem`, `sceAgcDriverInitResourceRegistrationInterface` and `sceAgcDriverSetResourceRegistrationInfo` in [Registration.cpp](../../../core/libs/prx/libSceAgcDriver/Resource/src/Registration.cpp), are declared without parameters: the console bodies return a constant without reading any argument, so their signatures are unknown. `sceAgcDriverAllocateToolMemoryForGpuReset` and `sceAgcDriverGetAllocatedToolMemoryForGpuReset` read only the output pointer (fourth and second argument, a 12-byte range the console zeroes); the other arguments are declared as `uint64_t`. - [Indices far past every vertex fetch](../../../core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp) (libSceAgcDriver) - when a draw's highest index is at least 64Ki vertices past the largest per-vertex record count, every index past that count is moved to it in a copy of the indices, so the zero-padded vertex copies are not sized to the original index (PPSA04159 draws a list of `0xffffffff` with primitive restart off, which asked for 160 GiB). Each attribute fetched by vertex index reads zeros there as at the original index (out-of-bounds select 0 or 1); a draw with another out-of-bounds select keeps its indices. The vertex index the shader sees changes for the moved indices, which a shader that reads it directly would notice