diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/Draw.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/Draw.hpp index ba77615d8..13bbe2103 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/Draw.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/Draw.hpp @@ -6,6 +6,7 @@ #include "prx/libSceAgcDriver/Graphics/include/Pipeline.hpp" #include "prx/libSceAgcDriver/Execution/include/Pm4.hpp" #include "prx/libSceAgcDriver/Execution/include/Recipe.hpp" +#include "prx/libSceAgcDriver/Graphics/include/Recorder.hpp" #include #include @@ -17,6 +18,16 @@ namespace AgcDriver::Graphics { void Draw(const Context& context, const State& state, const Pm4::DrawParameters& draw, std::span shaders, std::span snapshots = {}, std::shared_ptr* recipe = nullptr); std::optional KnownValidationFailure(const Context& context, std::span shaders, const State& state); +struct DrawInputCopy { + std::shared_ptr buffer; + bool reused = false; + std::uint32_t derived = 0; + std::uint64_t generation = 0; + std::uint64_t registryGeneration = 0; +}; +DrawInputCopy CopyDrawInput(const Context& context, Recorder* recorder, std::uint64_t address, std::size_t bytes, std::size_t alignment, Recorder::SnapshotUse use); +void KeepDrawInput(Recorder* recorder, std::uint64_t address, const DrawInputCopy& copy, Recorder::SnapshotUse use, std::uint32_t derived); + std::array MeshIndexBufferDescriptor(const Pm4::DrawParameters& draw, std::uint64_t unreadAddress); // Why DrawWithRecipe did not record from the recipe (the caller then runs Draw): the draw is not diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/Recorder.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/Recorder.hpp index eb15bda52..816f8844a 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/Recorder.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/Recorder.hpp @@ -94,10 +94,13 @@ public: // neither the mutex nor the recorder nor a particular thread. ~Recorder joins the release // thread and waits for every release in progress before the device goes. void Keep(std::shared_ptr object); + enum class SnapshotUse : std::uint8_t { Storage, Vertex, Index16, Index32 }; static constexpr std::size_t DrawSnapshotBudget = std::size_t{256} << 20u; static constexpr std::size_t DrawSnapshotEntries = 1024; - std::shared_ptr ReusableDrawSnapshot(std::uint64_t address, std::size_t bytes); - void KeepDrawSnapshot(std::uint64_t address, std::size_t bytes, std::uint64_t generation, std::uint64_t registryGeneration, std::shared_ptr buffer); + static constexpr std::size_t DrawInputBudget = std::size_t{1024} << 20u; + static constexpr std::size_t DrawInputEntries = 16384; + std::shared_ptr ReusableDrawSnapshot(std::uint64_t address, std::size_t bytes, SnapshotUse use = SnapshotUse::Storage, std::uint32_t* derived = nullptr); + void KeepDrawSnapshot(std::uint64_t address, std::size_t bytes, std::uint64_t generation, std::uint64_t registryGeneration, std::shared_ptr buffer, SnapshotUse use = SnapshotUse::Storage, std::uint32_t derived = 0); void OnComplete(std::function action); void NotePendingWrite(std::uint64_t address, std::size_t bytes); // Notes several [begin, end) ranges and publishes the snapshot once (a dispatch writes many buffers). @@ -694,16 +697,20 @@ private: std::array completed; std::uint64_t newestSubmitted = 0; std::chrono::steady_clock::time_point newestSubmittedAt{}; - using DrawSnapshotKey = std::pair; + using DrawSnapshotKey = std::tuple; struct DrawSnapshot { std::uint64_t generation; std::uint64_t registryGeneration; std::list::iterator recent; std::shared_ptr buffer; + std::uint32_t derived; + }; + struct DrawSnapshotPool { + std::list recency; + std::size_t bytes = 0; }; std::map drawSnapshots; - std::list drawSnapshotRecency; - std::size_t drawSnapshotBytes = 0; + std::array drawSnapshotPools; void eraseDrawSnapshot(std::map::iterator entry); }; diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp index 9aca4f99a..1c9e47706 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp @@ -12,6 +12,7 @@ #include "prx/libSceAgcDriver/Execution/include/CaptureTrace.hpp" #include "prx/libSceAgcDriver/Execution/include/PerformanceTimer.hpp" #include "prx/libc/include/General.hpp" +#include "prx/libc/include/GuestAllocations.hpp" #include "Optimization/include/Optimization/ShaderStageInputInfo.hpp" #include #include @@ -670,6 +671,33 @@ void reportDrawEnd(const State& state, const DrawTimer& timer, const ShaderResou reportDraw(timer.us, built, outcome); } +} + +DrawInputCopy CopyDrawInput(const Context& context, Recorder* recorder, std::uint64_t address, std::size_t bytes, std::size_t alignment, Recorder::SnapshotUse use) { + Require(use != Recorder::SnapshotUse::Storage, "a draw input is a vertex or index buffer"); + DrawInputCopy copy; + if (recorder != nullptr && bytes != 0) { + GuestMemory::FlushGpuWrites(address, bytes); + copy.registryGeneration = GuestAllocations::GuestAllocationsGeneration_nid_postfix(); + copy.generation = GuestMemory::CollectWrites(address, bytes); + if (copy.generation != 0) copy.buffer = recorder->ReusableDrawSnapshot(address, bytes, use, ©.derived); + if (copy.buffer != nullptr) { + copy.reused = true; + return copy; + } + } + copy.buffer = std::make_shared(context, bytes, use == Recorder::SnapshotUse::Vertex ? VK_BUFFER_USAGE_VERTEX_BUFFER_BIT : VK_BUFFER_USAGE_INDEX_BUFFER_BIT); + GuestMemory::Read(address, copy.buffer->Bytes(), alignment); + return copy; +} + +void KeepDrawInput(Recorder* recorder, std::uint64_t address, const DrawInputCopy& copy, Recorder::SnapshotUse use, std::uint32_t derived) { + if (recorder == nullptr || copy.reused || copy.generation == 0 || copy.buffer == nullptr) return; + recorder->KeepDrawSnapshot(address, copy.buffer->Bytes().size(), copy.generation, copy.registryGeneration, copy.buffer, use, derived); +} + +namespace { + // The draw's inputs before its resources (prepareDrawInputs): the validated parameters, the index // buffer copy with its highest index, the vertex buffer copies and their layout, the fragment // outputs and the pipeline stages. @@ -677,10 +705,10 @@ struct DrawInputs { // An empty auto draw: nothing to record. bool nothing = false; std::uint64_t indexBytes = 0; - std::unique_ptr indices; + std::shared_ptr indices; std::uint32_t maxIndex = 0; VertexInputLayout vertexInput; - std::vector> vertexBuffers; + std::vector> vertexBuffers; std::vector vertexHandles; std::vector vertexOffsets; std::set fragmentOutputs; @@ -753,20 +781,28 @@ DrawInputs prepareDrawInputs(const Context& context, const State& state, const P timer.phase(PhaseValidate); inputs.maxIndex = draw.indexed ? 0u : draw.firstVertex + draw.indexCount - 1u; if (draw.indexed) { - inputs.indices = std::make_unique(context, static_cast(indexBytes), VK_BUFFER_USAGE_INDEX_BUFFER_BIT); - GuestMemory::Read(draw.indexAddress, inputs.indices->Bytes(), draw.indexSize); - for (std::size_t offset = 0; offset < indexBytes; offset += draw.indexSize) { - std::uint32_t index = 0; - if (draw.indexSize == 2) { - std::uint16_t value = 0; - std::memcpy(&value, inputs.indices->Bytes().data() + offset, sizeof(value)); - index = value; - } else { - std::memcpy(&index, inputs.indices->Bytes().data() + offset, sizeof(index)); + const auto use = draw.indexSize == 2 ? Recorder::SnapshotUse::Index16 : Recorder::SnapshotUse::Index32; + auto copy = CopyDrawInput(context, context.recorder, draw.indexAddress, static_cast(indexBytes), draw.indexSize, use); + std::uint32_t highest = copy.derived; + if (!copy.reused) { + highest = 0; + const auto bytes = copy.buffer->Bytes(); + for (std::size_t offset = 0; offset < indexBytes; offset += draw.indexSize) { + std::uint32_t index = 0; + if (draw.indexSize == 2) { + std::uint16_t value = 0; + std::memcpy(&value, bytes.data() + offset, sizeof(value)); + index = value; + } else { + std::memcpy(&index, bytes.data() + offset, sizeof(index)); + } + highest = std::max(highest, index); } - Require(index <= context.limits.maxDrawIndexedIndexValue, "index exceeds the device's indexed draw limit"); - inputs.maxIndex = std::max(inputs.maxIndex, index); + KeepDrawInput(context.recorder, draw.indexAddress, copy, use, highest); } + Require(highest <= context.limits.maxDrawIndexedIndexValue, "index exceeds the device's indexed draw limit"); + inputs.maxIndex = highest; + inputs.indices = std::move(copy.buffer); } APS5_LOG_CHARS_OUT_DEBUG("Index validation OK"); const auto& attributes = shaders.front().program->vertexAttributes; @@ -786,10 +822,10 @@ DrawInputs prepareDrawInputs(const Context& context, const State& state, const P const auto address = fields[0] | (static_cast(fields[1] & 0xffffu) << 32u); Require(!state.hasColorTarget || address + bytes <= state.color.address || state.color.address + state.color.bytes <= address, "vertex buffer aliases the render target"); GuestMemory::CheckRange(reinterpret_cast(address), bytes, 1); - auto buffer = std::make_unique(context, bytes, VK_BUFFER_USAGE_VERTEX_BUFFER_BIT); - GuestMemory::Read(address, buffer->Bytes(), 1); - inputs.vertexHandles.push_back(buffer->Handle()); - inputs.vertexBuffers.push_back(std::move(buffer)); + auto copy = CopyDrawInput(context, context.recorder, address, bytes, 1, Recorder::SnapshotUse::Vertex); + KeepDrawInput(context.recorder, address, copy, Recorder::SnapshotUse::Vertex, 0); + inputs.vertexHandles.push_back(copy.buffer->Handle()); + inputs.vertexBuffers.push_back(std::move(copy.buffer)); } timer.phase(PhaseVertex); return inputs; @@ -1010,8 +1046,8 @@ struct Kept { std::shared_ptr resources; std::shared_ptr pipeline; std::shared_ptr framebuffer; - std::unique_ptr indices; - std::vector> vertexBuffers; + std::shared_ptr indices; + std::vector> vertexBuffers; std::vector> targets; std::unique_ptr scratch; }; diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp index 1ac0b93a9..0c25fe4f6 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp @@ -1919,36 +1919,53 @@ void Recorder::Keep(std::shared_ptr object) { open->kept.push_back(std::move(object)); } +namespace { +std::size_t SnapshotPool(Recorder::SnapshotUse use) { + return use == Recorder::SnapshotUse::Storage ? 0 : 1; +} +} + void Recorder::eraseDrawSnapshot(std::map::iterator entry) { - drawSnapshotBytes -= entry->first.second; - drawSnapshotRecency.erase(entry->second.recent); + auto& pool = drawSnapshotPools[SnapshotPool(std::get<1>(entry->first))]; + pool.bytes -= std::get<2>(entry->first); + pool.recency.erase(entry->second.recent); drawSnapshots.erase(entry); } -std::shared_ptr Recorder::ReusableDrawSnapshot(std::uint64_t address, std::size_t bytes) { - const auto found = drawSnapshots.find({address, bytes}); - if (found == drawSnapshots.end()) return {}; +std::shared_ptr Recorder::ReusableDrawSnapshot(std::uint64_t address, std::size_t bytes, SnapshotUse use, std::uint32_t* derived) { + auto found = use == SnapshotUse::Vertex ? drawSnapshots.lower_bound({address, use, bytes}) : drawSnapshots.find({address, use, bytes}); + if (found == drawSnapshots.end() || std::get<0>(found->first) != address || std::get<1>(found->first) != use) return {}; if (found->second.registryGeneration != GuestAllocations::GuestAllocationsGeneration_nid_postfix() || !GuestMemory::UnchangedSince(address, bytes, found->second.generation)) { eraseDrawSnapshot(found); return {}; } - drawSnapshotRecency.splice(drawSnapshotRecency.end(), drawSnapshotRecency, found->second.recent); + auto& recency = drawSnapshotPools[SnapshotPool(use)].recency; + recency.splice(recency.end(), recency, found->second.recent); + if (derived != nullptr) *derived = found->second.derived; return found->second.buffer; } -void Recorder::KeepDrawSnapshot(std::uint64_t address, std::size_t bytes, std::uint64_t generation, std::uint64_t registryGeneration, std::shared_ptr buffer) { - if (generation == 0 || bytes > DrawSnapshotBudget) return; - if (const auto found = drawSnapshots.find({address, bytes}); found != drawSnapshots.end()) eraseDrawSnapshot(found); - while (!drawSnapshots.empty() && (drawSnapshotBytes + bytes > DrawSnapshotBudget || drawSnapshots.size() >= DrawSnapshotEntries)) eraseDrawSnapshot(drawSnapshots.find(drawSnapshotRecency.front())); - const DrawSnapshotKey key{address, bytes}; - drawSnapshotRecency.push_back(key); +void Recorder::KeepDrawSnapshot(std::uint64_t address, std::size_t bytes, std::uint64_t generation, std::uint64_t registryGeneration, std::shared_ptr buffer, SnapshotUse use, std::uint32_t derived) { + const bool storage = use == SnapshotUse::Storage; + const auto budget = storage ? DrawSnapshotBudget : DrawInputBudget; + const auto maxEntries = storage ? DrawSnapshotEntries : DrawInputEntries; + auto& pool = drawSnapshotPools[SnapshotPool(use)]; + if (generation == 0 || bytes > budget) return; + if (use == SnapshotUse::Vertex) { + for (auto it = drawSnapshots.lower_bound({address, use, 0}); it != drawSnapshots.end() && std::get<0>(it->first) == address && std::get<1>(it->first) == use && std::get<2>(it->first) <= bytes;) eraseDrawSnapshot(it++); + } else if (const auto found = drawSnapshots.find({address, use, bytes}); found != drawSnapshots.end()) { + eraseDrawSnapshot(found); + } + while (!pool.recency.empty() && (pool.bytes + bytes > budget || pool.recency.size() >= maxEntries)) eraseDrawSnapshot(drawSnapshots.find(pool.recency.front())); + const DrawSnapshotKey key{address, use, bytes}; + pool.recency.push_back(key); try { - drawSnapshots.emplace(key, DrawSnapshot{generation, registryGeneration, std::prev(drawSnapshotRecency.end()), std::move(buffer)}); + drawSnapshots.emplace(key, DrawSnapshot{generation, registryGeneration, std::prev(pool.recency.end()), std::move(buffer), derived}); } catch (...) { - drawSnapshotRecency.pop_back(); + pool.recency.pop_back(); throw; } - drawSnapshotBytes += bytes; + pool.bytes += bytes; } void Recorder::OnComplete(std::function action) { diff --git a/core/libs/prx/libSceAgcDriver/tests/Recorder.cpp b/core/libs/prx/libSceAgcDriver/tests/Recorder.cpp index 615df730b..4034f78e6 100644 --- a/core/libs/prx/libSceAgcDriver/tests/Recorder.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/Recorder.cpp @@ -1007,6 +1007,7 @@ void drawSnapshotEvictionTests(const Device& device) { const auto generation = CollectWrites(address, 4096); Require(generation != 0, "the watched block has no generation"); constexpr auto cap = Recorder::DrawSnapshotEntries; + cache.KeepDrawSnapshot(address, 16, generation, registry, buffer, Recorder::SnapshotUse::Vertex); for (std::size_t size = 1; size <= cap; ++size) cache.KeepDrawSnapshot(address, size, generation, registry, buffer); Require(cache.ReusableDrawSnapshot(address, 1) == buffer, "a kept snapshot is not reusable"); cache.KeepDrawSnapshot(address, cap + 1, generation, registry, buffer); @@ -1014,6 +1015,7 @@ void drawSnapshotEvictionTests(const Device& device) { Require(cache.ReusableDrawSnapshot(address, 1) == buffer && cache.ReusableDrawSnapshot(address, 3) == buffer && cache.ReusableDrawSnapshot(address, cap + 1) == buffer, "eviction dropped a more recently used snapshot"); cache.KeepDrawSnapshot(address, cap + 2, generation, registry, buffer); Require(cache.ReusableDrawSnapshot(address, 4) == nullptr && cache.ReusableDrawSnapshot(address, 1) == buffer, "the second eviction did not take the next oldest"); + Require(cache.ReusableDrawSnapshot(address, 16, Recorder::SnapshotUse::Vertex) == buffer, "storage snapshots evicted a vertex snapshot"); cache.KeepDrawSnapshot(address, 1, generation, registry, buffer); Require(cache.ReusableDrawSnapshot(address, 1) == buffer && cache.ReusableDrawSnapshot(address, 5) == buffer, "replacing a kept snapshot evicted another"); cache.KeepDrawSnapshot(address + 8192, Recorder::DrawSnapshotBudget, generation, registry, buffer); @@ -1024,6 +1026,82 @@ void drawSnapshotEvictionTests(const Device& device) { Require(cache.ReusableDrawSnapshot(address, 16) == nullptr && cache.ReusableDrawSnapshot(address, 16) == nullptr, "a snapshot outlived a CPU store"); } +void drawInputReuseTests(const Device& device, Recorder& recorder) { + using namespace AgcDriver::GuestMemory; + using Use = Recorder::SnapshotUse; + constexpr std::size_t bytes = 65536; + void* block = WriteWatched() ? AllocateWatched(bytes, 65536) : nullptr; + if (block == nullptr) { + std::cout << "write watching unavailable: draw input reuse not tested\n"; + return; + } + struct Release { + void* block; + ~Release() { ReleaseWatched(block, bytes); } + } release{block}; + const auto& context = device.GetContext(); + auto* words = static_cast(block); + for (std::uint32_t i = 0; i < bytes / sizeof(std::uint32_t); ++i) words[i] = i * 3; + const auto address = reinterpret_cast(block); + constexpr std::size_t size = 256; + const auto equalsGuest = [&](const DrawInputCopy& copy) { + const auto contents = copy.buffer->Bytes(); + return contents.size() == size && std::memcmp(contents.data(), block, size) == 0; + }; + const auto first = CopyDrawInput(context, &recorder, address, size, 4, Use::Index32); + Require(!first.reused && first.generation != 0 && equalsGuest(first), "the first draw input copy is wrong"); + KeepDrawInput(&recorder, address, first, Use::Index32, 189); + const auto second = CopyDrawInput(context, &recorder, address, size, 4, Use::Index32); + Require(second.reused && second.buffer == first.buffer && second.derived == 189, "an unchanged draw input was copied again"); + const auto vertex = CopyDrawInput(context, &recorder, address, size, 1, Use::Vertex); + const auto narrow = CopyDrawInput(context, &recorder, address, size, 2, Use::Index16); + Require(!vertex.reused && !narrow.reused && equalsGuest(vertex) && equalsGuest(narrow), "a draw input reused another use's copy"); + KeepDrawInput(&recorder, address, vertex, Use::Vertex, 0); + Require(CopyDrawInput(context, &recorder, address, size, 1, Use::Vertex).buffer == vertex.buffer && CopyDrawInput(context, &recorder, address, size, 4, Use::Index32).buffer == first.buffer, "the uses' copies displaced each other"); + Require(!CopyDrawInput(context, nullptr, address, size, 4, Use::Index32).reused, "a draw input was reused without a recorder"); + words[5] = 0xdead; + const auto stored = CopyDrawInput(context, &recorder, address, size, 4, Use::Index32); + Require(!stored.reused && stored.buffer != first.buffer && equalsGuest(stored), "a draw input outlived a CPU store"); + KeepDrawInput(&recorder, address, stored, Use::Index32, 0xdead); + Require(CopyDrawInput(context, &recorder, address, size, 4, Use::Index32).derived == 0xdead, "the new copy was not kept"); + MarkWritten(address + 128, 4); + const auto marked = CopyDrawInput(context, &recorder, address, size, 4, Use::Index32); + Require(!marked.reused && equalsGuest(marked), "a draw input outlived a stamped GPU store"); + KeepDrawInput(&recorder, address, marked, Use::Index32, 1); + Require(CopyDrawInput(context, &recorder, address, size, 4, Use::Index32).reused, "the copy after the GPU store was not kept"); + alignas(64) static std::byte other[64]; + { + GuestAllocations::Mutation mutation; + mutation.Add(other, sizeof(other), true, true); + } + { + GuestAllocations::Mutation mutation; + mutation.Remove(other); + } + Require(!CopyDrawInput(context, &recorder, address, size, 4, Use::Index32).reused, "a draw input outlived a registry mutation"); + const auto pool = address + 8192; + const auto whole = CopyDrawInput(context, &recorder, pool, 12288, 1, Use::Vertex); + Require(!whole.reused && std::memcmp(whole.buffer->Bytes().data(), reinterpret_cast(pool), 12288) == 0, "the vertex pool copy is wrong"); + KeepDrawInput(&recorder, pool, whole, Use::Vertex, 0); + const auto prefix = CopyDrawInput(context, &recorder, pool, 4096, 1, Use::Vertex); + Require(prefix.reused && prefix.buffer == whole.buffer, "a shorter vertex read did not reuse the longer snapshot"); + Require(!CopyDrawInput(context, &recorder, pool, 16384, 1, Use::Vertex).reused, "a longer vertex read reused a shorter snapshot"); + Require(!CopyDrawInput(context, &recorder, pool + 4, 4096, 1, Use::Vertex).reused, "a vertex read at another address reused the snapshot"); + Require(!CopyDrawInput(context, &recorder, pool, 4096, 4, Use::Index32).reused, "an index read reused a longer vertex snapshot"); + const auto shorter = CopyDrawInput(context, &recorder, pool, 8192, 4, Use::Index32); + KeepDrawInput(&recorder, pool, shorter, Use::Index32, 3); + Require(!CopyDrawInput(context, &recorder, pool, 4096, 4, Use::Index32).reused, "an index read reused a longer index snapshot"); + words[(8192 + 8192 + 16) / 4] = 0xbeef; + const auto prefixAfter = CopyDrawInput(context, &recorder, pool, 4096, 1, Use::Vertex); + Require(std::memcmp(prefixAfter.buffer->Bytes().data(), reinterpret_cast(pool), 4096) == 0, "a shorter vertex read after a store got other bytes"); + const auto after = CopyDrawInput(context, &recorder, pool, 12288, 1, Use::Vertex); + Require(!after.reused && std::memcmp(after.buffer->Bytes().data(), reinterpret_cast(pool), 12288) == 0, "a vertex read over the store reused the old bytes"); + KeepDrawInput(&recorder, pool, after, Use::Vertex, 0); + const auto small = CopyDrawInput(context, &recorder, pool, 4096, 1, Use::Vertex); + Require(small.reused && small.buffer == after.buffer, "the new vertex snapshot does not serve shorter reads"); + recorder.Sync(); +} + // Unit shadows (UnitShadow.hpp) over a host import of write-watched arena memory: a retile piece's // slab destination and its seeds, freshness from the tracker (a publish never stamps, a CPU write // makes the unit stale), the scopes, the slab boundary, and the retire publish. With @@ -2098,6 +2176,7 @@ int main() { misalignedSnapshotTests(device, recorder); drawSnapshotReuseTests(device, recorder); drawSnapshotEvictionTests(device); + drawInputReuseTests(device, recorder); storeRunTests(device, recorder); movedMetadataTests(device, recorder); unitShadowTests(device, recorder);