diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/Draw.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/Draw.cpp index f9fc9528c8a5..a02a2fffb048 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/Draw.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/Draw.cpp @@ -298,6 +298,13 @@ bool EmptyIndirectSkip() { return enabled; } +void FinishLeaseWritesBeforeRead() { + if (!Graphics::LeaseWritesMayBePending()) return; + GuestMemory::TagGpuLockSite(GuestMemory::GpuLockSite::Indirect); + std::lock_guard gpuLock(GuestMemory::GpuMutex()); + Graphics::FinishLeaseWrites(); +} + struct CpuIndirectProgramsStorage {}; std::unordered_map& CpuIndirectPrograms() { @@ -536,6 +543,7 @@ DrawVerdict Driver::draw(QueueState& queue, std::span packe const auto& indirect = *drawParameters.indirect; recordQueuedLabelsBeforeRead(submission.queue); const auto readStart = std::chrono::steady_clock::now(); + FinishLeaseWritesBeforeRead(); const auto count = std::min(indirect.countIndirect ? Pm4::ReadDrawCount(indirect) : indirect.count, indirect.count); bool any = false; for (std::uint32_t record = 0; record < count && !any; ++record) any = recordDraws(Pm4::ReadDrawArguments(indirect, record)); @@ -1124,6 +1132,7 @@ DrawVerdict Driver::finishDraw(DrawTail& tail, PerformanceTimer& timing) { } recordQueuedLabelsBeforeRead(submission.queue); const auto readStart = std::chrono::steady_clock::now(); + FinishLeaseWritesBeforeRead(); const auto count = std::min(indirect.countIndirect ? Pm4::ReadDrawCount(indirect) : indirect.count, indirect.count); std::vector records; for (std::uint32_t record = 0; record < count; ++record) records.push_back(Pm4::ReadDrawArguments(indirect, record)); diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp index 3532d6069f13..7328094dbaed 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp @@ -6464,7 +6464,7 @@ VulkanDevice::IndirectOutcome VulkanDevice::recordCompletedDispatch(const Shader const auto syncStart = std::chrono::steady_clock::now(); recorder.Sync(); timer.phase(PhaseSync); - if (resources->HoldsLease()) Graphics::CountLeaseOutcome(true, 0); + if (resources->HoldsLease()) Graphics::CountLeaseOutcome(true, 0, !resources->BdaReadOnly()); if (profile) { // APS5_PROFILE_DRAW: the [recorder] line's "address-based" syncs by program, every 10 s, // so the programs still waiting here are known (under the GpuMutex, like the rest). @@ -6493,7 +6493,7 @@ VulkanDevice::IndirectOutcome VulkanDevice::recordCompletedDispatch(const Shader } else if (resources->HoldsLease()) { // The lease is in the open batch (kept above, nothing submitted since): the pin waiter // finishes the recorder up to that batch's serial. Prints the [address-sync] leases line. - Graphics::CountLeaseOutcome(false, recorder.Submissions() + 1); + Graphics::CountLeaseOutcome(false, recorder.Submissions() + 1, !resources->BdaReadOnly()); } if (TraceDispatchIo()) std::fprintf(stderr, "[dispatch-io] %s:%s\n", groupsText, resources->Describe().c_str()); WatchMemory(programAddress); diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/GuestBufferMemory.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/GuestBufferMemory.hpp index 395832275ac3..c6d89263e8b3 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/GuestBufferMemory.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/GuestBufferMemory.hpp @@ -231,12 +231,15 @@ std::uint64_t ImageMirrorSerial(const Context& context, std::uint64_t address, s // when synced, and the waiter targets the newest of them. Under APS5_PROFILE_DRAW CountLeaseOutcome // prints the [address-sync] leases line every 10 s from LeaseCounters (cumulative). bool SyncLeaseWork(); -void CountLeaseOutcome(bool synced, std::uint64_t batchSerial); +void CountLeaseOutcome(bool synced, std::uint64_t batchSerial, bool writes); void FinishLeaseWork(); +void FinishLeaseWrites(); bool LeaseWorkPending(); +bool LeaseWritesMayBePending(); struct LeaseStats { std::uint64_t deferred = 0; std::uint64_t synced = 0; + std::uint64_t writing = 0; // Pin-contention waits made by guest threads (the waiter calls), how many of them finished the // newest lease batch, how many had to drain the whole recorder instead (no lease batch noted), // how many only dropped the cached address space (no GPU wait, see AddressSpaceStats), and diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp index 92678ebe252a..953a2124024d 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp @@ -2506,7 +2506,7 @@ void keepRecordedDraw(Recorder& recorder, const std::shared_ptr // Counted for the [address-sync] line: a lease released by the completion (the pin waiter // finishes the recorder up to the open batch, which holds the kept resources and gets the // next serial), or waited for by the caller (any wait releases it at once). - if (resources->HoldsLease()) CountLeaseOutcome(outcome.waited, outcome.waited ? 0 : recorder.Submissions() + 1); + if (resources->HoldsLease()) CountLeaseOutcome(outcome.waited, outcome.waited ? 0 : recorder.Submissions() + 1, !resources->BdaReadOnly()); // Every use of a (possibly shared) resources object registers its GPU writes anew. resources->MarkGpuWrites(recorder); if (spaceKeep != nullptr) *spaceKeep = resources->ReleaseSpace(); @@ -3543,6 +3543,7 @@ bool prepareDraw(const Context& context, const State& state, const Pm4::DrawPara // The reads wait for the producing batch through the flush hook, as the driver's // resolve did for every indirect dispatch before its GPU path. const auto readStart = std::chrono::steady_clock::now(); + FinishLeaseWrites(); const auto count = std::min(args->countIndirect ? Pm4::ReadDrawCount(*args) : args->count, args->count); records.reserve(count); for (std::uint32_t record = 0; record < count; ++record) records.push_back(Pm4::ReadDrawArguments(*args, record)); diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/GuestBufferMemory.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/GuestBufferMemory.cpp index 66a983d1ebc4..2944d7b1de02 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/GuestBufferMemory.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/GuestBufferMemory.cpp @@ -3708,6 +3708,9 @@ struct LeaseState { const Recorder* leaseRecorder = nullptr; std::uint64_t newestLeaseSerial = 0; std::uint64_t finishedLeaseSerial = 0; + std::uint64_t newestWritingLeaseSerial = 0; + std::atomic notedWritingLeases{0}; + std::atomic finishedWritingLeases{0}; }; LeaseState& Leases() { @@ -3885,6 +3888,15 @@ void ensurePinWaiter() { static_cast(registered); } +void finishLeaseBatches(std::uint64_t target, const void* site) { + const auto& state = Leases(); + auto* recorder = Recorder::Active(); + if (recorder == nullptr || recorder != state.leaseRecorder || target <= recorder->CompletedThrough()) return; + if (target >= recorder->OpenSerial()) recorder->Submit(); + Recorder::AnnounceSyncSite(site); + recorder->FinishUpTo(target); +} + } bool SyncLeaseWork() { @@ -3892,7 +3904,7 @@ bool SyncLeaseWork() { return sync; } -void CountLeaseOutcome(bool synced, std::uint64_t batchSerial) { +void CountLeaseOutcome(bool synced, std::uint64_t batchSerial, bool writes) { static const bool profile = std::getenv("APS5_PROFILE_DRAW") != nullptr; auto& state = Leases(); if (!synced) { @@ -3903,11 +3915,17 @@ void CountLeaseOutcome(bool synced, std::uint64_t batchSerial) { state.leaseRecorder = recorder; state.newestLeaseSerial = 0; state.finishedLeaseSerial = 0; + state.newestWritingLeaseSerial = 0; } state.newestLeaseSerial = std::max(state.newestLeaseSerial, batchSerial); + if (writes) { + state.newestWritingLeaseSerial = std::max(state.newestWritingLeaseSerial, batchSerial); + state.notedWritingLeases.fetch_add(1); + } } std::lock_guard lock(state.mutex); ++(synced ? state.stats.synced : state.stats.deferred); + if (writes) ++state.stats.writing; if (!profile) return; // APS5_PROFILE_DRAW: the leases (dispatches and draws) deferred and synced, the guest's // pin-contention waits and the BDA table cache, every 10 s (cumulative counts, like the @@ -3918,18 +3936,20 @@ void CountLeaseOutcome(bool synced, std::uint64_t batchSerial) { const auto& stats = state.stats; const auto table = BdaResources::TableCacheCounters(); const auto& snapshots = Snapshots(); - AgcDriver::ProfilePrint_nid_no_patch("[address-sync] leases: %llu released at completion, %llu synced at once; %llu pin-contention waits by guest threads (%llu finished the lease batch, %llu drained the recorder, %llu cache-only drops) %.1f s; BDA table cache %llu hits / %llu misses (%zu tables held); snapshot compares: %llu skipped (live-backed region), %llu made\n", static_cast(stats.deferred), static_cast(stats.synced), static_cast(stats.contentionWaits), static_cast(stats.contentionSyncs), static_cast(stats.contentionDrains), static_cast(stats.cacheDrops), stats.contentionMs / 1000, static_cast(table.hits), static_cast(table.misses), table.held, static_cast(snapshots.skipped.load(std::memory_order_relaxed)), static_cast(snapshots.checked.load(std::memory_order_relaxed))); + AgcDriver::ProfilePrint_nid_no_patch("[address-sync] leases: %llu released at completion, %llu synced at once; %llu by builds that store through addresses; %llu pin-contention waits by guest threads (%llu finished the lease batch, %llu drained the recorder, %llu cache-only drops) %.1f s; BDA table cache %llu hits / %llu misses (%zu tables held); snapshot compares: %llu skipped (live-backed region), %llu made\n", static_cast(stats.deferred), static_cast(stats.synced), static_cast(stats.writing), static_cast(stats.contentionWaits), static_cast(stats.contentionSyncs), static_cast(stats.contentionDrains), static_cast(stats.cacheDrops), stats.contentionMs / 1000, static_cast(table.hits), static_cast(table.misses), table.held, static_cast(snapshots.skipped.load(std::memory_order_relaxed)), static_cast(snapshots.checked.load(std::memory_order_relaxed))); } void FinishLeaseWork() { GuestMemory::AssertGpuLockHeld("FinishLeaseWork"); - const auto& state = Leases(); - auto* recorder = Recorder::Active(); - const auto target = state.newestLeaseSerial; - if (recorder == nullptr || recorder != state.leaseRecorder || target <= recorder->CompletedThrough()) return; - if (target >= recorder->OpenSerial()) recorder->Submit(); - Recorder::AnnounceSyncSite(__builtin_return_address(0)); - recorder->FinishUpTo(target); + finishLeaseBatches(Leases().newestLeaseSerial, __builtin_return_address(0)); +} + +void FinishLeaseWrites() { + GuestMemory::AssertGpuLockHeld("FinishLeaseWrites"); + auto& state = Leases(); + const auto noted = state.notedWritingLeases.load(); + finishLeaseBatches(state.newestWritingLeaseSerial, __builtin_return_address(0)); + state.finishedWritingLeases.store(noted); } bool LeaseWorkPending() { @@ -3939,6 +3959,11 @@ bool LeaseWorkPending() { return recorder != nullptr && recorder == state.leaseRecorder && state.newestLeaseSerial > recorder->CompletedThrough(); } +bool LeaseWritesMayBePending() { + const auto& state = Leases(); + return state.notedWritingLeases.load() > state.finishedWritingLeases.load(); +} + LeaseStats LeaseCounters() { auto& state = Leases(); std::lock_guard lock(state.mutex); diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_indirect_draw_pending_producer_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_indirect_draw_pending_producer_tests.cmake new file mode 100644 index 000000000000..8b57b6a0e517 --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_indirect_draw_pending_producer_tests.cmake @@ -0,0 +1,9 @@ +if(BUILD_TESTING) + agc_add_draw_pipeline_test(agc_driver_indirect_draw_pending_producer) + add_test(NAME agc_driver_indirect_draw_pending_producer_gpu_indirect_disabled COMMAND agc_driver_indirect_draw_pending_producer_tests --gpu-indirect-disabled) + set_tests_properties(agc_driver_indirect_draw_pending_producer_gpu_indirect_disabled PROPERTIES ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1;APS5_NO_GPU_INDIRECT_DRAW=1" SKIP_RETURN_CODE 77 WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}") + if(WIN32) + set_tests_properties(agc_driver_indirect_draw_pending_producer_gpu_indirect_disabled PROPERTIES ENVIRONMENT_MODIFICATION + "PATH=path_list_prepend:$") + endif() +endif() diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/IndirectDrawPendingProducer.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/IndirectDrawPendingProducer.cpp new file mode 100644 index 000000000000..cce938f2524a --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/execution/IndirectDrawPendingProducer.cpp @@ -0,0 +1,354 @@ +#include "prx/libSceAgcDriver/Execution/include/Driver.hpp" +#include "prx/libSceAgcDriver/Execution/include/GuestMemory.hpp" +#include "prx/libSceAgcDriver/Graphics/include/Draw.hpp" +#include "prx/libSceAgcDriver/Graphics/include/GuestBufferMemory.hpp" +#include "prx/libSceAgcDriver/Submit/include/Dcb.hpp" +#include "prx/libc/include/GuestAllocations.hpp" +#include "prx/libc/include/GuestArena.hpp" +#include "prx/libc/include/GuestWriteWatch.hpp" +#include "VulkanTestDevice.hpp" +#ifdef _WIN32 +#ifndef NOMINMAX +#define NOMINMAX +#endif +#include +#else +#include +#endif +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +using AgcDriver::Graphics::Require; +using Path = AgcDriver::Graphics::IndirectDrawPath; + +constexpr std::uint32_t Width = 192; +constexpr std::uint32_t Height = 128; +constexpr std::uint32_t DistanceVector = 0x00400000u; +constexpr std::uint32_t SetContextReg = 0x69u; +constexpr std::uint32_t SetShReg = 0x76u; +constexpr std::uint32_t SetUconfigReg = 0x79u; + +constexpr std::size_t Block = 65536; +constexpr std::size_t PoolBytes = Block; +constexpr std::size_t ColorBytes = Width * Height * 4; +constexpr std::size_t VertexOffset = 0x2000; +constexpr std::size_t RecordOffset = 0x3000; +constexpr std::size_t CountOffset = 0x3100; +constexpr std::size_t SinkOffset = 0x3800; +constexpr std::array Indices{0, 1, 2}; + +std::byte* ColorMemory = nullptr; +std::byte* Pool = nullptr; + +alignas(256) constexpr std::array VertexCode{ + 0xe0382000, 0x80020005, 0xe0382010, 0x80020405, 0xbf8c3f70, + 0xf80000cf, 0x03020100, 0xf80008df, 0x07060504, 0xbf810000, +}; + +alignas(256) constexpr std::array PixelCode{ + 0x7e0002f2, 0x7e0202f2, 0x7e0402f2, 0x7e0602f2, 0xf800080f, 0x03020100, 0xbf810000, +}; + +alignas(256) constexpr std::array AddressWriterCode{0x7e000202u, 0x7e020203u, 0x7e040204u, 0x7e060280u, 0xdc7c8000u, 0x00000003u, 0xbf810000u}; + +alignas(256) constexpr std::array AddressReaderCode{0x7e060280u, 0xdc308000u, 0x00000003u, 0xbf8c3f70u, 0xe0700000u, 0x80010000u, 0xbf810000u}; + +struct Vertex { + std::array position; + std::array distances; +}; + +std::array Vertices{}; + +constexpr std::array PositionX{-3.0f, 1.0f, 1.0f}; +constexpr std::array PositionY{-1.0f, -1.0f, 3.0f}; + +struct RegisteredShader { + Shader shader; + ShaderUserData userData; +}; +RegisteredShader VertexShader{}; +RegisteredShader PixelShader{}; + +const std::vector> ContextBaseline{ + {0x2d5, 0x2000}, + {0x1b6, 0}, {0x200, 0}, {0x203, 0x800}, + {0x2dc, 0xaa00}, {0x2f8, 0}, {0x292, 2}, {0x293, 0}, + {0x80, 0}, {0x8d, 0}, {0x83, 0xffff}, {0x8c, 0xa}, + {0x2f9, 0x2d}, {0x313, 0x6000}, {0x30e, 0xffffffff}, {0x30f, 0xffffffff}, + {0x206, 0x43f}, {0x204, 0x80000}, {0x205, 0x240}, + {0x8e, 0xf}, {0x8f, 0xf}, {0x202, 0xcc0010}, + {0x1c4, 0}, {0x1c5, 9}, {0x1c3, 4}, {0x31c, 0x28028}, + {0x31b, 0}, {0x31d, 0}, {0x3b8, 0x9000000}, {0x1e0, 0}, + {0xc, 0}, + {0x81, 0x80000000}, {0x90, 0x80000000}, {0x94, 0x80000000}, + {0xb4, 0}, {0xb5, std::bit_cast(1.0f)}, {0x114, 0}, {0x113, std::bit_cast(1.0f)}, +}; + +enum class Shape { Direct, Indexed, IndexedCount }; + +enum class Producer { Writer, Reader }; + +struct Case { + const char* name; + Shape shape; + Path path; + Producer producer; +}; + +constexpr Case GpuPath{"a draw whose records the GPU reads", Shape::Direct, Path::Gpu, Producer::Writer}; +constexpr Case CpuRecords{"an indexed draw with no INDEX_BUFFER_SIZE, its records read by the driver", Shape::Indexed, Path::IndexLimitUnknown, Producer::Writer}; +constexpr Case CpuCount{"an indexed multi-draw with no INDEX_BUFFER_SIZE, its count read by the driver before it decides the draw is not empty", Shape::IndexedCount, Path::IndexLimitUnknown, Producer::Writer}; +constexpr Case CpuRecordsReadOnly{"an indexed draw with no INDEX_BUFFER_SIZE behind a dispatch that only reads through addresses", Shape::Indexed, Path::IndexLimitUnknown, Producer::Reader}; +constexpr Case DisabledRecords{"a draw whose records are read on the CPU with APS5_NO_GPU_INDIRECT_DRAW", Shape::Direct, Path::Disabled, Producer::Writer}; + +std::byte* AllocateWatched(std::size_t bytes) { +#ifdef _WIN32 + void* block = GuestArena::GuestArenaAllocate_nid_postfix(bytes, Block); + GuestArena::GuestArenaCommit_nid_postfix(block, bytes, PAGE_READWRITE, bytes); +#else + void* raw = mmap(nullptr, bytes + Block, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); + if (raw == MAP_FAILED) throw std::runtime_error("indirect draw pending producer: cannot map the watched block"); + const auto begin = reinterpret_cast(raw); + const auto aligned = (begin + Block - 1) & ~static_cast(Block - 1); + if (aligned != begin) munmap(raw, aligned - begin); + if (aligned + bytes != begin + bytes + Block) munmap(reinterpret_cast(aligned + bytes), begin + Block - aligned); + void* block = reinterpret_cast(aligned); + GuestWriteWatch::GuestWriteWatchRegister_nid_postfix(block, bytes); +#endif + return static_cast(block); +} + +void Register(RegisteredShader& registered, const void* code, std::uint32_t bytes, std::uint8_t type) { + registered.shader.file_header = 0x34333231u; + registered.shader.version = 0x18u; + registered.shader.user_data = ®istered.userData; + registered.shader.code = code; + registered.shader.header_size = sizeof(RegisteredShader); + registered.shader.shader_size = bytes; + registered.shader.type = type; + AgcDriverRegisterShader_nid_postfix(®istered.shader); +} + +std::uint32_t Low(std::uintptr_t address) { + return static_cast(address); +} + +std::uint32_t High(std::uintptr_t address) { + return static_cast(static_cast(address) >> 32u); +} + +std::uintptr_t PoolAt(std::size_t offset) { + return reinterpret_cast(Pool + offset); +} + +void SetRegister(std::vector& words, std::uint32_t opcode, std::uint32_t offset, std::uint32_t value) { + words.push_back(0xc0010000u | (opcode << 8u)); + words.push_back(offset); + words.push_back(value); +} + +void Dispatch(std::vector& words, const void* program, std::span userData) { + const auto code = reinterpret_cast(program); + SetRegister(words, SetShReg, 0x20c, static_cast(code >> 8u)); + SetRegister(words, SetShReg, 0x20d, static_cast(static_cast(code) >> 40u) & 0xffu); + for (const std::uint32_t threads : {0x207u, 0x208u, 0x209u}) SetRegister(words, SetShReg, threads, 1u); + SetRegister(words, SetShReg, 0x212, 0u); + SetRegister(words, SetShReg, 0x213, static_cast(userData.size()) << 1u); + for (std::uint32_t i = 0; i < userData.size(); ++i) SetRegister(words, SetShReg, 0x240 + i, userData[i]); + words.insert(words.end(), {0xc0031500u, 1u, 1u, 1u, 0x41u}); +} + +void Produce(std::vector& words, std::size_t offset, std::array values) { + const auto target = PoolAt(offset); + const std::array userData{Low(target), High(target), values[0], values[1], values[2]}; + Dispatch(words, AddressWriterCode.data(), userData); +} + +void ReadRecord(std::vector& words) { + const auto source = PoolAt(RecordOffset); + const auto sink = PoolAt(SinkOffset); + const std::array userData{Low(source), High(source), 0u, 0u, Low(sink), High(sink) & 0xffffu, 16u, 0x31016facu}; + Dispatch(words, AddressReaderCode.data(), userData); +} + +std::vector Commands(Shape shape, bool produce) { + std::vector words; + if (produce && shape == Shape::IndexedCount) Produce(words, CountOffset, {1u, 0u, 0u}); + else if (produce) Produce(words, RecordOffset, {static_cast(Indices.size()), 1u, 0u}); + const auto colorAddress = reinterpret_cast(ColorMemory); + const auto vertexAddress = reinterpret_cast(VertexCode.data()); + const auto pixelAddress = reinterpret_cast(PixelCode.data()); + for (const auto& [offset, value] : ContextBaseline) SetRegister(words, SetContextReg, offset, value); + SetRegister(words, SetContextReg, 0x207, DistanceVector); + SetRegister(words, SetContextReg, 0x318, static_cast(colorAddress >> 8u)); + SetRegister(words, SetContextReg, 0x390, static_cast(static_cast(colorAddress) >> 40u)); + SetRegister(words, SetContextReg, 0x3b0, ((Width - 1u) << 14u) | (Height - 1u)); + SetRegister(words, SetContextReg, 0x10f, std::bit_cast(Width / 2.0f)); + SetRegister(words, SetContextReg, 0x110, std::bit_cast(Width / 2.0f)); + SetRegister(words, SetContextReg, 0x111, std::bit_cast(-(Height / 2.0f))); + SetRegister(words, SetContextReg, 0x112, std::bit_cast(Height / 2.0f)); + const auto extent = (Height << 16u) | Width; + SetRegister(words, SetContextReg, 0xd, extent); + SetRegister(words, SetContextReg, 0x82, extent); + SetRegister(words, SetContextReg, 0x91, extent); + SetRegister(words, SetContextReg, 0x95, extent); + SetRegister(words, SetUconfigReg, 0x242, 4u); + SetRegister(words, SetShReg, 0x008, static_cast(pixelAddress >> 8u)); + SetRegister(words, SetShReg, 0x009, static_cast(static_cast(pixelAddress) >> 40u)); + SetRegister(words, SetShReg, 0x00b, 0u); + SetRegister(words, SetShReg, 0x0c8, static_cast(vertexAddress >> 8u)); + SetRegister(words, SetShReg, 0x0c9, static_cast(static_cast(vertexAddress) >> 40u)); + SetRegister(words, SetShReg, 0x08b, 4u << 1u); + const auto vertices = PoolAt(VertexOffset); + const std::array descriptor{Low(vertices), (High(vertices) & 0xffffu) | (static_cast(sizeof(Vertex)) << 16u), static_cast(Vertices.size()), 0x01016facu}; + for (std::uint32_t i = 0; i < descriptor.size(); ++i) SetRegister(words, SetShReg, 0x08c + i, descriptor[i]); + words.insert(words.end(), {0xc0021100u, 1u, Low(PoolAt(0)), High(PoolAt(0))}); + SetRegister(words, SetUconfigReg, 0x24a, 0u); + if (shape == Shape::Direct) { + words.insert(words.end(), {0xc0032400u, static_cast(RecordOffset), 0u, 0u, 2u}); + return words; + } + words.insert(words.end(), {0xc0012600u, Low(PoolAt(0)), High(PoolAt(0))}); + SetRegister(words, SetUconfigReg, 0x243, 0x401u); + if (shape == Shape::Indexed) { + words.insert(words.end(), {0xc0032500u, static_cast(RecordOffset), 0u, 0u, 0u}); + } else { + const auto count = PoolAt(CountOffset); + words.insert(words.end(), {0xc0083800u, static_cast(RecordOffset), 0u, 0u, 1u << 30u, 1u, Low(count), High(count), 20u, 0u}); + } + return words; +} + +std::uint32_t PoolWord(std::size_t offset) { + std::uint32_t value = 0; + AgcDriver::GuestMemory::Read(static_cast(PoolAt(offset)), std::as_writable_bytes(std::span(&value, 1)), 4); + return value; +} + +void ResetPool(bool record) { + std::memset(Pool, 0, PoolBytes); + std::memcpy(Pool, Indices.data(), Indices.size() * sizeof(std::uint32_t)); + std::memcpy(Pool + VertexOffset, Vertices.data(), sizeof(Vertex) * Vertices.size()); + if (record) { + const std::array words{static_cast(Indices.size()), 1u, 0u, 0u, 0u}; + std::memcpy(Pool + RecordOffset, words.data(), sizeof(words)); + } +} + +std::size_t WrittenPixels() { + std::vector colors(ColorBytes); + AgcDriver::GuestMemory::Read(static_cast(reinterpret_cast(ColorMemory)), colors); + std::size_t written = 0; + for (std::uint32_t pixel = 0; pixel < Width * Height; ++pixel) { + const auto value = std::to_integer(colors[pixel * 4u]); + Require(value == 0u || value == 255u, "indirect draw pending producer: pixel " + std::to_string(pixel) + " stored " + std::to_string(value)); + written += value == 255u ? 1u : 0u; + } + return written; +} + +void Submit(const Case& test, Shape shape, bool produce) { + std::vector words; + if (produce && test.producer == Producer::Reader) ReadRecord(words); + const auto commands = Commands(shape, produce && test.producer == Producer::Writer); + words.insert(words.end(), commands.begin(), commands.end()); + Packet packet{words.data(), static_cast(words.size()), 0, {}}; + Require(sceAgcDriverSubmitDcb(&packet) == 0, std::string(test.name) + ": the submission failed"); + AgcDriverWaitIdle_nid_postfix(); +} + +void PrimeCpuPath(const Case& test) { + ResetPool(true); + std::memset(ColorMemory, 0, ColorBytes); + const auto paths = AgcDriver::Graphics::IndirectDrawCounts(); + Submit(test, Shape::Indexed, false); + const auto taken = AgcDriver::Graphics::IndirectDrawCounts()[static_cast(test.path)] - paths[static_cast(test.path)]; + Require(taken == 1 && WrittenPixels() == Width * Height, std::string(test.name) + ": the indexed draw that marks its vertex program as read by the driver did not draw through the " + AgcDriver::Graphics::IndirectDrawPathName(test.path) + " path"); +} + +std::string Run(const Case& test) { + if (test.shape == Shape::IndexedCount) PrimeCpuPath(test); + const bool reader = test.producer == Producer::Reader; + ResetPool(test.shape == Shape::IndexedCount || reader); + std::memset(ColorMemory, 0, ColorBytes); + const auto leases = AgcDriver::Graphics::LeaseCounters(); + const auto paths = AgcDriver::Graphics::IndirectDrawCounts(); + const auto empty = AgcDriver::Graphics::EmptyIndirectDrawCount(); + Submit(test, test.shape, true); + const auto pathsAfter = AgcDriver::Graphics::IndirectDrawCounts(); + auto taken = pathsAfter[static_cast(test.path)] - paths[static_cast(test.path)]; + const auto notImported = pathsAfter[static_cast(Path::NotImported)] - paths[static_cast(Path::NotImported)]; + if (test.path == Path::Gpu && taken == 0 && notImported == 1) { + std::cout << test.name << ": the device has no host import of the records, so it read them on the CPU\n"; + taken = 1; + } + const auto skipped = AgcDriver::Graphics::EmptyIndirectDrawCount() - empty; + const auto written = WrittenPixels(); + const auto leasesAfter = AgcDriver::Graphics::LeaseCounters(); + if (leasesAfter.deferred == leases.deferred) return "the address-based dispatch did not defer its lease, so the draw had no pending producer to wait for"; + if (reader && leasesAfter.writing != leases.writing) return "a dispatch that only reads through addresses was counted as a lease that can write"; + if (!reader && leasesAfter.writing == leases.writing) return "the address-based store was not counted as a lease that can write, so the draw would not wait for it"; + if (reader && PoolWord(SinkOffset) != Indices.size()) return "the address-based read stored " + std::to_string(PoolWord(SinkOffset)) + " in its buffer, expected the record's " + std::to_string(Indices.size()) + " vertices"; + const bool count = test.shape == Shape::IndexedCount; + const auto produced = count ? PoolWord(CountOffset) : PoolWord(RecordOffset); + const std::uint32_t expected = count ? 1u : static_cast(Indices.size()); + if (produced != expected) return "the producer's address-based store left " + std::to_string(produced) + " in the " + (count ? "count" : "record") + ", expected " + std::to_string(expected); + if (written != Width * Height) return "the draw wrote " + std::to_string(written) + " of " + std::to_string(Width * Height) + " pixels (" + std::to_string(skipped) + " skipped as empty, " + std::to_string(taken) + " through the " + AgcDriver::Graphics::IndirectDrawPathName(test.path) + " path), expected the triangle its producer's " + (count ? "count" : "record") + " names"; + if (taken != 1 || skipped != 0) return "the draw went through the " + std::string(AgcDriver::Graphics::IndirectDrawPathName(test.path)) + " path " + std::to_string(taken) + " times and was skipped as empty " + std::to_string(skipped) + " times, expected once and never"; + return {}; +} + +} + +int main(int argc, char** argv) { +#ifdef _WIN32 + _putenv_s("APS5_PROFILE_DRAW", "1"); +#else + setenv("APS5_PROFILE_DRAW", "1", 1); +#endif + const bool disabled = argc > 1 && std::string(argv[1]) == "--gpu-indirect-disabled"; + try { + if (disabled) Require(std::getenv("APS5_NO_GPU_INDIRECT_DRAW") != nullptr, "--gpu-indirect-disabled needs APS5_NO_GPU_INDIRECT_DRAW=1"); + { + const auto device = OpenVulkanTestDevice(); + if (!device) return VulkanTestSkipped; + } + ColorMemory = AllocateWatched(2 * Block); + Pool = AllocateWatched(PoolBytes); + GuestAllocations::Mutation().Add(Pool, PoolBytes, true, true, true); + Register(VertexShader, VertexCode.data(), sizeof(VertexCode), 2); + Register(PixelShader, PixelCode.data(), sizeof(PixelCode), 1); + for (std::size_t i = 0; i < Vertices.size(); ++i) Vertices[i] = {{PositionX[i], PositionY[i], 0.5f, 1.0f}, {-1.0f, -1.0f, -1.0f, 0.0f}}; + const std::vector cases = disabled ? std::vector{DisabledRecords} : std::vector{GpuPath, CpuRecords, CpuCount, CpuRecordsReadOnly}; + std::size_t failed = 0; + for (const auto& test : cases) { + const auto failure = Run(test); + if (failure.empty()) { + std::cout << test.name << ": passed\n"; + } else { + std::cerr << test.name << ": " << failure << '\n'; + ++failed; + } + } + AgcDriverShutdown_nid_postfix(); + if (failed != 0) return 1; + std::cout << "indirect draw pending producer tests passed\n"; + return 0; + } catch (const std::exception& error) { + std::cerr << error.what() << '\n'; + AgcDriverShutdown_nid_postfix(); + return 1; + } +} diff --git a/docs/dev/debt/libSceAgcDriver.md b/docs/dev/debt/libSceAgcDriver.md index d92f05c9f818..76c665817dd1 100644 --- a/docs/dev/debt/libSceAgcDriver.md +++ b/docs/dev/debt/libSceAgcDriver.md @@ -259,7 +259,7 @@ - [SET_*_REG_INDIRECT](../../../core/libs/prx/libSceAgcDriver/Execution/src/Driver/Queues/Submission.cpp) (libSceAgcDriver) reads its register list when the command buffer is submitted, with the packets. The console's graphics PFP reads it when it reaches the packet, so a list written after the submission (by the CPU, or by GPU work ahead of the packet behind PFP_SYNC_ME) is read here before that write. When the list read at submission holds an offset dword that is not a register offset (bits 16-27 set, or the 0xffffffff sentinel), the worker reads the list again where the packet executes and writes that copy. PPSA23566 (UFC 6) intermittently submits a SET_CONTEXT_REG_INDIRECT whose first entry is 0x038f038f or 0x03900390 in both copies; what the PFP does with such an entry is unknown, so a copy that still holds one throws unless `APS5_SKIP_INVALID_INDIRECT_REGISTERS=1`, which skips its invalid entries and writes its valid ones. - The [shader float mode](../../../core/libs/prx/libSceAgcDriver/Execution/src/Driver/Shaders/ShaderRegistry.cpp) (`FLOAT_MODE`, `DX10_CLAMP`, `IEEE_MODE` and `FP16_OVFL` of `COMPUTE_PGM_RSRC1` and `SPI_SHADER_PGM_RSRC1_PS/GS/HS`, bit positions from Mesa's `gfx10.json` and `gfx103.json`) is decoded into `GuestContext::floatMode` and is part of the shader cache keys and the serialized request (#981). `IEEE_MODE` is read by `v_min_f32`, `v_max_f32`, `v_min3_f32`, `v_max3_f32` and `v_med3_f32`, their f16 forms, `v_min_f64` and `v_max_f64`, `IEEE_MODE` and the `FLOAT_MODE` output denormal bits by the output modifier, `DX10_CLAMP` by the clamp modifier, `FP16_OVFL` by every instruction with an f16 result (see its entry), and the whole mode by the 16-bit interpolation instructions (see their entries). With IEEE=1 a signaling NaN operand returns that NaN quieted (the first operand checked first, min3/max3 as two nested pairs, med3 as min3 when any operand is NaN), measured on RDNA2 (gfx1035) over every combination of ±0, ±1, ±inf, denormals, quiet and signaling NaNs with f32 denormals kept and flushed. IEEE=0 and unknown modes keep the previous f32 lowering, which matches IEEE=0. The f16 forms choose their NaN results on the bits: a NaN operand returns the other operand unchanged (src0 when both are NaN), and with IEEE=1 a signaling NaN operand returns that NaN quieted, in the same order as f32. `v_min_f64` and `v_max_f64` quiet a signaling NaN operand the same way with IEEE=1; with IEEE=0 they return src0 unchanged when src1 is NaN, otherwise src1 when src0 is NaN. Both were measured on RDNA2 (gfx1036) at IEEE=0 and IEEE=1 with f32 denormals kept and flushed and f16/f64 denormals kept; RDNA2 has no f64 min3, max3 or med3. Unknown modes follow IEEE=0. `v_min_f16` and `v_max_f16` flush each denormal input to its signed zero when bit 0 of the f16/f64 denormal field is clear (0 and 2); fields 1 and 3 preserve inputs, even when output flushing is enabled. Measured on RDNA2 (gfx1036) at IEEE=0 and IEEE=1, including signed zeros, NaNs and neg/abs modifiers. Unknown modes keep f16 denormals. `v_min_f64` and `v_max_f64` flush subnormal inputs to signed zero when bit 0 of the f16/f64 denormal field is clear (0 and 2); fields 1 and 3, and an unknown mode, preserve inputs. The fully flushed and preserved f64 behavior was [measured on gfx1036](https://github.com/boykopovar/AnyPS5/pull/2036); split-mode selection follows [LLVM's denormal-mode enumeration](https://llvm.org/docs/AMDGPUUsage.html#floating-point-denorm-mode-enumeration-values). `v_fma_f64`, `v_div_fmas_f64`, `v_div_scale_f64`, `v_ldexp_f64`, `v_rcp_f64`, `v_rsq_f64`, `v_sqrt_f64` and `v_trig_preop_f64` do not model these denormal controls. NaN quieting in f16 arithmetic (the unary instructions and the f32 arithmetic follow it, see below) still follows a single mode, as the entries below record. The mode comes from the registered shader header's `sh_registers`, the same source at registration and at draw/dispatch so the prepared artifact keys match. A registered shader keeps that mode when a title rewrites RSRC1; a raw compute program takes the live RSRC1. - A [WAIT_REG_MEM](../../../core/libs/prx/libSceAgcDriver/Execution/src/Driver/Synchronization/WaitMemory.cpp) (libSceAgcDriver) that a compute queue passes on another queue's recorded label store, before the GPU has executed it, is landed before the queue's next dispatch, draw, COND_EXEC or predicated packet reads guest memory: the worker polls until memory satisfies the wait or no unfinished batch writes the label. The graphics queue (queue 0) is exempt, as landing its waits costs PPSA01341 about a quarter of its frame rate; a title that fills memory a graphics command buffer reads after it submits the buffer behind such a wait reads it early there, unless the fill lands before the draw or dispatch reading it is recorded: the worker compares the memory a draw or dispatch captured with guest memory before recording or queuing it, and prepares it again once from current memory when they differ. `APS5_LAND_WAITS_ALL_QUEUES=1` lands the graphics queue's waits too. -- [CPU reads behind an address-based build](../../../core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/Draw.cpp) (libSceAgcDriver) - an address-based store (FLAT/GLOBAL, or through a descriptor the recompiler cannot resolve to a static buffer) is not recorded as a pending write: its batch holds a lease on the registered allocations instead, and the flush hook does not wait for it. A DISPATCH_INDIRECT whose arguments are read on the CPU first finishes the batches recorded with a lease (`Graphics::FinishLeaseWork`). These reads do not, so they can see guest memory from before such a build ran: the indirect draw arguments and draw count of a draw resolved on the CPU (`Pm4::ReadDrawArguments`, `Pm4::ReadDrawCount`), the count record of the [copy kernel](../../../core/libs/prx/libSceAgcDriver/Execution/src/Driver/Memory/BufferCopy.cpp) HLE (guarded only by its shape check), and the checks in [Submission.cpp](../../../core/libs/prx/libSceAgcDriver/Execution/src/Driver/Queues/Submission.cpp) that decide whether a queue awaits a label only the title writes (`awaitsTitle`, `orderReleased`). No test covers them and no title has been seen to read such memory there. +- [CPU reads behind an address-based build](../../../core/libs/prx/libSceAgcDriver/Execution/src/Driver/Memory/BufferCopy.cpp) (libSceAgcDriver) - these CPU reads do not wait for an address-based store (FLAT/GLOBAL, or through an unresolved descriptor) and can see guest memory from before it: the non-indexed copy kernel's count record, the record `recordMeshArguments` reads while recording, the checks in [Submission.cpp](../../../core/libs/prx/libSceAgcDriver/Execution/src/Driver/Queues/Submission.cpp) on whether a queue awaits a label only the title writes (`awaitsTitle`, `orderReleased`), and the indirect draw reads behind a draw that queue 0's draw pipeline has queued but not yet recorded. Such a store is not recorded as a pending write: its batch holds a lease, which the flush hook does not wait for. No test puts an address-based store before any of the four, and no title has been seen to read such memory there. - The [dispatches that follow a compute queue's wait](../../../core/libs/prx/libSceAgcDriver/Execution/src/Driver/Dispatch/DispatchAhead.cpp) (libSceAgcDriver), up to the next wait that memory does not satisfy, a packet that writes guest memory other than a label, or a conditional packet, are resolved (memory captured, shader recompiled) when the wait passes, as the CP reads them right after it; the graphics queue is exempt (`APS5_GROUP_CAPTURE_ALL_QUEUES=1` includes it). The device still reads guest memory when the dispatch is issued; when that memory no longer matches the capture, the dispatch is resolved again from current memory. - [PA_CL_CLIP_CNTL](../../../core/libs/prx/libSceAgcDriver/Graphics/src/State.cpp) (libSceAgcDriver) - `CLIP_DISABLE` (bit 16) and `DX_LINEAR_ATTR_CLIP_ENA` (bit 24) are accepted without changing pipeline state: Vulkan clips primitives against viewport guard bands and clips `NoPerspective` outputs linearly; what clearing bit 24 or setting bit 16 changes on the console beyond standard clipping is undocumented. - [10_11_11 unorm color targets](../../../core/libs/prx/libSceAgcDriver/Graphics/src/State.cpp) (libSceAgcDriver) render into R32_UINT attachments: the pixel shader packs each export, rounded to nearest even like format-30 image stores, which is assumed to match the CB's conversion.