diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp index c8830d353d95..1e5ab5aa2080 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp @@ -710,6 +710,7 @@ struct VulkanDevice::State { copiedWriters->clear(); resourceCache.Clear(); Graphics::ClearCachedTextures(device); + Graphics::ClearSnapshotCopies(device); Graphics::ClearImageMirrors(device); Graphics::ClearHostImports(device); patternBuffers.clear(); diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/GuestBufferMemory.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/GuestBufferMemory.hpp index e9b639cbeb9d..2f70fd0e1a5e 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/GuestBufferMemory.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/GuestBufferMemory.hpp @@ -167,6 +167,8 @@ struct MirrorStats { std::uint64_t sparseBinds = 0; }; MirrorStats MirrorCounters(); +void ClearSnapshotCopies(VkDevice device); +std::vector AddressTableKey(std::span> writes, std::span own); void ClearImageMirrors(VkDevice device); void ClearHostImports(VkDevice device); @@ -392,8 +394,8 @@ class GuestBufferMemory { // The cached address space this build maps through (its lease pins the ranges); `regions` then // holds only the regions outside it (V#s, snapshots, ranges copied per build). std::shared_ptr space; - mutable std::uint64_t writeTableSerial = 0; - mutable std::shared_ptr> writeTableRanges; + mutable std::uint64_t tableSerial = 0; + mutable std::shared_ptr> tableRanges; // Import registry epoch when `direct` pointers were taken at acquire time; they are reused while // no import was destroyed since. std::uint64_t importsEpoch = 0; diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/GuestBufferMemory.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/GuestBufferMemory.cpp index 578128f2fe84..0677e53c03ae 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/GuestBufferMemory.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/GuestBufferMemory.cpp @@ -29,6 +29,7 @@ #include #include #include +#include #include #include #include @@ -112,7 +113,13 @@ struct GuestBufferMemory::AddressSpace { std::vector ranges; std::shared_ptr>> directReads; mutable std::mutex tableMutex; - mutable std::map>, std::pair>>> writeTables; + struct Table { + std::uint64_t serial; + std::shared_ptr> ranges; + std::list*>::iterator recent; + }; + mutable std::map, Table> tables; + mutable std::list*> tableRecency; }; namespace { @@ -1236,6 +1243,64 @@ ImageMirrors& Mirrors() { return mirrors; } +struct SnapshotCopies { + using Key = std::tuple; + static constexpr std::size_t Budget = std::size_t{16} << 20u; + static constexpr std::size_t MaxEntries = 1024; + std::mutex mutex; + VkDevice device = VK_NULL_HANDLE; + struct Entry { + std::shared_ptr buffer; + std::vector bytes; + std::list::iterator recent; + }; + std::map entries; + std::list recency; + std::size_t bytes = 0; + void clear() { + entries.clear(); + recency.clear(); + bytes = 0; + } +}; + +SnapshotCopies& SnapshotCopyCache() { + static SnapshotCopies copies; + return copies; +} + +std::shared_ptr snapshotCopy(const Context& context, std::uint64_t address, std::span bytes, VkBufferUsageFlags usage) { + auto& copies = SnapshotCopyCache(); + std::lock_guard lock(copies.mutex); + if (copies.device != context.device) { + copies.clear(); + copies.device = context.device; + } + const SnapshotCopies::Key key{address, bytes.size(), usage}; + if (const auto found = copies.entries.find(key); found != copies.entries.end()) { + if (std::memcmp(found->second.bytes.data(), bytes.data(), bytes.size()) == 0) { + copies.recency.splice(copies.recency.end(), copies.recency, found->second.recent); + return found->second.buffer; + } + copies.recency.erase(found->second.recent); + copies.bytes -= bytes.size(); + copies.entries.erase(found); + } + auto buffer = std::make_shared(context, bytes.size(), usage); + std::memcpy(buffer->Bytes().data(), bytes.data(), bytes.size()); + if (bytes.size() > SnapshotCopies::Budget) return buffer; + while (!copies.recency.empty() && (copies.bytes + bytes.size() > SnapshotCopies::Budget || copies.entries.size() >= SnapshotCopies::MaxEntries)) { + const auto oldest = copies.entries.find(copies.recency.front()); + copies.bytes -= std::get<1>(oldest->first); + copies.entries.erase(oldest); + copies.recency.pop_front(); + } + copies.recency.push_back(key); + copies.entries.emplace(key, SnapshotCopies::Entry{buffer, {bytes.begin(), bytes.end()}, std::prev(copies.recency.end())}); + copies.bytes += bytes.size(); + return buffer; +} + bool mirrorsEnabled() { static const bool disabled = std::getenv("APS5_NO_LEASE_MIRROR") != nullptr; return !disabled; @@ -2072,6 +2137,23 @@ MirrorStats MirrorCounters() { return stats; } +std::vector AddressTableKey(std::span> writes, std::span own) { + std::vector key; + key.reserve(writes.size() * 2u + 1u + own.size() * 4u); + for (const auto& [begin, end] : writes) key.insert(key.end(), {begin, end}); + key.push_back(std::numeric_limits::max()); + for (const auto& range : own) key.insert(key.end(), {range.begin, range.end, range.deviceAddress, (static_cast(range.reserved) << 32u) | range.permissions}); + return key; +} + +void ClearSnapshotCopies(VkDevice device) { + auto& copies = SnapshotCopyCache(); + std::lock_guard lock(copies.mutex); + if (copies.device != device) return; + copies.clear(); + copies.device = VK_NULL_HANDLE; +} + void ClearImageMirrors(VkDevice device) { auto space = Spaces().current.load(); if (space != nullptr && space->device == device) { @@ -3514,7 +3596,9 @@ void GuestBufferMemory::copyRegion(Region& region, bool addressable) { } const auto allocated = region.bufferEnd != 0 ? region.bufferEnd - region.begin : bytes; // A buffer made by UploadPrepare for a GPU copy that fell back here (its import went) is kept. - if (region.buffer == nullptr) region.buffer = std::make_shared(context, static_cast(allocated), usage); + const bool shared = region.buffer == nullptr && !region.hostBacked && !region.writable && !region.sparse && region.bufferEnd == 0 && region.snapshot.size() == bytes; + if (shared) region.buffer = snapshotCopy(context, region.begin, region.snapshot, usage); + else if (region.buffer == nullptr) region.buffer = std::make_shared(context, static_cast(allocated), usage); const auto readStart = std::chrono::steady_clock::now(); if (profile) allocateUs.fetch_add(microsecondsSince(allocateStart), std::memory_order_relaxed); // Named for the [hooksync] attribution: the reads below go through the flush hook. @@ -3544,7 +3628,7 @@ void GuestBufferMemory::copyRegion(Region& region, bool addressable) { } } else { - std::memcpy(region.buffer->Bytes().data(), region.snapshot.data(), region.snapshot.size()); + if (!shared) std::memcpy(region.buffer->Bytes().data(), region.snapshot.data(), region.snapshot.size()); readBytes += region.snapshot.size(); } region.snapshot.clear(); @@ -3840,12 +3924,12 @@ std::vector GuestBufferMemory::AddressRanges() } std::optional GuestBufferMemory::CachedAddressTable() const { - if (space == nullptr || !regions.empty()) return std::nullopt; + if (space == nullptr) return std::nullopt; Require(uploaded && !committed, "guest GPU address ranges are not available"); - if (writes.empty()) return CachedTable{space->serial, &space->ranges}; - if (writeTableRanges != nullptr) return CachedTable{writeTableSerial, writeTableRanges.get()}; + if (writes.empty() && regions.empty()) return CachedTable{space->serial, &space->ranges}; + if (tableRanges != nullptr) return CachedTable{tableSerial, tableRanges.get()}; const auto& spaceRanges = space->ranges; - const bool inWritable = std::all_of(writes.begin(), writes.end(), [&](const auto& written) { + const bool inWritable = regions.empty() && std::all_of(writes.begin(), writes.end(), [&](const auto& written) { auto at = std::partition_point(spaceRanges.begin(), spaceRanges.end(), [&](const auto& range) { return range.end <= written.first; }); for (; at != spaceRanges.end() && at->begin < written.second; ++at) { if ((at->permissions & ShaderRecompiler::BdaAbi::Write) == 0u) return false; @@ -3853,18 +3937,32 @@ std::optional GuestBufferMemory::CachedAddressTa return true; }); if (inWritable) return CachedTable{space->serial, &space->ranges}; + std::vector own; + own.reserve(regions.size()); + for (const auto& region : regions) own.push_back(addressRange(region)); + auto key = AddressTableKey(writes, own); + static const bool verify = std::getenv("APS5_VERIFY_BDA_TABLES") != nullptr; std::lock_guard lock(space->tableMutex); - const auto found = space->writeTables.find(writes); - if (found != space->writeTables.end()) { - writeTableSerial = found->second.first; - writeTableRanges = found->second.second; + const auto found = space->tables.find(key); + if (found != space->tables.end()) { + space->tableRecency.splice(space->tableRecency.end(), space->tableRecency, found->second.recent); + tableSerial = found->second.serial; + tableRanges = found->second.ranges; + if (verify) { + const auto built = AddressRanges(); + Require(built.size() == tableRanges->size() && (built.empty() || std::memcmp(built.data(), tableRanges->data(), built.size() * sizeof(built.front())) == 0), "a cached BDA table differs from the ranges of the build that found it"); + } } else { - writeTableRanges = std::make_shared>(AddressRanges()); - writeTableSerial = Spaces().serials.fetch_add(1, std::memory_order_relaxed) + 1; - if (space->writeTables.size() >= 64u) space->writeTables.erase(space->writeTables.begin()); - space->writeTables.emplace(writes, std::pair{writeTableSerial, writeTableRanges}); + tableRanges = std::make_shared>(AddressRanges()); + tableSerial = Spaces().serials.fetch_add(1, std::memory_order_relaxed) + 1; + if (space->tables.size() >= 64u) { + space->tables.erase(*space->tableRecency.front()); + space->tableRecency.pop_front(); + } + const auto inserted = space->tables.emplace(std::move(key), AddressSpace::Table{tableSerial, tableRanges, {}}).first; + inserted->second.recent = space->tableRecency.insert(space->tableRecency.end(), &inserted->first); } - return CachedTable{writeTableSerial, writeTableRanges.get()}; + return CachedTable{tableSerial, tableRanges.get()}; } bool GuestBufferMemory::HasCopiedWrites() const { diff --git a/core/libs/prx/libSceAgcDriver/tests/BdaResources.cpp b/core/libs/prx/libSceAgcDriver/tests/BdaResources.cpp index ab8b8f312596..2fe20f100c6f 100644 --- a/core/libs/prx/libSceAgcDriver/tests/BdaResources.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/BdaResources.cpp @@ -1,4 +1,5 @@ #include "BdaTests.hpp" +#include "prx/libSceAgcDriver/Graphics/include/BdaResources.hpp" #include "prx/libSceAgcDriver/Graphics/include/Recorder.hpp" #include "prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp" #include "prx/libc/include/GuestAllocations.hpp" @@ -23,6 +24,7 @@ #include #include #include +#include #ifndef _WIN32 #include @@ -42,6 +44,118 @@ void reject(TAction action, const char* reason) { throw std::runtime_error(std::string("expected BDA rejection: ") + reason); } +void addressTableKeyTests() { + using ShaderRecompiler::BdaAbi::Range; + const std::array, 1> written{{{0x1000, 0x1040}}}; + const std::array, 1> otherWritten{{{0x1000, 0x1080}}}; + const std::array own{{{0x2000, 0x2100, 0x70000000, ShaderRecompiler::BdaAbi::Read, 0}}}; + const std::array moved{{{0x2000, 0x2100, 0x70010000, ShaderRecompiler::BdaAbi::Read, 0}}}; + const std::array, 2> ownAsWrites{{{0x2000, 0x2100}, {0x70000000, ShaderRecompiler::BdaAbi::Read}}}; + const auto plain = AddressTableKey({}, own); + Require(AddressTableKey({}, own) == plain, "one build's BDA table key is not stable"); + Require(AddressTableKey(written, own) != plain && AddressTableKey(written, own) != AddressTableKey(otherWritten, own), "BDA table keys of builds that differ only in their written ranges are equal"); + Require(AddressTableKey({}, moved) != plain, "BDA table keys of builds whose own region moved are equal"); + Require(AddressTableKey(ownAsWrites, {}) != plain, "written ranges and own regions with the same words give one BDA table key"); +} + +void snapshotTableTests(const Context& context, const BdaTestAccess& access) { + constexpr std::size_t piece = 65536; + void* block = ::operator new(piece, std::align_val_t{piece}); + std::memset(block, 0x3c, piece); + auto importing = context; + importing.hostImportAlignment = piece; + const auto change = [&](bool add) { + auto* mutation = GuestAllocations::GuestAllocationsBegin_nid_postfix(); + if (add) GuestAllocations::GuestAllocationsAdd_nid_postfix(mutation, block, piece, true, true, true); + else GuestAllocations::GuestAllocationsRemove_nid_postfix(mutation, block); + GuestAllocations::GuestAllocationsEnd_nid_postfix(mutation); + }; + change(true); + alignas(256) static std::array source{}; + const auto snapshotAddress = reinterpret_cast(source.data()); + std::array first{}; + std::array second{}; + first.fill(std::byte{0x11}); + second.fill(std::byte{0x22}); + struct Build { + std::unique_ptr memory; + std::unique_ptr bda; + std::uint64_t snapshot = 0; + VkBuffer table = VK_NULL_HANDLE; + VkBuffer view = VK_NULL_HANDLE; + }; + const auto build = [&](std::span bytes, bool written, bool addressable, std::uint64_t address) { + Build result; + result.memory = std::make_unique(importing); + auto& memory = *result.memory; + if (addressable) memory.AcquireRegistered(); + if (written) memory.AddWritable(reinterpret_cast(block) + 256, 64); + memory.AddSnapshot({address, bytes}); + memory.Upload(addressable); + std::uint32_t adjustment = 0; + result.view = memory.Descriptor(address, bytes.size(), adjustment).buffer; + if (!addressable) return result; + const auto ranges = memory.AddressRanges(); + const auto found = std::find_if(ranges.begin(), ranges.end(), [&](const auto& range) { return range.begin == address; }); + Require(found != ranges.end() && found->end == address + bytes.size(), "the snapshot has no BDA table entry of its own"); + result.snapshot = found->deviceAddress; + const auto held = access.addressBytes(result.snapshot); + Require(held.size() >= bytes.size() && std::memcmp(held.data(), bytes.data(), bytes.size()) == 0, "the snapshot's device copy does not hold its bytes"); + if (const auto cached = memory.CachedAddressTable()) { + Require(cached->ranges->size() == ranges.size() && std::memcmp(cached->ranges->data(), ranges.data(), ranges.size() * sizeof(ranges.front())) == 0, "a cached BDA table differs from the build's ranges"); + } + result.bda = std::make_unique(importing, memory); + result.table = result.bda->Table().buffer; + return result; + }; + const bool spaces = AddressSpaceCounters().enabled; + { + auto a = build(first, false, true, snapshotAddress); + auto plain = build(first, false, false, snapshotAddress); + auto d = build(first, true, true, snapshotAddress); + auto b = build(first, false, true, snapshotAddress); + auto c = build(second, false, true, snapshotAddress); + Require(a.snapshot == b.snapshot && a.view == b.view, "two builds of one snapshot with the same bytes do not share its device copy"); + Require(c.snapshot != a.snapshot, "a snapshot with other bytes took the device copy of the first"); + Require(plain.view != a.view && d.snapshot == a.snapshot, "a snapshot copy made for BDA serves a build bound by descriptor, or a build with written ranges did not share the snapshot copy"); + if (spaces) { + Require(a.memory->CachedAddressTable().has_value() && c.memory->CachedAddressTable().has_value() && d.memory->CachedAddressTable().has_value(), "a build with its own regions over the address space has no cached BDA table"); + Require(a.table == b.table, "two builds of the same space and snapshot do not share their BDA table"); + Require(c.table != a.table, "a build with other snapshot bytes took another build's BDA table"); + Require(a.memory->CachedAddressTable()->serial == b.memory->CachedAddressTable()->serial && c.memory->CachedAddressTable()->serial != a.memory->CachedAddressTable()->serial, "cached BDA table serials do not follow the build's ranges"); + } + ClearSnapshotCopies(importing.device); + auto e = build(first, false, true, snapshotAddress); + Require(e.snapshot != a.snapshot, "a snapshot copy outlived the teardown of its device's copies"); + for (auto* item : {&a, &b, &c, &d, &e, &plain}) item->memory->WriteBack(); + } + if (spaces) { + std::vector> variants(66); + for (std::size_t index = 0; index < variants.size(); ++index) { + variants[index].fill(std::byte{0x40}); + variants[index][0] = static_cast(index); + variants[index][1] = static_cast(index >> 8u); + } + alignas(256) static std::array sources{}; + std::vector builds; + const auto serial = [&](std::size_t index) { + builds.push_back(build(variants[index], false, true, reinterpret_cast(sources.data()) + index * 512)); + return builds.back().memory->CachedAddressTable()->serial; + }; + const auto kept = serial(0); + const auto evicted = serial(1); + for (std::size_t index = 2; index < 64; ++index) serial(index); + Require(serial(0) == kept, "a BDA table was dropped before 64 newer tables of its space"); + serial(64); + Require(serial(0) == kept, "the most recently used BDA table of a space was evicted"); + Require(serial(1) != evicted, "the least recently used BDA table of a space was kept past 64 tables"); + for (auto& item : builds) item.memory->WriteBack(); + } + ClearSnapshotCopies(importing.device); + change(false); + ::operator delete(block, std::align_val_t{piece}); +} + void importCrossingTests(const Context& context, const BdaTestAccess& access) { constexpr std::size_t half = 65536; void* block = ::operator new(2 * half, std::align_val_t{half}); @@ -1661,6 +1775,8 @@ void RunBdaResourceTests(const Context& context, const BdaTestAccess& access) { if (dropped.enabled) Require(dropped.waiterDrops == after.waiterDrops + 1 && LeaseCounters().cacheDrops == dropped.waiterDrops, "the free did not drop the cached address space"); } importCrossingTests(context, access); + addressTableKeyTests(); + snapshotTableTests(context, access); importSpanTests(context); failedImportRemapTests(context, access); spaceImportRunTests(context); @@ -1686,4 +1802,5 @@ void RunBdaResourceTests(const Context& context, const BdaTestAccess& access) { Require(AddressCopyOverflow({{0x1000, 0x3000, 0x2000, "uncommitted pages"}}, 0x2000).empty(), "copies within the limit were refused"); const auto copies = AddressCopyOverflow({{0x1000, 0x2000, 0x1000, "not mirrored"}, {0x10000, 0x30000, 0x18000, "uncommitted pages"}}, 0x2000); Require(!copies.empty() && copies.find("0x10000+0x20000 (0.1 MiB committed, uncommitted pages)") < copies.find("0x1000+0x1000"), "the copy limit does not name the largest copy first"); + ClearSnapshotCopies(context.device); }