Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 12 additions & 1 deletion core/libs/prx/libSceAgcDriver/Graphics/src/DepthSurface.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -927,6 +927,7 @@ bool StencilShadowCopyWorks(const Context& context, VkFormat format, std::uint32
class DepthSurface;
std::pair<std::uint64_t, std::uint64_t> staleStencilRange(const DepthSurface& surface);
void noteStalePlane(std::uint64_t begin, std::uint64_t end);
void retireStencil(DepthSurface& surface);
std::uint64_t nextPlaneSerial();

class DepthSurface {
Expand Down Expand Up @@ -3008,19 +3009,29 @@ PlaneOwners& stencilOwners() {
void takePlane(DepthSurface& surface, PlaneOwners& owners, std::uint64_t address, VkImageAspectFlagBits aspect, bool created, VkImageAspectFlags clearAspects) {
auto& entry = owners[{surface.context.device, address}];
auto* owner = entry.surface;
if (owner != nullptr && owner->active->load(std::memory_order_acquire) && owner != &surface && owner->target.format == surface.target.format && owner->target.samples == surface.target.samples && owner->target.extent.width == surface.target.extent.width && owner->target.extent.height == surface.target.extent.height && (!created || (clearAspects & aspect) == 0)) {
const bool compatible = owner != nullptr && owner->active->load(std::memory_order_acquire) && owner != &surface && owner->target.format == surface.target.format && owner->target.samples == surface.target.samples && owner->target.extent.width == surface.target.extent.width && owner->target.extent.height == surface.target.extent.height;
if (compatible && (!created || (clearAspects & aspect) == 0)) {
if ((owner->pendingClear & aspect) != 0) {
if (aspect == VK_IMAGE_ASPECT_DEPTH_BIT) {
surface.depthFill = owner->depthFill;
surface.depthMark = std::max(surface.depthMark, owner->depthMark);
} else {
surface.stencilFill = owner->stencilFill;
if (surface.target.samples == 1u && !surface.stencilFill.has_value()) surface.stencilFill = owner->clearStencil;
surface.stencilMark = std::max(surface.stencilMark, owner->stencilMark);
}
if (!created || (aspect == VK_IMAGE_ASPECT_DEPTH_BIT ? surface.depthFill.has_value() : surface.stencilFill.has_value())) surface.pendingClear |= aspect;
} else {
surface.CopyAspectFrom(*owner, aspect);
}
if (aspect == VK_IMAGE_ASPECT_STENCIL_BIT && surface.StencilMirrorable() && owner->StencilMirrorable()) {
surface.stencilBaseline = owner->stencilBaseline;
surface.stencilGeneration = owner->stencilGeneration;
}
}
if (compatible && aspect == VK_IMAGE_ASPECT_STENCIL_BIT && surface.StencilMirrorable() && owner->stencilStale) {
surface.MarkStencilStale();
retireStencil(*owner);
}
entry = {&surface, ++planeBinds};
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
if(BUILD_TESTING)
set_tests_properties(agc_driver_stencil_plane_ownership PROPERTIES TIMEOUT 30)
foreach(case d16 readonly cpu cpu_fresh clear independent copy_failure unwatched_cpu_fresh unwatched_cpu_reused unwatched_cpu_after unwatched_gpu_after)
add_test(NAME agc_driver_stencil_plane_ownership_${case} COMMAND agc_driver_stencil_plane_ownership_tests ${case})
set_tests_properties(agc_driver_stencil_plane_ownership_${case} PROPERTIES ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1;APS5_NO_PIPELINE_JOURNAL=1" TIMEOUT 30 SKIP_RETURN_CODE 77 WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}")
if(case MATCHES "^unwatched_")
set_property(TEST agc_driver_stencil_plane_ownership_${case} APPEND PROPERTY ENVIRONMENT "APS5_NO_WRITE_WATCH=1")
endif()
if(WIN32)
set_tests_properties(agc_driver_stencil_plane_ownership_${case} PROPERTIES ENVIRONMENT_MODIFICATION "PATH=path_list_prepend:$<TARGET_FILE_DIR:libc>")
endif()
endforeach()
endif()
Original file line number Diff line number Diff line change
@@ -0,0 +1,292 @@
#include "prx/libSceAgcDriver/Execution/include/GuestMemory.hpp"
#include "prx/libSceAgcDriver/Graphics/include/Context.hpp"
#include "prx/libSceAgcDriver/Graphics/include/DepthSurface.hpp"
#include "prx/libSceAgcDriver/Graphics/include/TextureTiling.hpp"
#include "prx/libc/include/GuestAllocations.hpp"
#include "prx/libc/include/GuestArena.hpp"
#include "prx/libc/include/GuestWriteWatch.hpp"
#include "DepthFastClearHarness.hpp"
#include <algorithm>
#include <array>
#include <bit>
#include <cstdio>
#include <cstring>
#include <span>
#include <stdexcept>
#include <string_view>
#include <vector>

namespace {

using DepthFastClearHarness::Require;
constexpr VkExtent2D Extent{256u, 256u};
constexpr std::size_t Block = 65536u;
constexpr std::size_t DepthBytes = 4u * Block;
constexpr std::size_t Texels = 256u * 256u;
alignas(256) std::array<std::byte, Texels * 4u> Colors{};

struct Fixture {
AgcDriver::VulkanDevice& device;
DepthFastClearHarness::Shaders shaders;
std::uintptr_t base;
VkFormat format;

Fixture(AgcDriver::VulkanDevice& device, VkFormat format) : device(device), shaders(DepthFastClearHarness::Compile(device)), format(format) {
constexpr std::size_t bytes = 3u * DepthBytes + 4u * Block;
auto* memory = GuestArena::GuestArenaAllocate_nid_postfix(bytes, Block);
Require(memory != nullptr, "cannot allocate stencil ownership fixture");
GuestArena::GuestArenaCommit_nid_postfix(memory, bytes, 0x04, bytes);
GuestAllocations::Mutation().Add(memory, bytes, true, true, true);
GuestWriteWatch::GuestWriteWatchRegister_nid_postfix(memory, bytes);
base = reinterpret_cast<std::uintptr_t>(memory);
std::fill_n(static_cast<float*>(memory), 3u * DepthBytes / sizeof(float), 1.0f);
std::memset(reinterpret_cast<void*>(Stencil()), 0, 4u * Block);
AgcDriver::GuestMemory::BumpCollectEpoch();
}

std::uintptr_t Depth(unsigned index) const { return base + index * DepthBytes; }
std::uintptr_t Stencil(unsigned index = 0u) const { return base + 3u * DepthBytes + index * Block; }

DepthFastClearHarness::Surface Surface(unsigned depth, unsigned stencil = 0u) const {
return {Depth(depth), Stencil(stencil), 0u, false, format, 0u, 0u, AgcDriver::Graphics::XorSwizzleMode(AgcDriver::Graphics::TextureTileMode::kZ64KBX)};
}

static DepthFastClearHarness::DrawOptions Options(std::uint8_t value, bool write) {
DepthFastClearHarness::DrawOptions options;
options.depthTest = write;
options.depthWrite = write;
options.depthCompare = VK_COMPARE_OP_ALWAYS;
options.minDepth = options.maxDepth = 0.5f;
options.stencilTest = true;
options.stencil = {VK_STENCIL_OP_KEEP, write ? VK_STENCIL_OP_REPLACE : VK_STENCIL_OP_KEEP, VK_STENCIL_OP_KEEP,
write ? VK_COMPARE_OP_ALWAYS : VK_COMPARE_OP_EQUAL, 255u, write ? 255u : 0u, value};
return options;
}

std::uint32_t Draw(const DepthFastClearHarness::Surface& surface, const DepthFastClearHarness::DrawOptions& options) {
return DepthFastClearHarness::Draw(device, shaders, surface, options, Extent, Colors);
}

void Write(unsigned index, std::uint8_t value, unsigned stencil = 0u) {
Require(Draw(Surface(index, stencil), Options(value, true)) == Texels, "source stencil draw did not cover the plane");
}

void CheckStencil(std::uint8_t value, unsigned stencil = 0u) {
const auto address = Stencil(stencil);
const auto ranges = AgcDriver::Graphics::FlushDepthPlanes(address, Block);
device.WaitIdle();
std::vector<std::byte> bytes(Block);
AgcDriver::GuestMemory::ReadCommitted(address, bytes);
Require(ranges.size() == 1u, "a superseded stencil replica was also published");
Require(std::ranges::all_of(bytes, [&](std::byte byte) { return byte == static_cast<std::byte>(value); }), "guest stencil bytes do not hold the current owner's value");
Require(AgcDriver::Graphics::FlushDepthPlanes(address, Block).empty(), "a clean stencil plane was published twice");
}

void CheckDepth(unsigned index) {
static_cast<void>(AgcDriver::Graphics::FlushDepthPlanes(Depth(index), DepthBytes));
device.WaitIdle();
std::array<std::uint32_t, Texels> values{};
AgcDriver::GuestMemory::ReadCommitted(Depth(index), std::as_writable_bytes(std::span(values)));
Require(std::ranges::all_of(values, [](std::uint32_t value) { return value == std::bit_cast<std::uint32_t>(0.5f); }), "stencil handoff discarded an independently owned depth plane");
}
};

struct CopyFailureProbe {
explicit CopyFailureProbe(AgcDriver::Graphics::Context& context) : original(context.deviceProc) {
Require(active == nullptr, "a stencil copy failure probe is already active");
fallback = original;
active = this;
context.deviceProc = Resolve;
}

~CopyFailureProbe() { active = nullptr; }

static VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL Resolve(VkDevice device, const char* name) {
if (active != nullptr && active->failNext && std::strcmp(name, "vkCmdCopyImage") == 0) {
active->failNext = false;
++active->refused;
return nullptr;
}
return (active != nullptr ? active->original : fallback)(device, name);
}

inline static CopyFailureProbe* active = nullptr;
inline static PFN_vkGetDeviceProcAddr fallback = nullptr;
PFN_vkGetDeviceProcAddr original;
bool failNext = false;
unsigned refused = 0;
};

void CopyFailure(Fixture& fixture) {
auto context = fixture.device.graphicsContext();
CopyFailureProbe probe(context);
const auto destination = fixture.Surface(1u);
AgcDriver::Graphics::DepthTarget target{destination.depth, destination.stencil, Extent, destination.format, 1.0f, destination.clearStencil, destination.htile, destination.htileStencil};
target.depthSwizzle = destination.swizzle;
try {
Require(AgcDriver::Graphics::DepthSurfaceViewWithStencilWriteIntent(context, target, false, true, false) != VK_NULL_HANDLE, "cannot prime the stencil copy destination");
fixture.Write(1u, 37u);
fixture.Write(0u, 203u);
std::vector<std::byte> before(Block);
AgcDriver::GuestMemory::ReadCommittedUnsynced(fixture.Stencil(), before);
Require(!std::ranges::all_of(before, [](std::byte byte) { return byte == std::byte{203}; }), "the source stencil was published before the failed handoff");
const auto nativeCopy = probe.original(context.device, "vkCmdCopyImage");
Require(nativeCopy != nullptr, "the native image copy callback is unavailable");
probe.failNext = true;
bool rejected = false;
try {
static_cast<void>(AgcDriver::Graphics::DepthSurfaceViewWithStencilWriteIntent(context, target, false, true, false));
} catch (const std::runtime_error& error) {
rejected = std::string_view(error.what()) == "AGC graphics: missing Vulkan function: vkCmdCopyImage";
}
probe.failNext = false;
Require(rejected && probe.refused == 1u, "the stencil inheritance copy did not reach its injected resolver failure");
Require(context.deviceProc(context.device, "vkCmdCopyImage") == nativeCopy, "the native image copy callback was not restored after the failure");
std::printf("stencil copy failure injected=%u source=203 previous destination=37\n", probe.refused);
fixture.device.WaitIdle();
fixture.CheckStencil(203u);
Require(fixture.Draw(destination, Fixture::Options(203u, false)) == Texels, "stencil inheritance did not recover after its copy failed");
fixture.CheckStencil(203u);
fixture.CheckDepth(0u);
fixture.CheckDepth(1u);
fixture.device.WaitIdle();
AgcDriver::Graphics::ClearDepthSurfaces(context.device);
} catch (...) {
probe.failNext = false;
fixture.device.WaitIdle();
AgcDriver::Graphics::ClearDepthSurfaces(context.device);
throw;
}
}

void SharedWrites(Fixture& fixture) {
fixture.Write(0u, 37u);
fixture.Write(1u, 203u);
fixture.Write(2u, 91u);
fixture.CheckStencil(91u);
if (fixture.format == VK_FORMAT_D32_SFLOAT_S8_UINT) {
for (unsigned index = 0; index != 3u; ++index) fixture.CheckDepth(index);
}
}

void ReadOnly(Fixture& fixture) {
fixture.Write(0u, 37u);
fixture.Write(1u, 203u);
Require(fixture.Draw(fixture.Surface(0u), Fixture::Options(203u, false)) == Texels, "a read-only rebind lost the newest stencil value");
auto masked = Fixture::Options(73u, true);
masked.depthWrite = false;
masked.stencil.writeMask = 0u;
Require(fixture.Draw(fixture.Surface(0u), masked) == Texels, "a masked stencil draw failed");
fixture.CheckStencil(203u);
fixture.CheckDepth(0u);
fixture.CheckDepth(1u);
}

void CpuStore(Fixture& fixture, bool fresh) {
fixture.Write(0u, 37u);
fixture.Write(1u, 203u);
std::memset(reinterpret_cast<void*>(fixture.Stencil()), 5, Block);
AgcDriver::GuestMemory::BumpCollectEpoch();
const auto destination = fixture.Surface(fresh ? 2u : 0u);
Require(fixture.Draw(destination, Fixture::Options(5u, false)) == Texels, "the new stencil owner did not consume the CPU store");
Require(fixture.Draw(destination, Fixture::Options(203u, false)) == 0u, "the old GPU stencil value survived the CPU store");
fixture.CheckStencil(5u);
fixture.CheckDepth(0u);
fixture.CheckDepth(1u);
}

void CheckHandoffBytes(Fixture& fixture, std::uint8_t value, bool published) {
const auto ranges = AgcDriver::Graphics::FlushDepthPlanes(fixture.Stencil(), Block);
fixture.device.WaitIdle();
std::array<std::byte, Block> bytes{};
AgcDriver::GuestMemory::ReadCommitted(fixture.Stencil(), bytes);
Require(std::ranges::all_of(bytes, [&](std::byte byte) { return byte == static_cast<std::byte>(value); }), "read-only stencil handoff did not preserve CPU/GPU write order");
Require(ranges.size() == (published ? 1u : 0u), "read-only stencil handoff published an unexpected number of replicas");
Require(AgcDriver::Graphics::FlushDepthPlanes(fixture.Stencil(), Block).empty(), "a discarded or clean stencil plane was published again");
}

void UnwatchedHandoff(Fixture& fixture, std::string_view mode) {
Require(!AgcDriver::GuestMemory::Watched(fixture.Stencil(), Block), "the unwatched handoff fixture must not use write watch");
const bool reused = mode == "unwatched_cpu_reused";
const bool after = mode == "unwatched_cpu_after";
const bool gpuAfter = mode == "unwatched_gpu_after";
fixture.Write(0u, 37u);
if (reused) {
fixture.CheckStencil(37u);
std::memset(reinterpret_cast<void*>(fixture.Stencil()), 5, Block);
AgcDriver::GuestMemory::BumpCollectEpoch();
}
fixture.Write(1u, 203u);
if (!reused && !after) {
std::memset(reinterpret_cast<void*>(fixture.Stencil()), 5, Block);
AgcDriver::GuestMemory::BumpCollectEpoch();
}
const auto destination = fixture.Surface(reused ? 0u : 2u);
Require(fixture.Draw(destination, Fixture::Options(203u, false)) == Texels, "a read-only handoff lost the latest GPU stencil");
if (after) {
std::memset(reinterpret_cast<void*>(fixture.Stencil()), 5, Block);
AgcDriver::GuestMemory::BumpCollectEpoch();
}
if (gpuAfter) fixture.Write(2u, 91u);
CheckHandoffBytes(fixture, reused ? 203u : gpuAfter ? 91u : 5u, reused || gpuAfter);
fixture.CheckDepth(0u);
fixture.CheckDepth(1u);
if (gpuAfter) fixture.CheckDepth(2u);
}

void PendingClear(Fixture& fixture) {
auto surface = fixture.Surface(0u);
surface.htile = fixture.Stencil(3u);
surface.htileStencil = true;
surface.clearStencil = 90u;
const auto bytes = AgcDriver::Graphics::HtileMetadataBytes(Extent);
Require(bytes <= Block, "HTILE does not fit its fixture allocation");
std::memset(reinterpret_cast<void*>(surface.htile), 255, bytes);
AgcDriver::GuestMemory::BumpCollectEpoch();
Require(fixture.Draw(surface, Fixture::Options(37u, true)) == Texels, "stencil clear source draw failed");
std::memset(reinterpret_cast<void*>(surface.htile), 0, bytes);
AgcDriver::GuestMemory::BumpCollectEpoch();
AgcDriver::Graphics::NoteDepthMetadataFill(surface.htile, bytes, 0u);
auto target = fixture.Surface(1u);
target.clearStencil = 165u;
Require(fixture.Draw(target, Fixture::Options(90u, false)) == Texels, "a new stencil owner replaced the pending clear with its clear-register value");
fixture.CheckStencil(90u);
}

void Independent(Fixture& fixture) {
constexpr std::array<std::uint8_t, 3> values{37u, 203u, 91u};
for (unsigned index = 0; index != values.size(); ++index) fixture.Write(index, values[index], index);
for (unsigned index = 0; index != values.size(); ++index) {
fixture.CheckStencil(values[index], index);
fixture.CheckDepth(index);
}
}

}

int main(int argc, char** argv) {
try {
const std::string_view mode = argc == 1 ? "write" : argc == 2 ? argv[1] : "invalid";
auto device = OpenVulkanTestDevice();
if (!device) return VulkanTestSkipped;
Fixture fixture(*device, mode == "d16" ? VK_FORMAT_D16_UNORM_S8_UINT : VK_FORMAT_D32_SFLOAT_S8_UINT);
if (mode == "write" || mode == "d16") SharedWrites(fixture);
else if (mode == "readonly") ReadOnly(fixture);
else if (mode == "cpu" || mode == "cpu_fresh") {
if (!AgcDriver::GuestMemory::WriteWatched() || !AgcDriver::GuestMemory::Watched(fixture.Stencil(), Block)) {
std::puts("skipped, guest write watch unavailable");
return VulkanTestSkipped;
}
CpuStore(fixture, mode == "cpu_fresh");
} else if (mode == "unwatched_cpu_fresh" || mode == "unwatched_cpu_reused" || mode == "unwatched_cpu_after" || mode == "unwatched_gpu_after") {
UnwatchedHandoff(fixture, mode);
} else if (mode == "clear") PendingClear(fixture);
else if (mode == "independent") Independent(fixture);
else if (mode == "copy_failure") CopyFailure(fixture);
else throw std::runtime_error("unknown stencil ownership test arguments");
} catch (const std::exception& error) {
std::fprintf(stderr, "%s\n", error.what());
return 1;
}
std::puts("stencil plane ownership tests passed");
}
5 changes: 5 additions & 0 deletions docs/dev/debt/changes/ivan-20261115-stencil-ownership.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# libSceAgcDriver

## add Functional

- [Stencil ownership handoff](../../../core/libs/prx/libSceAgcDriver/Graphics/src/DepthSurface.cpp) (libSceAgcDriver) - Shared-stencil transitions across different extents or formats, multisampled and nonmirrorable planes remain unverified. Matching mirrorable owners transfer stencil publication while depth ownership remains independent. Console behavior and commercial titles have not been measured.
Loading