diff --git a/core/libs/prx/libSceAgcDriver/CMakeLists.txt b/core/libs/prx/libSceAgcDriver/CMakeLists.txt index 40c7b7629653..f4069127f783 100644 --- a/core/libs/prx/libSceAgcDriver/CMakeLists.txt +++ b/core/libs/prx/libSceAgcDriver/CMakeLists.txt @@ -139,6 +139,7 @@ set(agcDriverSources ${CMAKE_CURRENT_SOURCE_DIR}/Graphics/src/Resources.cpp ${CMAKE_CURRENT_SOURCE_DIR}/Graphics/src/Recorder.cpp ${CMAKE_CURRENT_SOURCE_DIR}/Graphics/src/ShaderInputState.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/Graphics/src/BufferCache.cpp ${CMAKE_CURRENT_SOURCE_DIR}/Graphics/src/ShaderResources.cpp ${CMAKE_CURRENT_SOURCE_DIR}/Graphics/src/ShaderAddressResources.cpp ${CMAKE_CURRENT_SOURCE_DIR}/Graphics/src/GuestBufferMemory.cpp @@ -384,6 +385,7 @@ target_include_directories(agc_driver_recorder_tests PRIVATE ) target_link_libraries(agc_driver_recorder_tests PRIVATE + libkernel libSceAgcDriver SDL2-static libc @@ -441,6 +443,7 @@ add_test_executable(agc_driver_graphics_tests EXCLUDE_FROM_ALL Graphics/src/ColorTargetLayout.cpp Graphics/src/ColorTargetTransfer.cpp Graphics/src/Resources.cpp + Graphics/src/BufferCache.cpp Graphics/src/ShaderResources.cpp Graphics/src/ShaderAddressResources.cpp Graphics/src/GuestBufferMemory.cpp @@ -597,6 +600,7 @@ if(AGC_BUILD_VISUAL_TEST) Graphics/src/Pipeline.cpp Graphics/src/PipelineCache.cpp Graphics/src/Resources.cpp + Graphics/src/BufferCache.cpp Graphics/src/ShaderResources.cpp Graphics/src/ShaderAddressResources.cpp Graphics/src/GuestBufferMemory.cpp diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/BufferCache.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/BufferCache.hpp new file mode 100644 index 000000000000..79b0b4aec802 --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/BufferCache.hpp @@ -0,0 +1,67 @@ +#ifndef CORE_LIBS_PRX_LIBSCEAGCDRIVER_GRAPHICS_INCLUDE_BUFFERCACHE_HPP +#define CORE_LIBS_PRX_LIBSCEAGCDRIVER_GRAPHICS_INCLUDE_BUFFERCACHE_HPP + +#include +#include +#include +#include +#include +#include +#include + +namespace AgcDriver::Graphics { + +class Buffer; + +class BufferCache { +public: + enum class Use : std::uint8_t { Storage, Vertex, Index16, Index32 }; + static constexpr std::size_t StorageBudget = std::size_t{256} << 20u; + static constexpr std::size_t StorageEntries = 1024; + static constexpr std::size_t GeometryBudget = std::size_t{1024} << 20u; + static constexpr std::size_t GeometryEntries = 16384; + struct Slice { + std::shared_ptr buffer; + std::size_t offset = 0; + std::size_t bytes = 0; + std::uint32_t derived = 0; + explicit operator bool() const { return buffer != nullptr; } + }; + struct Statistics { + std::uint64_t lookups = 0; + std::uint64_t hits = 0; + std::uint64_t invalidations = 0; + std::uint64_t mappingInvalidations = 0; + std::uint64_t evictions = 0; + std::uint64_t uploadedBytes = 0; + std::uint64_t uploads = 0; + }; + BufferCache() = default; + BufferCache(const BufferCache&) = delete; + BufferCache& operator=(const BufferCache&) = delete; + Slice Find(std::uint64_t address, std::size_t bytes, Use use); + void Keep(std::uint64_t address, std::uint64_t generation, std::uint64_t mappingGeneration, Slice slice, Use use); + void NoteUpload(std::size_t bytes) { ++stats.uploads; stats.uploadedBytes += bytes; } + const Statistics& Counters() const { return stats; } + +private: + using Key = std::tuple; + struct Entry { + std::uint64_t generation; + std::uint64_t mappingGeneration; + std::list::iterator recent; + Slice slice; + }; + struct Pool { + std::list recency; + std::size_t bytes = 0; + }; + std::map entries; + std::array pools; + Statistics stats; + void erase(std::map::iterator entry); +}; + +} + +#endif diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/GuestBufferMemory.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/GuestBufferMemory.hpp index 14988113ade4..0962a570e1cf 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/GuestBufferMemory.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/GuestBufferMemory.hpp @@ -295,6 +295,7 @@ class GuestBufferMemory { // The device refused the shadow (memory or allocations exhausted): the region takes the // path it would take without staging, in both upload stages. bool unstaged = false; + std::size_t bufferOffset = 0; }; // How [begin, end) lies against the space's base regions. diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/Recorder.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/Recorder.hpp index cea65de457a6..c58f6d882b4a 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/Recorder.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/Recorder.hpp @@ -1,6 +1,7 @@ #ifndef CORE_LIBS_PRX_LIBSCEAGCDRIVER_GRAPHICS_INCLUDE_RECORDER_HPP #define CORE_LIBS_PRX_LIBSCEAGCDRIVER_GRAPHICS_INCLUDE_RECORDER_HPP +#include "prx/libSceAgcDriver/Graphics/include/BufferCache.hpp" #include "prx/libSceAgcDriver/Graphics/include/Context.hpp" #include #include @@ -90,13 +91,16 @@ class Recorder { static constexpr std::size_t KeptBytesBudget = std::size_t{512} << 20u; void BoundKeptBytes(); std::size_t InFlightKeptBytes() const { return inFlightKeptBytes; } - 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; - 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); + std::pair, std::size_t> AllocateDrawUpload(std::size_t bytes); + using SnapshotUse = BufferCache::Use; + static constexpr auto DrawSnapshotBudget = BufferCache::StorageBudget; + static constexpr auto DrawSnapshotEntries = BufferCache::StorageEntries; + static constexpr auto DrawInputBudget = BufferCache::GeometryBudget; + static constexpr auto DrawInputEntries = BufferCache::GeometryEntries; + BufferCache::Slice ReadBuffer(std::uint64_t address, std::size_t bytes); + const BufferCache::Statistics& BufferCounters() const { return bufferCache.Counters(); } + std::shared_ptr ReusableDrawSnapshot(std::uint64_t address, std::size_t bytes, SnapshotUse use = SnapshotUse::Storage, std::uint32_t* derived = nullptr, std::size_t* offset = 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, std::size_t offset = 0); void OnComplete(std::function action); void NotePendingWrite(std::uint64_t address, std::size_t bytes); void NotePendingFill(std::uint64_t address, std::size_t bytes, std::uint8_t value); @@ -496,6 +500,8 @@ class Recorder { VkFence fence = VK_NULL_HANDLE; std::vector> kept; std::size_t keptBytes = 0; + std::shared_ptr drawUpload; + std::size_t drawUploadUsed = 0; std::vector> completions; std::vector> writes; std::vector writeNotes; @@ -748,21 +754,7 @@ class Recorder { std::array completed; std::uint64_t newestSubmitted = 0; std::chrono::steady_clock::time_point newestSubmittedAt{}; - 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::array drawSnapshotPools; - void eraseDrawSnapshot(std::map::iterator entry); + BufferCache bufferCache; }; } diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp index 29e48af8369f..8506bc3e7fff 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp @@ -110,6 +110,9 @@ class ShaderResources { struct Snapshot { std::uint64_t address; std::shared_ptr buffer; + std::size_t offset = 0; + std::size_t size = 0; + std::span Bytes() const { return buffer->Bytes().subspan(offset, size); } }; DescriptorCache* cache = nullptr; DescriptorCache::SetAllocation allocation; @@ -243,7 +246,7 @@ class ShaderResources { std::uint64_t address; std::size_t size; bool guest; - std::unique_ptr buffer; + std::shared_ptr buffer; ShaderRecompiler::DescriptorRole role = ShaderRecompiler::DescriptorRole::ShaderData; // Guest buffers: whether the shader may store to the range (see addGuestBuffer). bool written = true; @@ -253,6 +256,9 @@ class ShaderResources { std::int32_t pushByte = -1; std::int64_t dataAllocation = -1; std::uint32_t dataByte = 0; + std::size_t bufferOffset = 0; + std::span pendingData; + std::span Bytes() const { return buffer->Bytes().subspan(bufferOffset, size); } }; struct DataPatch { std::size_t allocation; @@ -401,6 +407,10 @@ class ShaderResources { // The cache pool the set was allocated from, freed back to it on release. VkDescriptorPool cachePool = VK_NULL_HANDLE; std::vector allocations; + std::vector descriptorSizes; + std::vector descriptorBuffers; + std::vector descriptorImages; + std::vector descriptorWrites; // Guest buffer elements bound read-only: each use of this object skips that many pending-write // notes (counted in MarkGpuWrites for the [buffers] line). std::size_t readOnlyBuffers = 0; diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/BufferCache.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/BufferCache.cpp new file mode 100644 index 000000000000..8cebf8654345 --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/BufferCache.cpp @@ -0,0 +1,65 @@ +#include "prx/libSceAgcDriver/Graphics/include/BufferCache.hpp" +#include "prx/libSceAgcDriver/Execution/include/GuestMemory.hpp" +#include "prx/libc/include/GuestAllocations.hpp" +#include + +namespace AgcDriver::Graphics { + +namespace { +std::size_t poolIndex(BufferCache::Use use) { + return use == BufferCache::Use::Storage ? 0 : 1; +} +} + +void BufferCache::erase(std::map::iterator entry) { + auto& pool = pools[poolIndex(std::get<1>(entry->first))]; + pool.bytes -= std::get<2>(entry->first); + pool.recency.erase(entry->second.recent); + entries.erase(entry); +} + +BufferCache::Slice BufferCache::Find(std::uint64_t address, std::size_t bytes, Use use) { + ++stats.lookups; + const auto found = use == Use::Vertex ? entries.lower_bound({address, use, bytes}) : entries.find({address, use, bytes}); + if (found == entries.end() || std::get<0>(found->first) != address || std::get<1>(found->first) != use) return {}; + const auto mappingGeneration = GuestAllocations::GuestAllocationsValidateMapping_nid_no_patch(address, std::get<2>(found->first), found->second.mappingGeneration); + const bool mappingChanged = mappingGeneration == 0; + if (mappingChanged || !GuestMemory::UnchangedSince(address, bytes, found->second.generation)) { + ++stats.invalidations; + stats.mappingInvalidations += mappingChanged; + erase(found); + return {}; + } + found->second.mappingGeneration = mappingGeneration; + auto& recency = pools[poolIndex(use)].recency; + recency.splice(recency.end(), recency, found->second.recent); + ++stats.hits; + return found->second.slice; +} + +void BufferCache::Keep(std::uint64_t address, std::uint64_t generation, std::uint64_t mappingGeneration, Slice slice, Use use) { + const bool storage = use == Use::Storage; + const auto budget = storage ? StorageBudget : GeometryBudget; + const auto maxEntries = storage ? StorageEntries : GeometryEntries; + auto& pool = pools[poolIndex(use)]; + const auto bytes = slice.bytes; + if (generation == 0 || bytes == 0 || bytes > budget) return; + if (use == Use::Vertex) { + for (auto it = entries.lower_bound({address, use, 0}); it != entries.end() && std::get<0>(it->first) == address && std::get<1>(it->first) == use && std::get<2>(it->first) <= bytes;) erase(it++); + } else if (const auto found = entries.find({address, use, bytes}); found != entries.end()) erase(found); + while (!pool.recency.empty() && (pool.bytes + bytes > budget || pool.recency.size() >= maxEntries)) { + ++stats.evictions; + erase(entries.find(pool.recency.front())); + } + const Key key{address, use, bytes}; + pool.recency.push_back(key); + try { + entries.emplace(key, Entry{generation, mappingGeneration, std::prev(pool.recency.end()), std::move(slice)}); + } catch (...) { + pool.recency.pop_back(); + throw; + } + pool.bytes += bytes; +} + +} diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp index 29a48ebe9d2e..b5a92855075c 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp @@ -1269,15 +1269,15 @@ void captureInputs(const Context& context, Recorder& recorder, VkCommandBuffer c }; if (bindings != nullptr) { for (const auto& snapshot : bindings->snapshots) { - const auto bytes = snapshot.buffer->Bytes(); - addSample(snapshot.address, bytes.size(), snapshot.buffer->Handle(), 0, bytes.data()); + const auto bytes = snapshot.Bytes(); + addSample(snapshot.address, bytes.size(), snapshot.buffer->Handle(), snapshot.offset, bytes.data()); } } for (const auto& [begin, end] : resources.InPlaceReads()) { Require(end >= begin, "invalid capture input range"); const auto bytes = static_cast(end - begin); if (bytes == 0 || bytes > 512) continue; - if (bindings != nullptr && std::any_of(bindings->snapshots.begin(), bindings->snapshots.end(), [&](const auto& snapshot) { return snapshot.address < end && begin < snapshot.address + snapshot.buffer->Bytes().size(); })) continue; + if (bindings != nullptr && std::any_of(bindings->snapshots.begin(), bindings->snapshots.end(), [&](const auto& snapshot) { return snapshot.address < end && begin < snapshot.address + snapshot.size; })) continue; if (resources.WritesOverlap(begin, bytes) || recorder.PendingWriteOverlaps(begin, bytes)) { CaptureTrace::Log("input-skip draw=%llu batch=%llu address=%llx bytes=%zu reason=gpu-writer", draw, batch, static_cast(begin), bytes); continue; diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/GuestBufferMemory.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/GuestBufferMemory.cpp index 6f9fbad41e72..44b64f2c47fb 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/GuestBufferMemory.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/GuestBufferMemory.cpp @@ -1289,6 +1289,12 @@ const HostImport* HostImportFor(const Context& context, std::uint64_t address, s // A hit is only valid while the registry has not changed since the imports were reconciled. if (!importsStale(context, state)) { if (const auto* entry = findImport(state, address, address + bytes)) return entry; + const auto lease = GuestAllocations::GuestAllocationsAcquireRange_nid_no_patch(address, bytes); + if (!importsStale(context, state)) { + if (lease.empty()) return nullptr; + const auto& range = *lease.front(); + return importAllocation(context, state, range.address, range.bytes, lease); + } } const auto lease = GuestAllocations::GuestAllocationsAcquire_nid_postfix(); refreshImports(context, state, lease); @@ -1297,9 +1303,7 @@ const HostImport* HostImportFor(const Context& context, std::uint64_t address, s } bool RegisteredReadableCovers(std::uint64_t address, std::size_t bytes) { - if (bytes == 0 || bytes > std::numeric_limits::max() - address) return false; - const auto lease = GuestAllocations::GuestAllocationsAcquire_nid_postfix(); - return containingRange(lease, address, address + bytes) != nullptr; + return !GuestAllocations::GuestAllocationsAcquireRange_nid_no_patch(address, bytes).empty(); } bool HostImportCovers(const Context& context, std::uint64_t address, std::size_t bytes) { @@ -2049,6 +2053,10 @@ void GuestBufferMemory::UploadPrepare(bool addressable) { region.pending = true; continue; } + if (!addressable && !region.sparse && Recorder::Active() != nullptr) { + region.pending = true; + continue; + } copyRegion(region, addressable); } } @@ -2138,7 +2146,14 @@ void GuestBufferMemory::UploadFinish(bool addressable) { region.direct = nullptr; if (entry == nullptr) entry = findImport(state, region.begin, region.end); if (entry == nullptr) { - if (const auto* range = containingRange(importRanges(), region.begin, region.end)) entry = importAllocation(context, state, range->address, range->bytes, importRanges()); + GuestAllocations::Lease targeted; + const bool haveLease = !lease.empty() || space != nullptr || !acquired.empty(); + if (!haveLease) targeted = GuestAllocations::GuestAllocationsAcquireRange_nid_no_patch(region.begin, bytes); + const bool stale = importsStale(context, state); + const auto& available = haveLease || stale ? importRanges() : targeted; + if (stale) refreshImports(context, state, available); + if (const auto* range = containingRange(available, region.begin, region.end)) + entry = importAllocation(context, state, range->address, range->bytes, available); } // A staged region (see stagingEligible) is copied out of the import even when aligned; // without a recorder to record the copies it binds in place like any other. @@ -2227,6 +2242,16 @@ void GuestBufferMemory::UploadFinish(bool addressable) { void GuestBufferMemory::copyRegion(Region& region, bool addressable) { static const bool profile = std::getenv("APS5_PROFILE_DRAW") != nullptr; const auto bytes = region.end - region.begin; + if (!addressable && !region.sparse && bytes <= context.limits.maxStorageBufferRange && (region.hostBacked || region.writable) && !WritesOverlap(region.begin, static_cast(bytes))) { + if (auto* recorder = Recorder::Active()) { + const GuestMemory::ReadSiteScope site(GuestMemory::ReadSite::BufferUpload); + const auto slice = recorder->ReadBuffer(region.begin, static_cast(bytes)); + region.buffer = slice.buffer; + region.bufferOffset = slice.offset; + region.snapshot.clear(); + return; + } + } const auto usage = VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | (addressable ? VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT : 0u); if (profile) { // Why the region is copied rather than bound in place, totalled every 1000 uploads (under a @@ -2465,7 +2490,7 @@ VkDescriptorBufferInfo GuestBufferMemory::Descriptor(std::uint64_t address, std: Require(adjustment % 4 == 0, "guest buffer view off the storage buffer offset alignment is not DWORD aligned"); Require(bytes + adjustment <= context.limits.maxStorageBufferRange, "guest buffer view exceeds descriptor range limit"); const auto handle = region.direct != nullptr ? region.direct->buffer : region.mirror != nullptr ? region.mirror->buffer->Handle() : region.buffer->Handle(); - return {handle, offset - adjustment, bytes + adjustment}; + return {handle, offset - adjustment + (region.direct == nullptr && region.mirror == nullptr ? region.bufferOffset : 0), bytes + adjustment}; } ShaderRecompiler::BdaAbi::Range GuestBufferMemory::addressRange(const Region& region) { diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp index 2e8440e8386b..60c5f5c89a11 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp @@ -2206,53 +2206,56 @@ void Recorder::BoundKeptBytes() { } } -namespace { -std::size_t SnapshotPool(Recorder::SnapshotUse use) { - return use == Recorder::SnapshotUse::Storage ? 0 : 1; -} -} - -void Recorder::eraseDrawSnapshot(std::map::iterator entry) { - 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, 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 {}; - } - 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, 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(pool.recency.end()), std::move(buffer), derived}); - } catch (...) { - pool.recency.pop_back(); - throw; - } - pool.bytes += bytes; +std::pair, std::size_t> Recorder::AllocateDrawUpload(std::size_t bytes) { + constexpr std::size_t pageBytes = 65536; + constexpr auto usage = VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT; + Require(bytes != 0 && bytes <= context.limits.maxStorageBufferRange, "invalid draw upload size"); + ensureOpen(); + static const bool pooled = std::getenv("APS5_NO_DRAW_UPLOAD_POOL") == nullptr; + if (!pooled || bytes > pageBytes) { + auto buffer = std::make_shared(context, bytes, usage); + Keep(buffer, bytes); + return {std::move(buffer), 0}; + } + const auto alignment = std::max(4, context.limits.minStorageBufferOffsetAlignment); + auto offset = (open->drawUploadUsed + alignment - 1) & ~(alignment - 1); + if (open->drawUpload == nullptr || offset > pageBytes || bytes > pageBytes - offset) { + auto buffer = std::make_shared(context, pageBytes, usage); + Keep(buffer, pageBytes); + open->drawUpload = std::move(buffer); + offset = 0; + } + open->drawUploadUsed = offset + bytes; + return {open->drawUpload, offset}; +} + +BufferCache::Slice Recorder::ReadBuffer(std::uint64_t address, std::size_t bytes) { + constexpr std::size_t streamBytes = 4096; + std::uint64_t mappingGeneration = 0; + std::uint64_t generation = 0; + if (bytes > streamBytes) { + GuestMemory::FlushGpuWrites(address, bytes); + mappingGeneration = GuestAllocations::GuestAllocationsGeneration_nid_postfix(); + generation = GuestMemory::CollectWrites(address, bytes); + if (auto slice = bufferCache.Find(address, bytes, BufferCache::Use::Storage)) return slice; + } + auto [buffer, offset] = AllocateDrawUpload(bytes); + GuestMemory::Read(address, buffer->Bytes().subspan(offset, bytes)); + BufferCache::Slice slice{std::move(buffer), offset, bytes}; + bufferCache.NoteUpload(bytes); + if (generation != 0) bufferCache.Keep(address, generation, mappingGeneration, slice, BufferCache::Use::Storage); + return slice; +} + +std::shared_ptr Recorder::ReusableDrawSnapshot(std::uint64_t address, std::size_t bytes, SnapshotUse use, std::uint32_t* derived, std::size_t* offset) { + auto slice = bufferCache.Find(address, bytes, use); + if (derived != nullptr) *derived = slice.derived; + if (offset != nullptr) *offset = slice.offset; + return std::move(slice.buffer); +} + +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, std::size_t offset) { + bufferCache.Keep(address, generation, registryGeneration, {std::move(buffer), offset, bytes, derived}, use); } void Recorder::OnComplete(std::function action) { diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderAddressResources.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderAddressResources.cpp index 895fa359d54f..08bf8f771d38 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderAddressResources.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderAddressResources.cpp @@ -43,7 +43,7 @@ VkDescriptorBufferInfo ShaderResources::descriptor(Allocation& allocation) { return allocation.role == ShaderRecompiler::DescriptorRole::BdaPagetable ? bda->Table() : bda->Fault(); } Require(allocation.buffer != nullptr, "shader data has no buffer owner"); - return {allocation.buffer->Handle(), 0, allocation.size}; + return {allocation.buffer->Handle(), allocation.bufferOffset, allocation.size}; } } diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp index b15233be5966..798d2af0a02e 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp @@ -994,7 +994,7 @@ void ShaderResources::buildPrepare(std::span shaders, cons if (!bindings.empty()) { // The set is sized from the plan: every image element becomes exactly one descriptor // when stage B looks it up. - std::vector sizes; + auto& sizes = descriptorSizes; if (storageBuffers != 0) sizes.push_back({VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, static_cast(storageBuffers)}); if (plannedSampledImages != 0) sizes.push_back({VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, plannedSampledImages}); if (plannedStorageImages != 0) sizes.push_back({VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, plannedStorageImages}); @@ -1049,6 +1049,17 @@ void ShaderResources::buildComplete() { if (usesBda) bda = std::make_unique(context, guestMemory); else if (usesFaultBuffer) bda = std::make_unique(context); phase(BuildPhase::Bda); + for (auto& allocation : allocations) { + if (allocation.pendingData.empty()) continue; + if (auto* recorder = Recorder::Active()) { + std::tie(allocation.buffer, allocation.bufferOffset) = recorder->AllocateDrawUpload(allocation.size); + } else { + const bool refreshable = !allocation.dataWords.empty(); + allocation.buffer = std::make_shared(context, allocation.size, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | (refreshable ? VK_BUFFER_USAGE_TRANSFER_DST_BIT : 0u)); + } + std::memcpy(allocation.Bytes().data(), allocation.pendingData.data(), allocation.size); + allocation.pendingData = {}; + } if (_set != VK_NULL_HANDLE) { // One update call for the whole set: the info arrays are sized up front so every write's // pointer into them stays valid until the call. @@ -1058,11 +1069,11 @@ void ShaderResources::buildComplete() { bufferCount += binding.allocations.size(); imageCount += binding.imageAllocations.size(); } - std::vector buffers; - std::vector images; + auto& buffers = descriptorBuffers; + auto& images = descriptorImages; buffers.reserve(bufferCount); images.reserve(imageCount); - std::vector writes; + auto& writes = descriptorWrites; writes.reserve(bindings.size()); for (const auto& binding : bindings) { VkWriteDescriptorSet write{VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET}; @@ -1102,7 +1113,7 @@ void ShaderResources::buildComplete() { Require(allocation.dataAllocation >= 0, "a guest buffer off the storage buffer offset alignment in a shader without shader data is not implemented"); auto& data = allocations[static_cast(allocation.dataAllocation)]; Require(data.buffer != nullptr && allocation.dataByte < data.size, "guest buffer offset lies outside the shader's data buffer"); - data.buffer->Bytes()[allocation.dataByte] = static_cast(allocation.adjustment); + data.Bytes()[allocation.dataByte] = static_cast(allocation.adjustment); dataPatches.push_back({static_cast(allocation.dataAllocation), allocation.dataByte, allocation.adjustment}); } timing.descriptorsMs += phase(BuildPhase::Descriptors); @@ -1187,6 +1198,11 @@ void ShaderResources::reportDescriptorCaches() const { const auto samplerHits = context.samplerCache != nullptr ? context.samplerCache->Hits() : 0; const auto samplerMisses = context.samplerCache != nullptr ? context.samplerCache->Misses() : 0; AgcDriver::ProfilePrint_nid_no_patch("[descriptors] layouts %llu hits / %llu created, sets %llu from %llu pools, samplers %llu hits / %llu created\n", static_cast(descriptors.layoutHits), static_cast(descriptors.layoutMisses), static_cast(descriptors.sets), static_cast(descriptors.pools), static_cast(samplerHits), static_cast(samplerMisses)); + if (const auto* recorder = Recorder::Active()) { + const auto& buffers = recorder->BufferCounters(); + AgcDriver::ProfilePrint_nid_no_patch("[buffer-cache] %llu lookups, %llu hits, %llu invalidations (%llu mappings), %llu evictions; %llu read-only uploads, %.1f MiB streamed\n", static_cast(buffers.lookups), static_cast(buffers.hits), static_cast(buffers.invalidations), static_cast(buffers.mappingInvalidations), static_cast(buffers.evictions), static_cast(buffers.uploads), buffers.uploadedBytes / 1048576.0); + } + } std::vector ShaderResources::ContentKey(const CompiledShader& shader, bool dataWords, bool movableBuffers) { @@ -2262,7 +2278,7 @@ std::string ShaderResources::Describe() const { text += line; if (GuestMemory::Accessible(reinterpret_cast(allocation.address), allocation.size)) appendWords(reinterpret_cast(allocation.address), allocation.size); } else if (allocation.buffer) { - const auto bytes = allocation.buffer->Bytes(); + const auto bytes = allocation.Bytes(); std::snprintf(line, sizeof(line), " data+0x%zx nz=%.2f", allocation.size, sample(reinterpret_cast(bytes.data()), allocation.size)); text += line; appendWords(reinterpret_cast(bytes.data()), allocation.size); @@ -2275,9 +2291,13 @@ std::size_t ShaderResources::addDataBuffer(std::span words) const auto size = words.size() * sizeof(std::uint32_t); Require(size <= context.limits.maxStorageBufferRange, "shader data buffer exceeds descriptor range limit"); const bool refreshable = TemplateDataRefresh() && size <= MaxRefreshBytes; - auto buffer = std::make_unique(context, size, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | (refreshable ? VK_BUFFER_USAGE_TRANSFER_DST_BIT : 0u)); - std::memcpy(buffer->Bytes().data(), words.data(), size); - Allocation allocation{0, size, false, std::move(buffer)}; + Allocation allocation{0, size, false, nullptr}; + if (size <= 4096) { + allocation.pendingData = words; + } else { + allocation.buffer = std::make_shared(context, size, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | (refreshable ? VK_BUFFER_USAGE_TRANSFER_DST_BIT : 0u)); + std::memcpy(allocation.Bytes().data(), words.data(), size); + } if (refreshable) allocation.dataWords.assign(words.begin(), words.end()); allocations.push_back(std::move(allocation)); mixDataWords(dataWordsHash, allocations.back().dataWords); @@ -2345,10 +2365,11 @@ bool ShaderResources::RefreshData(VkCommandBuffer commands, const CompiledShader } void ShaderResources::writeDataWords(VkCommandBuffer commands, std::size_t allocation, std::span words) const { - const auto& buffer = *allocations[allocation].buffer; + const auto& item = allocations[allocation]; + const auto& buffer = *item.buffer; const auto size = words.size() * sizeof(std::uint32_t); if (std::none_of(dataPatches.begin(), dataPatches.end(), [&](const DataPatch& patch) { return patch.allocation == allocation; })) { - context.Resolved(&DeviceFunctions::cmdUpdateBuffer, "vkCmdUpdateBuffer")(commands, buffer.Handle(), 0, size, words.data()); + context.Resolved(&DeviceFunctions::cmdUpdateBuffer, "vkCmdUpdateBuffer")(commands, buffer.Handle(), item.bufferOffset, size, words.data()); return; } std::vector patched(words.begin(), words.end()); @@ -2356,7 +2377,7 @@ void ShaderResources::writeDataWords(VkCommandBuffer commands, std::size_t alloc for (const auto& patch : dataPatches) { if (patch.allocation == allocation && patch.byte < size) bytes[patch.byte] = static_cast(patch.adjustment); } - context.Resolved(&DeviceFunctions::cmdUpdateBuffer, "vkCmdUpdateBuffer")(commands, buffer.Handle(), 0, size, patched.data()); + context.Resolved(&DeviceFunctions::cmdUpdateBuffer, "vkCmdUpdateBuffer")(commands, buffer.Handle(), item.bufferOffset, size, patched.data()); } void ShaderResources::PrecollectSurfaces() const { @@ -2699,7 +2720,7 @@ std::optional> ShaderResources::MovedR const auto& item = allocations[index]; if (item.guest || item.buffer == nullptr || item.size != binding.guestDescriptor.size() * sizeof(std::uint32_t)) return std::nullopt; const bool patched = std::any_of(dataPatches.begin(), dataPatches.end(), [&](const DataPatch& patch) { return patch.allocation == index; }); - const bool same = !item.dataWords.empty() ? item.dataWords == binding.guestDescriptor : !patched && std::memcmp(item.buffer->Bytes().data(), binding.guestDescriptor.data(), item.size) == 0; + const bool same = !item.dataWords.empty() ? item.dataWords == binding.guestDescriptor : !patched && std::memcmp(item.Bytes().data(), binding.guestDescriptor.data(), item.size) == 0; if (same) continue; if (item.dataWords.empty() && patched) return std::nullopt; moved.push_back({index, 0, item.size, binding.guestDescriptor}); @@ -2737,19 +2758,21 @@ std::optional> ShaderResources::MovedR std::shared_ptr ShaderResources::PrepareDrawBindings(Recorder& recorder, std::span moved) const { if (_set == VK_NULL_HANDLE || usesBda) return {}; const auto reads = guestMemory.InPlaceReads(); + if (reads.empty() && moved.empty()) return {}; auto result = std::make_shared(); std::vector selected; for (std::size_t index = 0; index < allocations.size(); ++index) { const auto& item = allocations[index]; const auto override = std::find_if(moved.begin(), moved.end(), [&](const MovedBuffer& entry) { return entry.allocation == index; }); if (override != moved.end() && !override->words.empty()) { - auto buffer = std::make_shared(context, override->size, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT); - std::memcpy(buffer->Bytes().data(), override->words.data(), override->size); + auto [buffer, offset] = recorder.AllocateDrawUpload(override->size); + auto bytes = buffer->Bytes().subspan(offset, override->size); + std::memcpy(bytes.data(), override->words.data(), override->size); for (const auto& patch : dataPatches) { - if (patch.allocation == index && patch.byte < override->size) buffer->Bytes()[patch.byte] = static_cast(patch.adjustment); + if (patch.allocation == index && patch.byte < override->size) bytes[patch.byte] = static_cast(patch.adjustment); } selected.push_back(index); - result->snapshots.push_back({0, std::move(buffer)}); + result->snapshots.push_back({0, std::move(buffer), offset, override->size}); continue; } std::uint64_t address = item.address; @@ -2766,56 +2789,39 @@ std::shared_ptr ShaderResources::PrepareDrawBindi const auto bytes = size + item.adjustment; const auto registryGeneration = GuestAllocations::GuestAllocationsGeneration_nid_postfix(); const auto generation = GuestMemory::CollectWrites(begin, bytes); - auto buffer = recorder.ReusableDrawSnapshot(begin, bytes); + std::size_t offset = 0; + auto buffer = recorder.ReusableDrawSnapshot(begin, bytes, Recorder::SnapshotUse::Storage, nullptr, &offset); if (buffer == nullptr) { - buffer = std::make_shared(context, bytes, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_SRC_BIT); - std::memcpy(buffer->Bytes().data(), reinterpret_cast(begin), bytes); - recorder.KeepDrawSnapshot(begin, bytes, generation, registryGeneration, buffer); + std::tie(buffer, offset) = recorder.AllocateDrawUpload(bytes); + std::memcpy(buffer->Bytes().data() + offset, reinterpret_cast(begin), bytes); + recorder.KeepDrawSnapshot(begin, bytes, generation, registryGeneration, buffer, Recorder::SnapshotUse::Storage, 0, offset); } selected.push_back(index); - result->snapshots.push_back({begin, std::move(buffer)}); + result->snapshots.push_back({begin, std::move(buffer), offset, bytes}); CaptureTrace::Log("draw-snapshot batch=%llu address=%llx bytes=%zu", static_cast(recorder.Submissions() + 1), static_cast(begin), bytes); } if (selected.empty()) return {}; Require(context.descriptorCache != nullptr, "draw snapshots require a descriptor cache"); - std::map counts; - for (const auto& binding : bindings) counts[binding.layout.descriptorType] += binding.layout.descriptorCount; - std::vector sizes; - for (const auto& [type, count] : counts) sizes.push_back({type, count}); result->cache = context.descriptorCache; - result->allocation = result->cache->Allocate(_layout, sizes); + result->allocation = result->cache->Allocate(_layout, descriptorSizes); Require(result->allocation.set != VK_NULL_HANDLE, "draw snapshot descriptor allocation failed"); - std::vector copies; - for (const auto& binding : bindings) { - VkCopyDescriptorSet copy{VK_STRUCTURE_TYPE_COPY_DESCRIPTOR_SET}; - copy.srcSet = _set; - copy.srcBinding = binding.layout.binding; - copy.dstSet = result->allocation.set; - copy.dstBinding = binding.layout.binding; - copy.descriptorCount = binding.layout.descriptorCount; - copies.push_back(copy); - } - const auto update = context.Resolved(&DeviceFunctions::updateDescriptorSets, "vkUpdateDescriptorSets"); - update(context.device, 0, nullptr, static_cast(copies.size()), copies.data()); - std::vector infos; - infos.reserve(selected.size()); - for (const auto& snapshot : result->snapshots) infos.push_back({snapshot.buffer->Handle(), 0, snapshot.buffer->Bytes().size()}); - std::vector writes; - for (const auto& binding : bindings) { + auto buffers = descriptorBuffers; + auto writes = descriptorWrites; + for (std::size_t index = 0; index < bindings.size(); ++index) { + const auto& binding = bindings[index]; + auto& write = writes[index]; + write.dstSet = result->allocation.set; + if (binding.allocations.empty()) continue; + const auto offset = static_cast(write.pBufferInfo - descriptorBuffers.data()); + write.pBufferInfo = buffers.data() + offset; for (std::size_t element = 0; element < binding.allocations.size(); ++element) { const auto found = std::find(selected.begin(), selected.end(), binding.allocations[element]); if (found == selected.end()) continue; - VkWriteDescriptorSet write{VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET}; - write.dstSet = result->allocation.set; - write.dstBinding = binding.layout.binding; - write.dstArrayElement = static_cast(element); - write.descriptorCount = 1; - write.descriptorType = binding.layout.descriptorType; - write.pBufferInfo = &infos[static_cast(found - selected.begin())]; - writes.push_back(write); + const auto& snapshot = result->snapshots[static_cast(found - selected.begin())]; + buffers[offset + element] = {snapshot.buffer->Handle(), snapshot.offset, snapshot.size}; } } - update(context.device, static_cast(writes.size()), writes.data(), 0, nullptr); + context.Resolved(&DeviceFunctions::updateDescriptorSets, "vkUpdateDescriptorSets")(context.device, static_cast(writes.size()), writes.data(), 0, nullptr); recorder.Keep(result); return result; } diff --git a/core/libs/prx/libSceAgcDriver/tests/GuestAllocations.cpp b/core/libs/prx/libSceAgcDriver/tests/GuestAllocations.cpp index bb338d02ee3d..9d66fc0db301 100644 --- a/core/libs/prx/libSceAgcDriver/tests/GuestAllocations.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/GuestAllocations.cpp @@ -6,6 +6,7 @@ #include #include #include +#include #include #include #if defined(__linux__) @@ -24,9 +25,103 @@ void reject(TAction action) { throw std::runtime_error("expected guest allocation ownership rejection"); } +void targetedLeaseTests() { + std::array memory{}; + const auto base = reinterpret_cast(memory.data()); + using GuestAllocations::GuestAllocationsAcquireRange_nid_no_patch; + { + GuestAllocations::Mutation mutation; + mutation.Add(memory.data(), 64, true, true); + mutation.Add(memory.data() + 64, 64, true, false); + mutation.Add(memory.data() + 128, 64, false, false); + mutation.Add(memory.data() + 256, 64, true, true); + } + Require(GuestAllocationsAcquireRange_nid_no_patch(0, 1).empty(), "a null address acquired a lease"); + Require(GuestAllocationsAcquireRange_nid_no_patch(base, 0).empty(), "an empty range acquired a lease"); + Require(GuestAllocationsAcquireRange_nid_no_patch(std::numeric_limits::max() - 1, 4).empty(), "an overflowing range acquired a lease"); + Require(GuestAllocationsAcquireRange_nid_no_patch(base - 1, 2).empty(), "a range before the allocation acquired a lease"); + Require(GuestAllocationsAcquireRange_nid_no_patch(base + 16, 49).empty(), "a lease crossed an allocation boundary"); + Require(GuestAllocationsAcquireRange_nid_no_patch(base + 128, 1).empty(), "unreadable memory acquired a lease"); + Require(GuestAllocationsAcquireRange_nid_no_patch(base + 192, 1).empty(), "an allocation gap acquired a lease"); + Require(GuestAllocationsAcquireRange_nid_no_patch(base + 320, 1).empty(), "a range past the allocation acquired a lease"); + { + const auto readOnly = GuestAllocationsAcquireRange_nid_no_patch(base + 64, 64); + Require(readOnly.size() == 1 && !readOnly.front()->writable, "a read-only lease lost its protection"); + const auto lease = GuestAllocationsAcquireRange_nid_no_patch(base + 16, 48); + Require(lease.size() == 1 && lease.front()->address == base && lease.front()->bytes == 64, "a subrange lease did not retain its containing allocation"); + GuestAllocations::Mutation mutation; + mutation.Remove(memory.data() + 256); + reject([&] { mutation.Remove(memory.data()); }); + } + { + GuestAllocations::Mutation mutation; + mutation.Protect(memory.data(), 64, false, false, [] {}); + } + Require(GuestAllocationsAcquireRange_nid_no_patch(base, 1).empty(), "a protection change left a readable lease"); + { + GuestAllocations::Mutation mutation; + mutation.Remove(memory.data()); + mutation.Add(memory.data(), 32, true, true); + } + Require(GuestAllocationsAcquireRange_nid_no_patch(base, 32).size() == 1 && GuestAllocationsAcquireRange_nid_no_patch(base, 33).empty(), "address reuse retained the previous allocation extent"); + { + GuestAllocations::Mutation mutation; + mutation.Remove(memory.data()); + mutation.Remove(memory.data() + 64); + mutation.Remove(memory.data() + 128); + } + Require(GuestAllocationsAcquireRange_nid_no_patch(base, 1).empty(), "a removed allocation acquired a lease"); +} + +void rangeMutationTests() { + std::array memory{}; + const auto base = reinterpret_cast(memory.data()); + { + GuestAllocations::Mutation mutation; + mutation.Add(memory.data(), 128, true, true); + mutation.Add(memory.data() + 192, 128, true, true); + mutation.RequireAvailable(memory.data() + 128, 64); + reject([&] { mutation.RequireAvailable(memory.data() + 127, 2); }); + reject([&] { mutation.RequireAvailable(memory.data() + 191, 2); }); + Require(mutation.Covers(memory.data() + 96, 32), "a covered suffix was missed"); + Require(!mutation.Covers(memory.data() + 96, 97), "coverage skipped a hole"); + bool applied = false; + reject([&] { mutation.Protect(memory.data() + 96, 97, true, false, [&] { applied = true; }); }); + Require(!applied, "protection with a hole reached the host"); + reject([&] { mutation.Protect(memory.data() + 32, 32, true, false, [] { throw std::runtime_error("host protection failure"); }); }); + reject([&] { mutation.Unmap(memory.data() + 32, 32, [](const void*, std::size_t, const void*, bool) { throw std::runtime_error("host unmap failure"); }); }); + } + { + const auto lease = GuestAllocations::GuestAllocationsAcquire_nid_postfix(); + Require(lease.size() == 2 && lease[0]->bytes == 128 && lease[0]->writable && lease[1]->bytes == 128, + "a failed host operation changed allocation ranges"); + } + { + const auto unrelated = GuestAllocations::GuestAllocationsAcquireRange_nid_no_patch(base + 192, 128); + GuestAllocations::Mutation mutation; + mutation.Protect(memory.data() + 32, 32, true, false, [] {}); + Require(mutation.Covers(memory.data(), 128), "coverage did not cross protection fragments"); + mutation.Unmap(memory.data(), 128, [&](const void* pointer, std::size_t bytes, const void* allocation, bool last) { + Require(pointer == memory.data() && bytes == 128 && allocation == memory.data() && last, + "unmapping a split allocation did not release its last fragment"); + }); + Require(unrelated.size() == 1 && unrelated[0]->address == base + 192 && unrelated[0]->bytes == 128, + "a neighboring mutation changed an unrelated lease"); + mutation.RequireAvailable(memory.data(), 192); + mutation.Add(memory.data(), 128, true, true); + mutation.Remove(memory.data()); + } + { + GuestAllocations::Mutation mutation; + mutation.Remove(memory.data() + 192); + } +} + } void RunGuestAllocationTests() { + targetedLeaseTests(); + rangeMutationTests(); void* pointer = GuestHeap::GuestHeapAllocate_nid_postfix(32); Require(reinterpret_cast(pointer) % alignof(std::max_align_t) == 0, "guest malloc is not suitably aligned"); std::memset(pointer, 0x55, 32); diff --git a/core/libs/prx/libSceAgcDriver/tests/Recorder.cpp b/core/libs/prx/libSceAgcDriver/tests/Recorder.cpp index 61d55d291841..aebd0c3a67f7 100644 --- a/core/libs/prx/libSceAgcDriver/tests/Recorder.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/Recorder.cpp @@ -1,4 +1,5 @@ #include "prx/libSceAgcDriver/Graphics/include/Recorder.hpp" +#include "prx/libSceAgcDriver/Graphics/include/BufferPool.hpp" #include "prx/libSceAgcDriver/Graphics/include/Draw.hpp" #include "prx/libSceAgcDriver/Graphics/include/DccMetadata.hpp" #include "prx/libSceAgcDriver/Graphics/include/GuestBufferMemory.hpp" @@ -6,6 +7,8 @@ #include "prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp" #include "prx/libSceAgcDriver/Graphics/include/Shaders.hpp" #include "prx/libSceAgcDriver/Graphics/include/Texture.hpp" +#include "prx/libSceAgcDriver/Graphics/include/TextureCache.hpp" +#include "prx/libc/include/general/VabiMacros.hpp" #include "prx/libSceAgcDriver/Graphics/include/TextureDetiler.hpp" #include "prx/libSceAgcDriver/Graphics/include/UnitShadow.hpp" #include "prx/libSceAgcDriver/Execution/include/BdaFeatures.hpp" @@ -39,6 +42,13 @@ #include #include +extern "C" { +int APS5_VABI sceKernelAllocateDirectMemory(std::int64_t, std::int64_t, std::size_t, std::size_t, int, std::int64_t*); +int APS5_VABI sceKernelMapDirectMemory(void**, std::size_t, int, int, std::int64_t, std::size_t); +int APS5_VABI sceKernelReleaseDirectMemory(std::int64_t, std::size_t); +int APS5_VABI sceKernelMunmap(void*, std::size_t); +} + namespace { using namespace AgcDriver::Graphics; @@ -188,6 +198,7 @@ class Device { context.formatProperties = function("vkGetPhysicalDeviceFormatProperties"); context.Function("vkGetDeviceQueue")(context.device, family, 0, &context.queue); VkCommandPoolCreateInfo pool{VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO}; + pool.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT; pool.queueFamilyIndex = family; Check(context.Function("vkCreateCommandPool")(context.device, &pool, nullptr, &context.pool), "vkCreateCommandPool"); } catch (...) { @@ -1028,8 +1039,9 @@ void resourceReadTests(const Device& device, Recorder& recorder) { const auto commands = snapshotRecorder.Commands(); RecordMemoryBarrier(snapshotContext, commands, VK_PIPELINE_STAGE_HOST_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_ACCESS_HOST_WRITE_BIT, VK_ACCESS_TRANSFER_READ_BIT); const auto copy = snapshotContext.Function("vkCmdCopyBuffer"); - VkBufferCopy region{0, 0, elementBytes}; + VkBufferCopy region{first->snapshots[0].offset, 0, elementBytes}; copy(commands, first->snapshots[0].buffer->Handle(), downloaded->Handle(), 1, ®ion); + region.srcOffset = second->snapshots[0].offset; region.dstOffset = elementBytes; copy(commands, second->snapshots[0].buffer->Handle(), downloaded->Handle(), 1, ®ion); RecordMemoryBarrier(snapshotContext, commands, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_HOST_BIT, VK_ACCESS_TRANSFER_WRITE_BIT, VK_ACCESS_HOST_READ_BIT); @@ -1127,9 +1139,9 @@ void misalignedSnapshotTests(const Device& device, Recorder& recorder) { Require(push[0] == std::byte{0} && adjustment == offset % alignment, "the inner view's shader offset is not its distance from the binding"); const auto bindings = resources.PrepareDrawBindings(snapshotRecorder); Require(bindings != nullptr && bindings->snapshots.size() == 2, "read-only draw inputs were not snapshotted"); - const auto outerContents = bindings->snapshots[0].buffer->Bytes(); + const auto outerContents = bindings->snapshots[0].Bytes(); Require(outerContents.size() >= outerBytes && std::memcmp(outerContents.data(), guest + outer, outerBytes) == 0, "an aligned draw snapshot misses its view's bytes"); - const auto contents = bindings->snapshots[1].buffer->Bytes(); + const auto contents = bindings->snapshots[1].Bytes(); Require(contents.size() >= adjustment + elementBytes, "a draw snapshot ends before the bytes the shader reads"); Require(std::memcmp(contents.data() + adjustment, guest + offset, elementBytes) == 0, "the shader's offset into a draw snapshot misses the view's bytes"); snapshotRecorder.Sync(); @@ -1137,6 +1149,609 @@ void misalignedSnapshotTests(const Device& device, Recorder& recorder) { recorder.Activate(); } +class DescriptorUpdates { +public: + struct Contents { + std::map, VkDescriptorBufferInfo> buffers; + std::map, VkDescriptorImageInfo> images; + }; + explicit DescriptorUpdates(Context& context) : context(context), previous(context.functions), + update(context.Resolved(&DeviceFunctions::updateDescriptorSets, "vkUpdateDescriptorSets")) { + Require(active == nullptr, "nested descriptor update capture"); + if (previous != nullptr) functions = *previous; + functions.updateDescriptorSets = captureUpdate; + context.functions = &functions; + active = this; + } + ~DescriptorUpdates() { context.functions = previous; active = nullptr; } + std::vector calls; + std::uint32_t copies = 0; + +private: + static VKAPI_ATTR void VKAPI_CALL captureUpdate(VkDevice device, std::uint32_t count, const VkWriteDescriptorSet* writes, std::uint32_t copyCount, const VkCopyDescriptorSet* copies) { + Contents contents; + for (std::uint32_t i = 0; i < count; ++i) { + const auto& write = writes[i]; + for (std::uint32_t element = 0; element < write.descriptorCount; ++element) { + const auto key = std::pair{write.dstBinding, write.dstArrayElement + element}; + if (write.descriptorType == VK_DESCRIPTOR_TYPE_STORAGE_BUFFER) contents.buffers[key] = write.pBufferInfo[element]; + else contents.images[key] = write.pImageInfo[element]; + } + } + active->calls.push_back(std::move(contents)); + active->copies += copyCount; + active->update(device, count, writes, copyCount, copies); + } + Context& context; + const DeviceFunctions* previous; + DeviceFunctions functions{}; + PFN_vkUpdateDescriptorSets update; + static inline DescriptorUpdates* active = nullptr; +}; + +void drawDescriptorWriteTests(const Device& device, Recorder& recorder) { + auto context = device.GetContext(); + DescriptorUpdates updates(context); + { + DescriptorCache cache(context); + context.descriptorCache = &cache; + Recorder snapshots(context); + snapshots.Activate(); + ShaderRecompiler::RecompileResult program; + ShaderRecompiler::DescriptorBinding data{}; + data.kind = ShaderRecompiler::DescriptorKind::StorageBuffer; + data.role = ShaderRecompiler::DescriptorRole::FlattenedSrt; + data.binding = 2; + data.count = 1; + data.guestDescriptor = {1, 2, 3, 4}; + program.bindings.push_back(data); + data.binding = 7; + program.bindings.push_back(data); + ShaderRecompiler::DescriptorBinding sampler{}; + sampler.kind = ShaderRecompiler::DescriptorKind::Sampler; + sampler.role = ShaderRecompiler::DescriptorRole::GuestSamplers; + sampler.binding = 11; + sampler.count = 2; + sampler.guestDescriptor.resize(8); + sampler.samplerDepthCompare = {false, false}; + program.bindings.push_back(sampler); + const CompiledShader shader{ShaderRecompiler::ShaderStage::Compute, &program, 0}; + ShaderResources resources(context, shader); + Require(updates.calls.size() == 1, "building resources did not write one descriptor set"); + const auto original = updates.calls.front(); + Require(original.buffers.size() == 2 && original.images.size() == 2, "descriptor test lacks mixed bindings and an image array"); + for (std::size_t allocation = 0; allocation < 2; ++allocation) { + const ShaderResources::MovedBuffer moved{allocation, 0, 16, {5, 6, 7, 8}}; + const auto draw = resources.PrepareDrawBindings(snapshots, std::span(&moved, 1)); + Require(draw != nullptr && draw->snapshots.size() == 1, "moved shader data did not create a draw snapshot"); + Require(updates.calls.size() == allocation + 2 && updates.copies == 0, "draw descriptors copied GPU memory or needed multiple updates"); + const auto& actual = updates.calls.back(); + Require(actual.buffers.size() == original.buffers.size() && actual.images.size() == original.images.size(), "snapshot update omitted unchanged descriptors"); + for (const auto& [key, before] : original.buffers) { + const auto after = actual.buffers.at(key); + const bool replaced = key.first == (allocation == 0 ? 2u : 7u); + const auto& snapshot = draw->snapshots.front(); + const auto expected = replaced ? snapshot.buffer->Handle() : before.buffer; + Require(after.buffer == expected && after.offset == (replaced ? snapshot.offset : before.offset) && after.range == before.range, "snapshot update replaced the wrong buffer or changed its range"); + if (replaced) Require(std::memcmp(snapshot.Bytes().data(), moved.words.data(), moved.size) == 0, "snapshot descriptor points outside its uploaded words"); + } + for (const auto& [key, before] : original.images) { + const auto after = actual.images.at(key); + Require(after.sampler == before.sampler && after.imageView == before.imageView && after.imageLayout == before.imageLayout, "snapshot update changed an image descriptor"); + } + } + snapshots.Sync(); + } + recorder.Activate(); +} + +void shaderDataSliceTests(const Device& device, Recorder& outer) { + auto context = device.GetContext(); + context.hostImportAlignment = 0; + context.dmaBufImport = false; + context.limits.minStorageBufferOffsetAlignment = std::max(context.limits.minStorageBufferOffsetAlignment, 16); + DescriptorUpdates updates(context); + DescriptorCache descriptors(context); + context.descriptorCache = &descriptors; + Recorder recorder(context); + recorder.Activate(); + struct Restore { + Recorder& recorder; + Recorder& outer; + ~Restore() { recorder.Sync(); outer.Activate(); } + } restore{recorder, outer}; + const auto [guard, guardOffset] = recorder.AllocateDrawUpload(32); + std::fill_n(guard->Bytes().begin() + guardOffset, 32, std::byte{0xaa}); + alignas(64) std::array guest{1, 2, 3, 4, 5, 6, 7, 8}; + ShaderRecompiler::RecompileResult program; + program.variantId = 1000020; + program.memoryOffsetDword = 2; + ShaderRecompiler::DescriptorBinding buffers{}; + buffers.kind = ShaderRecompiler::DescriptorKind::StorageBuffer; + buffers.role = ShaderRecompiler::DescriptorRole::GuestBuffers; + buffers.binding = 0; + buffers.count = 2; + buffers.bufferWritten = {false, false}; + for (const auto [pointer, bytes] : {std::pair{guest.data(), 32u}, std::pair{guest.data() + 1, 8u}}) { + const auto address = reinterpret_cast(pointer); + for (auto word : {static_cast(address), static_cast(address >> 32u), bytes, 0x31016facu}) buffers.guestDescriptor.push_back(word); + } + program.bindings.push_back(buffers); + ShaderRecompiler::DescriptorBinding data{}; + data.kind = ShaderRecompiler::DescriptorKind::StorageBuffer; + data.role = ShaderRecompiler::DescriptorRole::ShaderData; + data.binding = 3; + data.count = 1; + data.guestDescriptor = {0x11, 0x22, 0}; + program.bindings.push_back(data); + data.role = ShaderRecompiler::DescriptorRole::FlattenedSrt; + data.binding = 5; + data.guestDescriptor = {5, 6, 7, 8}; + program.bindings.push_back(data); + const CompiledShader shader{ShaderRecompiler::ShaderStage::Compute, &program, 0}; + auto resources = std::make_shared(context, shader, std::span{}, true); + Require(updates.calls.empty(), "deferred shader data published descriptors before completion"); + resources->Complete(); + recorder.Keep(resources); + const auto first = updates.calls.back().buffers.at({3, 0}); + const auto second = updates.calls.back().buffers.at({5, 0}); + Require(first.buffer == guard->Handle() && second.buffer == first.buffer && first.offset > guardOffset && second.offset >= first.offset + first.range, "shader data did not use distinct aligned page slices"); + Require(first.offset % context.limits.minStorageBufferOffsetAlignment == 0 && second.offset % context.limits.minStorageBufferOffsetAlignment == 0, "shader data slice is misaligned"); + Buffer readback(context, 84, VK_BUFFER_USAGE_TRANSFER_DST_BIT); + const auto read = [&](std::size_t destination) { + CopyBuffer(context, recorder.Commands(), first.buffer, first.offset, readback.Handle(), destination, first.range); + CopyBuffer(context, recorder.Commands(), second.buffer, second.offset, readback.Handle(), destination + first.range, second.range); + }; + read(0); + auto changed = program; + changed.bindings[1].guestDescriptor = {0x33, 0x44, 0}; + const CompiledShader live{ShaderRecompiler::ShaderStage::Compute, &changed, 0}; + const auto refresh = [&](const CompiledShader& current) { + RecordMemoryBarrier(context, recorder.Commands(), VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_ACCESS_TRANSFER_READ_BIT, VK_ACCESS_TRANSFER_WRITE_BIT); + Require(resources->RefreshData(recorder.Commands(), current, &recorder), "shader data refresh did not record changed words"); + RecordMemoryBarrier(context, recorder.Commands(), VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_ACCESS_TRANSFER_WRITE_BIT, VK_ACCESS_TRANSFER_READ_BIT); + }; + refresh(live); + read(28); + refresh(shader); + read(56); + Require(!resources->RefreshData(recorder.Commands(), shader, &recorder), "unchanged shader data refreshed again"); + program = {}; + changed = {}; + resources.reset(); + RecordMemoryBarrier(context, recorder.Commands(), VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_HOST_BIT, VK_ACCESS_TRANSFER_WRITE_BIT, VK_ACCESS_HOST_READ_BIT); + recorder.Sync(); + const std::array expected{0x11, 0x22, 0x400, 5, 6, 7, 8, 0x33, 0x44, 0x400, 5, 6, 7, 8, 0x11, 0x22, 0x400, 5, 6, 7, 8}; + Require(std::memcmp(readback.Bytes().data(), expected.data(), sizeof(expected)) == 0, "shader data updates lost ordering, alignment patches or neighboring slices"); + Require(std::all_of(guard->Bytes().begin() + guardOffset, guard->Bytes().begin() + guardOffset + 32, [](auto byte) { return byte == std::byte{0xaa}; }), "shader data overwrote another draw's page slice"); + std::cout << "Shader data slices preserve deferred construction, patches, neighboring data and GPU-ordered refreshes\n"; +} + +void drawUploadTests(const Device& device, Recorder& recorder) { + recorder.Sync(); + const auto& context = device.GetContext(); + constexpr std::array sizes{4, 260, 4096, 65532, 12, 65540, 8188}; + constexpr std::size_t batches = 3; + std::size_t total = 0; + for (const auto bytes : sizes) total += bytes * batches; + Buffer readback(context, total, VK_BUFFER_USAGE_TRANSFER_DST_BIT); + std::vector expected(total); + std::shared_ptr held; + std::size_t heldOffset = 0; + std::size_t destination = 0; + for (std::size_t batch = 0; batch < batches; ++batch) { + const auto keptBefore = recorder.InFlightKeptBytes(); + std::vector pages; + std::size_t pageBytes = 0; + for (std::size_t i = 0; i < sizes.size(); ++i) { + const auto [buffer, offset] = recorder.AllocateDrawUpload(sizes[i]); + if (std::find(pages.begin(), pages.end(), buffer->Handle()) == pages.end()) { + pages.push_back(buffer->Handle()); + pageBytes += buffer->Bytes().size(); + } + Require(offset % context.limits.minStorageBufferOffsetAlignment == 0, "draw upload violates storage descriptor alignment"); + const auto value = static_cast(batch * sizes.size() + i + 1); + const auto bytes = buffer->Bytes().subspan(offset, sizes[i]); + std::fill(bytes.begin(), bytes.end(), value); + std::fill_n(expected.begin() + destination, sizes[i], value); + if (held == nullptr) { + held = buffer; + heldOffset = offset; + } + CopyBuffer(context, recorder.Commands(), buffer->Handle(), offset, readback.Handle(), destination, sizes[i]); + destination += sizes[i]; + } + RecordMemoryBarrier(context, recorder.Commands(), VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_HOST_BIT, VK_ACCESS_TRANSFER_WRITE_BIT, VK_ACCESS_HOST_READ_BIT); + recorder.Submit(); + Require(recorder.InFlightKeptBytes() == keptBefore + pageBytes, "draw uploads must count each retained buffer once in the batch byte budget"); + } + recorder.Sync(); + Require(recorder.InFlightKeptBytes() == 0, "finished draw uploads remain in the batch byte budget"); + Require(std::equal(expected.begin(), expected.end(), readback.Bytes().begin()), "draw uploads were overwritten before the GPU read them"); + for (unsigned i = 0; i < 4; ++i) { + const auto [buffer, offset] = recorder.AllocateDrawUpload(65536); + std::fill_n(buffer->Bytes().begin() + offset, 65536, std::byte{0xff}); + } + recorder.Sync(); + Require(held->Bytes()[heldOffset] == std::byte{1}, "a retained upload was recycled after its batch completed"); + std::cout << "Draw upload alignment, page rollover, large allocations and batch lifetime passed\n"; +} + +void copiedBufferResidencyTests(const Device& device, Recorder& outer) { + using namespace AgcDriver::GuestMemory; + auto context = device.GetContext(); + context.hostImportAlignment = 0; + context.dmaBufImport = false; + context.limits.minStorageBufferOffsetAlignment = std::max(context.limits.minStorageBufferOffsetAlignment, 16); + DescriptorUpdates updates(context); + DescriptorCache descriptors(context); + context.descriptorCache = &descriptors; + Recorder recorder(context); + recorder.Activate(); + constexpr std::size_t bytes = 65536; + void* block = AllocateWatched(bytes, bytes); + Require(block != nullptr, "copied-buffer test requires watched memory"); + struct Release { + void* block; + Recorder& recorder; + Recorder& outer; + ~Release() { recorder.Sync(); ReleaseWatched(block, bytes); outer.Activate(); } + } release{block, recorder, outer}; + const auto address = reinterpret_cast(block); + std::memset(block, 0x11, bytes); + const auto descriptor = [](std::uint64_t address, std::uint32_t size) { + return std::array{static_cast(address), static_cast(address >> 32u) & 0xffffu, size, 0x31016fac}; + }; + ShaderRecompiler::RecompileResult program; + program.variantId = 1000010; + program.pushConstants.resize(16); + ShaderRecompiler::DescriptorBinding binding{}; + binding.kind = ShaderRecompiler::DescriptorKind::StorageBuffer; + binding.role = ShaderRecompiler::DescriptorRole::GuestBuffers; + binding.binding = 0; + binding.count = 2; + binding.bufferWritten = {false, false}; + for (auto word : descriptor(address, 8192)) binding.guestDescriptor.push_back(word); + for (auto word : descriptor(address + 4, 64)) binding.guestDescriptor.push_back(word); + program.bindings.push_back(binding); + const CompiledShader shader{ShaderRecompiler::ShaderStage::Compute, &program, 0}; + const auto build = [&] { + auto resources = std::make_shared(context, shader); + Require(!resources->HasCopiedWrites() && !resources->HoldsLease(), "read-only residency became a copied writer or pinned guest memory"); + recorder.Keep(resources); + return resources; + }; + const auto first = build(); + const auto firstInfo = updates.calls.back().buffers.at({0, 0}); + const auto innerInfo = updates.calls.back().buffers.at({0, 1}); + std::array push{}; + first->PatchPushConstants(push); + Require(innerInfo.buffer == firstInfo.buffer && innerInfo.offset == firstInfo.offset && innerInfo.range == 68 && push[1] == std::byte{4}, "copied residency lost a misaligned overlapping view"); + const auto uploads = recorder.BufferCounters().uploads; + build(); + const auto repeated = updates.calls.back().buffers.at({0, 0}); + Require(repeated.buffer == firstInfo.buffer && repeated.offset == firstInfo.offset && recorder.BufferCounters().uploads == uploads, "unchanged copied buffers were uploaded again"); + Buffer readback(context, 768, VK_BUFFER_USAGE_TRANSFER_DST_BIT); + const auto recordRead = [&](const VkDescriptorBufferInfo& info, std::size_t destination) { + const auto commands = recorder.Commands(); + CopyBuffer(context, commands, info.buffer, info.offset, readback.Handle(), destination, 256); + }; + recordRead(firstInfo, 0); + std::memset(block, 0x22, 256); + build(); + const auto changed = updates.calls.back().buffers.at({0, 0}); + Require(changed.buffer != firstInfo.buffer || changed.offset != firstInfo.offset, "CPU writes overwrote a retained buffer version"); + recordRead(changed, 256); + std::memset(block, 0x33, 256); + MarkWritten(address, 256); + build(); + const auto stored = updates.calls.back().buffers.at({0, 0}); + recordRead(stored, 512); + RecordMemoryBarrier(context, recorder.Commands(), VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_HOST_BIT, VK_ACCESS_TRANSFER_WRITE_BIT, VK_ACCESS_HOST_READ_BIT); + recorder.Sync(); + for (std::size_t i = 0; i < 3; ++i) { + const auto contents = readback.Bytes().subspan(i * 256, 256); + Require(std::all_of(contents.begin(), contents.end(), [&](std::byte value) { return value == static_cast(0x11 * (i + 1)); }), "GPU reads did not preserve each copied buffer version"); + } + { + GuestAllocations::Mutation mutation; + } + GuestAllocations::GuestAllocationsInvalidate_nid_postfix(address + bytes, bytes); + build(); + const auto unrelated = updates.calls.back().buffers.at({0, 0}); + Require(unrelated.buffer == stored.buffer && unrelated.offset == stored.offset, "unrelated mapping changes discarded copied residency"); + GuestAllocations::GuestAllocationsInvalidate_nid_postfix(address, bytes); + build(); + const auto remapped = updates.calls.back().buffers.at({0, 0}); + Require(remapped.buffer != stored.buffer || remapped.offset != stored.offset, "copied residency survived an overlapping mapping change"); + auto writerProgram = program; + writerProgram.variantId = 1000011; + writerProgram.bindings.front().bufferWritten[1] = true; + const CompiledShader writerShader{ShaderRecompiler::ShaderStage::Compute, &writerProgram, 0}; + ShaderResources writer(context, writerShader); + Require(writer.HasCopiedWrites() && updates.calls.back().buffers.at({0, 0}).buffer != remapped.buffer, "an overlapping writer reused immutable read-only storage"); + const auto tinyFirst = recorder.ReadBuffer(address, 256); + const auto tinySecond = recorder.ReadBuffer(address, 256); + Require(tinyFirst.buffer == tinySecond.buffer && tinyFirst.offset != tinySecond.offset, "tiny copied buffers did not stream through distinct page slices"); + BumpCollectEpoch(); + const auto vertex = CopyDrawInput(context, &recorder, address, bytes, 1, Recorder::SnapshotUse::Vertex); + KeepDrawInput(&recorder, address, vertex, Recorder::SnapshotUse::Vertex, 0); + GuestAllocations::GuestAllocationsInvalidate_nid_postfix(address + bytes, bytes); + const auto prefix = CopyDrawInput(context, &recorder, address, bytes / 4, 1, Recorder::SnapshotUse::Vertex); + Require(prefix.reused && prefix.buffer == vertex.buffer, "unrelated mapping change discarded a larger vertex snapshot"); + GuestAllocations::GuestAllocationsInvalidate_nid_postfix(address + bytes / 2, bytes / 4); + const auto replacedPrefix = CopyDrawInput(context, &recorder, address, bytes / 4, 1, Recorder::SnapshotUse::Vertex); + Require(!replacedPrefix.reused, "vertex prefix promoted a stale mapping proof for its cached tail"); + std::cout << "Copied buffers preserve unchanged residency, CPU writes, driver writes, overlapping views, mapping generations and GPU lifetime\n"; +} + +void copiedBackingTests(const Device& device, Recorder& recorder) { + constexpr std::size_t bytes = 65536; + struct Release { + Recorder& recorder; + std::array mappings{}; + std::array physical{-1, -1}; + ~Release() { + recorder.Sync(); + for (const auto mapping : mappings) if (mapping != nullptr) sceKernelMunmap(mapping, bytes); + for (const auto backing : physical) if (backing >= 0) sceKernelReleaseDirectMemory(backing, bytes); + } + } release{recorder}; + for (auto& backing : release.physical) Require(sceKernelAllocateDirectMemory(0, 0x7fffffffffll, bytes, bytes, 0, &backing) == 0, "allocate copied buffer backing"); + Require(sceKernelMapDirectMemory(&release.mappings[0], bytes, 3, 0, release.physical[0], bytes) == 0, "map copied buffer backing"); + std::memset(release.mappings[0], 0x11, bytes); + const auto address = reinterpret_cast(release.mappings[0]); + const auto first = recorder.ReadBuffer(address, 8192); + Require(sceKernelMapDirectMemory(&release.mappings[1], bytes, 3, 0, release.physical[0], bytes) == 0, "alias copied buffer backing"); + std::memset(release.mappings[1], 0x22, bytes); + const auto throughAlias = recorder.ReadBuffer(address, 8192); + Require(sceKernelMapDirectMemory(&release.mappings[0], bytes, 3, 0x10, release.physical[1], bytes) == 0, "replace copied backing at the same address"); + std::memset(release.mappings[0], 0x33, bytes); + const auto remapped = recorder.ReadBuffer(address, 8192); + const auto alias = recorder.ReadBuffer(reinterpret_cast(release.mappings[1]), 8192); + const std::array versions{first, throughAlias, remapped, alias}; + const std::array expected{std::byte{0x11}, std::byte{0x22}, std::byte{0x33}, std::byte{0x22}}; + const auto& context = device.GetContext(); + Buffer readback(context, 4 * 8192, VK_BUFFER_USAGE_TRANSFER_DST_BIT); + for (std::size_t i = 0; i < versions.size(); ++i) CopyBuffer(context, recorder.Commands(), versions[i].buffer->Handle(), versions[i].offset, readback.Handle(), i * 8192, 8192); + RecordMemoryBarrier(context, recorder.Commands(), VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_HOST_BIT, VK_ACCESS_TRANSFER_WRITE_BIT, VK_ACCESS_HOST_READ_BIT); + recorder.Sync(); + for (std::size_t i = 0; i < versions.size(); ++i) { + const auto contents = readback.Bytes().subspan(i * 8192, 8192); + Require(std::all_of(contents.begin(), contents.end(), [&](auto value) { return value == expected[i]; }), "copied buffer reused stale alias or remapped contents"); + } + std::cout << "Copied buffer aliases and same-address backing replacement preserve recorded GPU reads\n"; +} + +void drawBindingsBenchmark(const Device& device) { + std::unique_lock gpu(GpuMutex()); + auto context = device.GetContext(); + DeviceFunctions functions; + FillDeviceFunctions(context, functions); + if (std::getenv("APS5_NO_PROC_TABLE") == nullptr) context.functions = &functions; + DescriptorCache cache(context); + context.descriptorCache = &cache; + Recorder recorder(context); + recorder.Activate(); + ShaderRecompiler::RecompileResult program; + std::vector moved; + for (std::uint32_t i = 0; i < 8; ++i) { + ShaderRecompiler::DescriptorBinding data{}; + data.kind = ShaderRecompiler::DescriptorKind::StorageBuffer; + data.role = ShaderRecompiler::DescriptorRole::FlattenedSrt; + data.binding = i; + data.count = 1; + data.guestDescriptor.resize(64, i); + moved.push_back({i, 0, data.guestDescriptor.size() * sizeof(std::uint32_t), data.guestDescriptor}); + program.bindings.push_back(std::move(data)); + } + const CompiledShader shader{ShaderRecompiler::ShaderStage::Compute, &program, 0}; + ShaderResources resources(context, shader); + std::array times{}; + std::uint64_t checksum = 0; + const auto lookups = DeviceProcLookups(); + for (std::size_t pass = 0; pass < times.size() + 1; ++pass) { + const auto started = std::chrono::steady_clock::now(); + for (unsigned batch = 0; batch < 160; ++batch) { + for (unsigned draw = 0; draw < 32; ++draw) { + moved.front().words.front() = batch * 32 + draw; + const auto bindings = resources.PrepareDrawBindings(recorder, moved); + Require(bindings != nullptr && bindings->snapshots.size() == moved.size(), "draw binding benchmark omitted an upload"); + checksum += std::to_integer(bindings->snapshots.front().Bytes().front()); + } + recorder.Sync(); + gpu.unlock(); + gpu.lock(); + } + if (pass != 0) times[pass - 1] = std::chrono::duration(std::chrono::steady_clock::now() - started).count() / (160 * 32); + } + std::sort(times.begin(), times.end()); + std::cout << "Draw binding benchmark: " << times[3] << " us/draw median, " << times.front() << " minimum, " << times.back() << " maximum, " << DeviceProcLookups() - lookups << " device lookups, checksum " << checksum << '\n'; +} + +void resourceBuildBenchmark(const Device& device, bool shaderData = false) { + std::unique_lock gpu(GpuMutex()); + auto context = device.GetContext(); + context.hostImportAlignment = 0; + context.dmaBufImport = false; + DeviceFunctions functions; + FillDeviceFunctions(context, functions); + context.functions = &functions; + DescriptorCache cache(context); + context.descriptorCache = &cache; + TextureDetiler detiler(context); + context.detiler = &detiler; + TextureCache textureCache(context); + context.textureCache = &textureCache; + context.bufferPool = std::make_shared(context); + Recorder recorder(context); + recorder.Activate(); + constexpr std::size_t bytes = 16 * 65536; + void* memory = AllocateWatched(bytes, 65536); + Require(memory != nullptr, "resource benchmark requires watched memory"); + { + GuestAllocations::Mutation mutation; + mutation.Add(memory, bytes, true, true); + } + struct Cleanup { + Context& context; + Recorder& recorder; + void* memory; + ~Cleanup() { + recorder.Sync(); + ClearCachedTextures(context.device); + { + GuestAllocations::Mutation mutation; + mutation.Remove(memory); + } + ReleaseWatched(memory, bytes); + } + } cleanup{context, recorder, memory}; + std::memset(memory, 0x71, bytes); + const auto address = reinterpret_cast(memory); + for (const std::uint32_t inputBytes : {256u, 16384u}) { + for (const std::uint32_t imageCount : {0u, 8u}) { + ShaderRecompiler::RecompileResult program; + program.variantId = 1000000 + imageCount + inputBytes; + program.pushConstants.resize(16); + for (std::uint32_t i = 0; i < 8; ++i) { + ShaderRecompiler::DescriptorBinding binding{}; + binding.kind = ShaderRecompiler::DescriptorKind::StorageBuffer; + binding.role = shaderData ? (i % 2 == 0 ? ShaderRecompiler::DescriptorRole::ShaderData : ShaderRecompiler::DescriptorRole::FlattenedSrt) : ShaderRecompiler::DescriptorRole::GuestBuffers; + binding.binding = i; + binding.count = 1; + binding.bufferWritten = {false}; + const auto base = address + i * inputBytes; + binding.guestDescriptor = {static_cast(base), static_cast(base >> 32), inputBytes, 0x31016fac}; + if (shaderData) binding.guestDescriptor.resize(inputBytes / 4, i + 1); + program.bindings.push_back(std::move(binding)); + } + for (std::uint32_t i = 0; i < imageCount; ++i) { + ShaderRecompiler::DescriptorBinding binding{}; + binding.kind = ShaderRecompiler::DescriptorKind::SampledImage; + binding.role = ShaderRecompiler::DescriptorRole::GuestImages; + binding.binding = 8 + i; + binding.count = 1; + binding.imageShape = ShaderRecompiler::DescriptorImageShape::Image2D; + binding.imageSamplers = {0}; + const auto base = address + 8 * 65536 + i * 16384; + binding.guestDescriptor = {static_cast(base >> 8), static_cast(base >> 40) | (56u << 20) | (3u << 30), 15u | (63u << 14), 0x90000fac, 0, 0, 0, 0}; + program.bindings.push_back(std::move(binding)); + } + const CompiledShader shader{ShaderRecompiler::ShaderStage::Fragment, &program, 0}; + ColorTarget target{}; + std::array times{}; + std::array buildTimes{}; + std::array retireTimes{}; +#ifndef _WIN32 + const auto cpuUs = [](clockid_t clock) { + timespec time{}; + Require(clock_gettime(clock, &time) == 0, "cannot read benchmark CPU time"); + return static_cast(time.tv_sec) * 1000000 + time.tv_nsec / 1000.0; + }; + std::array threadTimes{}; + std::array processTimes{}; +#endif + std::uint64_t checksum = 0; + for (std::size_t pass = 0; pass <= times.size(); ++pass) { +#ifndef _WIN32 + const auto threadStarted = cpuUs(CLOCK_THREAD_CPUTIME_ID); + const auto processStarted = cpuUs(CLOCK_PROCESS_CPUTIME_ID); +#endif + const auto started = std::chrono::steady_clock::now(); + double buildUs = 0; + double retireUs = 0; + for (unsigned batch = 0; batch < 32; ++batch) { + const auto buildStarted = std::chrono::steady_clock::now(); + AgcDriver::GuestMemory::BumpCollectEpoch(); + static_cast(recorder.Commands()); + for (unsigned draw = 0; draw < 32; ++draw) { + const auto base = address + ((batch * 32 + draw) % 8) * inputBytes; + program.bindings.front().guestDescriptor[0] = static_cast(base); + program.bindings.front().guestDescriptor[1] = static_cast(base >> 32); + auto resources = std::make_shared(context, std::span(&shader, 1), target, 0, 0); + checksum += resources->LayoutKey().size(); + recorder.Keep(std::move(resources)); + } + const auto built = std::chrono::steady_clock::now(); + buildUs += std::chrono::duration(built - buildStarted).count(); + recorder.Sync(); + gpu.unlock(); + gpu.lock(); + retireUs += std::chrono::duration(std::chrono::steady_clock::now() - built).count(); + } + if (pass != 0) { + times[pass - 1] = std::chrono::duration(std::chrono::steady_clock::now() - started).count() / 1024; + buildTimes[pass - 1] = buildUs / 1024; + retireTimes[pass - 1] = retireUs / 1024; +#ifndef _WIN32 + threadTimes[pass - 1] = (cpuUs(CLOCK_THREAD_CPUTIME_ID) - threadStarted) / 1024; + processTimes[pass - 1] = (cpuUs(CLOCK_PROCESS_CPUTIME_ID) - processStarted) / 1024; +#endif + } + } + std::sort(times.begin(), times.end()); + std::sort(buildTimes.begin(), buildTimes.end()); + std::sort(retireTimes.begin(), retireTimes.end()); +#ifndef _WIN32 + std::sort(threadTimes.begin(), threadTimes.end()); + std::sort(processTimes.begin(), processTimes.end()); +#endif + std::cout << (shaderData ? "Shader data batches (" : "Resource batches (") << inputBytes << " byte inputs, " << imageCount << " textures): median " << times[4] << " us/draw, p95 pass " << times[8] << " us/draw, minimum " << times[0] << " us, checksum " << checksum << ", build " << buildTimes[4] << " us/draw, retire " << retireTimes[4] << " us/draw"; +#ifndef _WIN32 + std::cout << ", thread CPU " << threadTimes[4] << " us/draw, process CPU " << processTimes[4] << " us/draw"; +#endif + std::cout << '\n'; + } + } +} + +void bufferMappingBenchmark(const Device& device) { + std::thread establishThreadedProcess([] {}); + establishThreadedProcess.join(); + auto context = device.GetContext(); + context.hostImportAlignment = 0; + context.dmaBufImport = false; + context.bufferPool = std::make_shared(context); + constexpr std::size_t count = 128; + constexpr std::size_t stride = 65536; + constexpr std::array sizes{128, 4096, 16384, 65536}; + void* memory = AllocateWatched(count * stride, stride); + Require(memory != nullptr, "mapping benchmark requires watched memory"); + struct Cleanup { + void* memory; + ~Cleanup() { ReleaseWatched(memory, count * stride); } + } cleanup{memory}; + const auto address = reinterpret_cast(memory); + for (std::size_t i = 0; i < count; ++i) std::memset(static_cast(memory) + i * stride, static_cast(i), stride); + for (const bool mappingChanges : {false, true}) { + Recorder recorder(context); + recorder.Activate(); + std::array times; + std::uint64_t checksum = 0; + std::uint64_t misses = 0; + for (std::size_t pass = 0; pass <= times.size(); ++pass) { + const auto started = std::chrono::steady_clock::now(); + for (unsigned frame = 0; frame < 128; ++frame) { + if (mappingChanges) GuestAllocations::GuestAllocationsInvalidate_nid_postfix(address + count * stride, stride); + for (std::size_t i = 0; i < count; ++i) { + AgcDriver::GuestMemory::BumpCollectEpoch(); + const auto input = address + i * stride; + const auto bytes = sizes[i % sizes.size()]; + const auto copy = CopyDrawInput(context, &recorder, input, bytes, 1, Recorder::SnapshotUse::Vertex); + KeepDrawInput(&recorder, input, copy, Recorder::SnapshotUse::Vertex, 0); + checksum += std::to_integer(copy.buffer->Bytes()[0]) + std::to_integer(copy.buffer->Bytes()[bytes - 1]); + if (pass != 0) misses += !copy.reused; + } + } + if (pass != 0) times[pass - 1] = std::chrono::duration(std::chrono::steady_clock::now() - started).count() / (128 * count); + } + std::ranges::sort(times); + Require(checksum == 10ull * 128 * count * (count - 1), "mapping benchmark copied the wrong input bytes"); + std::cout << "Vertex copies (unrelated mappings " << mappingChanges << "): median " << times[4] << " us/request, p95 pass " << times.back() << " us, misses " << misses << "/" << times.size() * 128 * count << ", checksum " << checksum << '\n'; + } +} + void drawSnapshotReuseTests(const Device& device, Recorder& recorder) { const auto& context = device.GetContext(); constexpr std::size_t bytes = 65536; @@ -1193,24 +1808,27 @@ void drawSnapshotReuseTests(const Device& device, Recorder& recorder) { const auto snapshot = [&](std::byte expected) { const auto bindings = resources.PrepareDrawBindings(snapshotRecorder); Require(bindings != nullptr && bindings->snapshots.size() == 1, "read-only draw input was not snapshotted"); - const auto buffer = bindings->snapshots[0].buffer; - const auto contents = buffer->Bytes(); + const auto& snapshot = bindings->snapshots[0]; + const auto contents = snapshot.Bytes(); Require(contents.size() == elementBytes && std::all_of(contents.begin(), contents.end(), [&](std::byte value) { return value == expected; }), "a draw snapshot does not hold the guest bytes of its draw"); - return buffer; + return std::pair{snapshot.buffer, snapshot.offset}; }; + const bool watched = AgcDriver::GuestMemory::Watched(element, elementBytes); const auto first = snapshot(std::byte{0x11}); - Require(snapshot(std::byte{0x11}) == first, "an unchanged draw input was copied again"); + const auto repeated = snapshot(std::byte{0x11}); + Require(!watched || repeated == first, "an unchanged watched draw input was copied again"); + Require(watched || repeated != first, "an unwatched imported input reused an unvalidated snapshot"); std::memset(reinterpret_cast(element), 0x22, elementBytes); const auto afterCpu = snapshot(std::byte{0x22}); Require(afterCpu != first, "a draw snapshot outlived a CPU store to its range"); - Require(snapshot(std::byte{0x22}) == afterCpu, "the recopied draw input was not kept"); + const auto repeatedCpu = snapshot(std::byte{0x22}); + Require(!watched || repeatedCpu == afterCpu, "the recopied watched draw input was not kept"); + Require(watched || repeatedCpu != afterCpu, "an unwatched imported input was kept after a CPU store"); std::memset(reinterpret_cast(element), 0x33, elementBytes); AgcDriver::GuestMemory::MarkWritten(element, 4); const auto afterStore = snapshot(std::byte{0x33}); Require(afterStore != afterCpu, "a draw snapshot outlived a driver store to its range"); - { - GuestAllocations::Mutation mutation; - } + GuestAllocations::GuestAllocationsInvalidate_nid_postfix(element, elementBytes); Require(snapshot(std::byte{0x33}) != afterStore, "a draw snapshot outlived a registry mutation"); snapshotRecorder.Sync(); } @@ -1307,7 +1925,9 @@ void drawInputReuseTests(const Device& device, Recorder& recorder) { GuestAllocations::Mutation mutation; mutation.Remove(other); } - Require(!CopyDrawInput(context, &recorder, address, size, 4, Use::Index32).reused, "a draw input outlived a registry mutation"); + Require(CopyDrawInput(context, &recorder, address, size, 4, Use::Index32).reused, "a draw input was discarded by an empty registry mutation"); + GuestAllocations::GuestAllocationsInvalidate_nid_postfix(address, size); + Require(!CopyDrawInput(context, &recorder, address, size, 4, Use::Index32).reused, "a draw input outlived an overlapping 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"); @@ -2448,6 +3068,7 @@ void dataRefreshTests(const Device& device, Recorder& recorder) { Require(!resources.DataWordsDiffer(original) && resources.DataWordsDiffer(live), "the per-word compare disagrees with the words"); Require(resources.RefreshData(recorder.Commands(), live, &recorder), "a refresh with different words recorded nothing"); Require(resources.DataWordsHash() == ShaderResources::DataWordsHash(live) && !resources.DataWordsDiffer(live), "the refreshed template's hash is not the patched words'"); + RecordMemoryBarrier(device.GetContext(), recorder.Commands(), VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_ACCESS_TRANSFER_WRITE_BIT, VK_ACCESS_TRANSFER_WRITE_BIT); Require(resources.RefreshData(recorder.Commands(), original, &recorder), "the refresh back recorded nothing"); Require(resources.DataWordsHash() == ShaderResources::DataWordsHash(original), "the refreshed template's hash is not the original words'"); Require(!resources.RefreshData(recorder.Commands(), original, &recorder), "a refresh with equal words recorded"); @@ -2812,13 +3433,58 @@ void keysFillTests(const Device& device, Recorder& recorder) { recorder.Sync(); } -int main() { +int main(int argc, char** argv) { try { Device device; + if (argc == 2 && std::string_view(argv[1]) == "--benchmark-draw-bindings") { + drawBindingsBenchmark(device); + return 0; + } + if (argc == 2 && std::string_view(argv[1]) == "--benchmark-resource-build") { + resourceBuildBenchmark(device); + return 0; + } + if (argc == 2 && std::string_view(argv[1]) == "--benchmark-buffer-mappings") { + bufferMappingBenchmark(device); + return 0; + } + if (argc == 2 && std::string_view(argv[1]) == "--benchmark-shader-data") { + resourceBuildBenchmark(device, true); + return 0; + } std::lock_guard gpu(GpuMutex()); std::cout << "host imports " << (PrepareImportWatch(device.GetContext()) == ImportWatch::Unwatch ? "are compared" : "stay watched") << '\n'; Recorder recorder(device.GetContext()); recorder.Activate(); + if (argc == 2 && std::string_view(argv[1]) == "--copied-buffers-only") { + copiedBufferResidencyTests(device, recorder); + copiedBackingTests(device, recorder); + return 0; + } + if (argc == 2 && std::string_view(argv[1]) == "--shader-data-only") { + shaderDataSliceTests(device, recorder); + dataRefreshTests(device, recorder); + return 0; + } + if (argc == 2 && std::string_view(argv[1]) == "--draw-upload-only") { + drawUploadTests(device, recorder); + drawDescriptorWriteTests(device, recorder); + return 0; + } + if (argc == 2 && std::string_view(argv[1]) == "--draw-snapshot-only") { + resourceReadTests(device, recorder); + misalignedSnapshotTests(device, recorder); + drawSnapshotReuseTests(device, recorder); + drawSnapshotEvictionTests(device); + drawInputReuseTests(device, recorder); + return 0; + } + if (argc == 2 && std::string_view(argv[1]) == "--draw-descriptors-only") { + drawDescriptorWriteTests(device, recorder); + std::cout << "Draw descriptor writes and snapshot overrides passed\n"; + return 0; + } + readTrackingTests(device, recorder); writeSettledTests(device, recorder); completionCountTests(device, recorder); @@ -2833,6 +3499,7 @@ int main() { resourceReadTests(device, recorder); misalignedSnapshotTests(device, recorder); drawSnapshotReuseTests(device, recorder); + drawDescriptorWriteTests(device, recorder); drawSnapshotEvictionTests(device); drawInputReuseTests(device, recorder); RunResidentPresentTests(device.GetContext()); @@ -2851,6 +3518,7 @@ int main() { importWindowTests(device, recorder); dataWordPositionsTests(); dataRefreshTests(device, recorder); + shaderDataSliceTests(device, recorder); minLodTests(device, recorder); firstLayerViewTests(device, recorder); atomicViewTests(device, recorder); diff --git a/core/libs/prx/libc/CMakeLists.txt b/core/libs/prx/libc/CMakeLists.txt index f57cdd011097..a835e0874ee3 100644 --- a/core/libs/prx/libc/CMakeLists.txt +++ b/core/libs/prx/libc/CMakeLists.txt @@ -55,6 +55,15 @@ if(BUILD_TESTING) set_tests_properties(guest_time_conversion PROPERTIES ENVIRONMENT_MODIFICATION "PATH=path_list_prepend:$") endif() + add_test_executable(guest_mapping_history_tests ${LIBS_INCLUDE_DIR}/tests/GuestMappingHistory.cpp) + target_include_directories(guest_mapping_history_tests PRIVATE ${LIBS_INCLUDE_DIR}) + target_link_libraries(guest_mapping_history_tests PRIVATE libc) + configure_windows_unwind(guest_mapping_history_tests) + add_test(NAME guest_mapping_history COMMAND guest_mapping_history_tests) + if(WIN32) + set_tests_properties(guest_mapping_history PROPERTIES ENVIRONMENT_MODIFICATION + "PATH=path_list_prepend:$") + endif() add_test_executable(guest_scan_count_tests ${LIBS_INCLUDE_DIR}/tests/GuestScanCount.cpp) target_include_directories(guest_scan_count_tests PRIVATE ${LIBS_INCLUDE_DIR}) target_link_libraries(guest_scan_count_tests PRIVATE libc) diff --git a/core/libs/prx/libc/include/GuestAllocations.hpp b/core/libs/prx/libc/include/GuestAllocations.hpp index 81c711b9e8f6..0c4b99cf2372 100644 --- a/core/libs/prx/libc/include/GuestAllocations.hpp +++ b/core/libs/prx/libc/include/GuestAllocations.hpp @@ -36,8 +36,10 @@ void GuestAllocationsRemove_nid_postfix(void* mutation, const void* pointer); void GuestAllocationsProtect_nid_postfix(void* mutation, const void* pointer, std::size_t bytes, bool readable, bool writable, const std::function& apply); void GuestAllocationsUnmap_nid_postfix(void* mutation, const void* pointer, std::size_t bytes, const std::function& apply); Lease GuestAllocationsAcquire_nid_postfix(); +Lease GuestAllocationsAcquireRange_nid_no_patch(std::uintptr_t address, std::size_t bytes); // Changes whenever a mutation ends, so callers can cache facts about guest mappings between changes. std::uint64_t GuestAllocationsGeneration_nid_postfix(); +std::uint64_t GuestAllocationsValidateMapping_nid_no_patch(std::uintptr_t address, std::size_t bytes, std::uint64_t since); // Precise invalidation for such caches: the callback runs, after the generation changed, for every // range whose mapping or protection changed (registry mutations and guest heap decommits). void GuestAllocationsSetInvalidator_nid_postfix(void (*callback)(std::uintptr_t address, std::size_t bytes)); diff --git a/core/libs/prx/libc/src/GuestAllocations.cpp b/core/libs/prx/libc/src/GuestAllocations.cpp index 344fcaa8295f..aa3a43faeb8b 100644 --- a/core/libs/prx/libc/src/GuestAllocations.cpp +++ b/core/libs/prx/libc/src/GuestAllocations.cpp @@ -1,4 +1,5 @@ #include "prx/libc/include/GuestAllocations.hpp" +#include #include #include #include @@ -8,6 +9,7 @@ #include #include #include +#include #include #ifdef _WIN32 #ifndef NOMINMAX @@ -37,6 +39,36 @@ std::atomic generation{1}; std::atomic invalidator{nullptr}; std::atomic pinWaiter{nullptr}; +struct MappingHistory { + struct Change { + std::uint64_t generation = 0; + std::uintptr_t address = 0; + std::size_t bytes = 0; + }; + std::mutex mutex; + std::array changes{}; + std::size_t next = 0; + std::uint64_t discardedThrough = 0; +}; + +MappingHistory& mappingHistory() { + static MappingHistory history; + return history; +} + +void publishChanges(std::span> ranges) { + auto& history = mappingHistory(); + std::lock_guard lock(history.mutex); + const auto nextGeneration = generation.load(std::memory_order_relaxed) + 1; + for (const auto& [address, bytes] : ranges) { + auto& change = history.changes[history.next]; + history.discardedThrough = change.generation; + change = {nextGeneration, address, bytes}; + history.next = (history.next + 1) % history.changes.size(); + } + generation.store(nextGeneration, std::memory_order_release); +} + std::chrono::milliseconds pinWait() { static const std::chrono::milliseconds value{[] { const char* text = std::getenv("APS5_PIN_WAIT_MS"); @@ -69,7 +101,7 @@ void* GuestAllocationsBegin_nid_postfix() { void GuestAllocationsEnd_nid_postfix(void* mutation) noexcept { auto* state = static_cast(mutation); - generation.fetch_add(1, std::memory_order_release); + publishChanges(state->changed); if (const auto callback = invalidator.load(std::memory_order_acquire)) { for (const auto& [address, bytes] : state->changed) callback(address, bytes); } @@ -80,12 +112,32 @@ std::uint64_t GuestAllocationsGeneration_nid_postfix() { return generation.load(std::memory_order_acquire); } +std::uint64_t GuestAllocationsValidateMapping_nid_no_patch(std::uintptr_t address, std::size_t bytes, std::uint64_t since) { + if (since == 0 || bytes == 0 || bytes > std::numeric_limits::max() - address) return 0; + auto current = generation.load(std::memory_order_acquire); + if (since == current) return current; + auto& history = mappingHistory(); + std::lock_guard lock(history.mutex); + current = generation.load(std::memory_order_relaxed); + if (since > current || since < history.discardedThrough) return 0; + const auto end = address + bytes; + auto index = history.next; + for (std::size_t count = 0; count < history.changes.size(); ++count) { + index = (index + history.changes.size() - 1) % history.changes.size(); + const auto& change = history.changes[index]; + if (change.generation <= since) break; + if (change.bytes > std::numeric_limits::max() - change.address || (change.address < end && address < change.address + change.bytes)) return 0; + } + return current; +} + void GuestAllocationsSetInvalidator_nid_postfix(void (*callback)(std::uintptr_t, std::size_t)) { invalidator.store(callback, std::memory_order_release); } void GuestAllocationsInvalidate_nid_postfix(std::uintptr_t address, std::size_t bytes) { - generation.fetch_add(1, std::memory_order_release); + const std::pair range{address, bytes}; + publishChanges(std::span(&range, 1)); if (const auto callback = invalidator.load(std::memory_order_acquire)) callback(address, bytes); } @@ -94,7 +146,7 @@ void GuestAllocationsSetPinWaiter_nid_postfix(bool (*callback)()) { } #ifdef _WIN32 -void GuestAllocationsRegisterMainImage_nid_postfix(void*) { +void GuestAllocationsRegisterMainImage_nid_postfix(void* mutation) { auto& state = registry(); if (state.mainImageRegistered) return; const auto image = GetModuleHandleW(nullptr); @@ -121,6 +173,7 @@ void GuestAllocationsRegisterMainImage_nid_postfix(void*) { require(previous.address + previous.bytes <= cursor, "guest image overlaps a registered allocation"); } replacement.emplace(cursor, std::make_shared(Range{cursor, memory.RegionSize, readable, writable, cursor, memory.RegionSize, false})); + recordChange(mutation, reinterpret_cast(cursor), memory.RegionSize); registered = true; } cursor += memory.RegionSize; @@ -130,7 +183,7 @@ void GuestAllocationsRegisterMainImage_nid_postfix(void*) { state.mainImageRegistered = true; } #else -void GuestAllocationsRegisterMainImage_nid_postfix(void*) { +void GuestAllocationsRegisterMainImage_nid_postfix(void* mutation) { auto& state = registry(); if (state.mainImageRegistered) return; struct Page { @@ -169,6 +222,7 @@ void GuestAllocationsRegisterMainImage_nid_postfix(void*) { require(previous.address + previous.bytes <= address, "guest image overlaps a registered allocation"); } replacement.emplace(address, std::make_shared(Range{address, bytes, page->second.readable, page->second.writable, address, bytes, false})); + recordChange(mutation, reinterpret_cast(address), bytes); page = std::next(last); } state.ranges.swap(replacement); @@ -247,7 +301,11 @@ void GuestAllocationsRequireUnpinned_nid_postfix(void* mutation, const void* poi void GuestAllocationsRequireAvailable_nid_postfix(void*, const void* pointer, std::size_t bytes) { const auto address = reinterpret_cast(pointer); require(address != 0 && bytes != 0 && bytes <= std::numeric_limits::max() - address, "invalid fixed guest mapping"); - for (const auto& [base, range] : registry().ranges) { + const auto& ranges = registry().ranges; + auto it = ranges.upper_bound(address); + if (it != ranges.begin()) --it; + for (; it != ranges.end(); ++it) { + const auto& [base, range] = *it; if (base >= address + bytes) break; if (base + range->bytes > address) { char message[160]; @@ -272,7 +330,11 @@ bool GuestAllocationsCovers_nid_postfix(void*, const void* pointer, std::size_t require(address != 0 && bytes != 0 && bytes <= std::numeric_limits::max() - address, "invalid guest allocation range"); const auto end = address + bytes; auto cursor = address; - for (const auto& [base, range] : registry().ranges) { + const auto& ranges = registry().ranges; + auto it = ranges.upper_bound(address); + if (it != ranges.begin()) --it; + for (; it != ranges.end(); ++it) { + const auto& [base, range] = *it; const auto finish = base + range->bytes; if (finish <= cursor) continue; if (base > cursor || !range->releasable) return false; @@ -314,22 +376,37 @@ void GuestAllocationsRemove_nid_postfix(void* mutation, const void* pointer) { namespace { -std::map> replaceRange(const void* pointer, std::size_t bytes, bool remove, bool readable, bool writable) { +using RangeMap = std::map>; + +struct RangeReplacement { + RangeMap::iterator first; + RangeMap::iterator last; + RangeMap fragments; + + void Commit() { + auto& ranges = registry().ranges; + ranges.erase(first, last); + ranges.merge(fragments); + } +}; + +RangeReplacement replaceRange(const void* pointer, std::size_t bytes, bool remove, bool readable, bool writable) { const auto address = reinterpret_cast(pointer); require(bytes != 0 && bytes <= std::numeric_limits::max() - address, "invalid guest protection or unmap range"); require(!writable || readable, "writable guest allocation must be readable"); const auto end = address + bytes; - auto replacement = registry().ranges; + auto& ranges = registry().ranges; + auto first = ranges.upper_bound(address); + if (first != ranges.begin() && std::prev(first)->first + std::prev(first)->second->bytes > address) --first; + RangeReplacement replacement{first, ranges.lower_bound(end), {}}; auto cursor = address; - for (const auto& [base, entry] : registry().ranges) { + for (auto it = replacement.first; it != replacement.last; ++it) { + const auto& [base, entry] = *it; const auto& range = *entry; const auto finish = base + range.bytes; - if (finish <= address) continue; - if (base >= end) break; require(base <= cursor, "guest protection or unmap range has a hole"); - replacement.erase(base); const auto insert = [&](std::uint64_t first, std::uint64_t last, bool canRead, bool canWrite) { - if (first < last) replacement.emplace(first, std::make_shared(Range{first, static_cast(last - first), canRead, canWrite, range.allocationAddress, range.allocationBytes, range.releasable})); + if (first < last) replacement.fragments.emplace(first, std::make_shared(Range{first, static_cast(last - first), canRead, canWrite, range.allocationAddress, range.allocationBytes, range.releasable})); }; insert(base, std::max(base, address), range.readable, range.writable); if (!remove) insert(std::max(base, address), std::min(finish, end), readable, writable); @@ -347,7 +424,7 @@ void GuestAllocationsProtect_nid_postfix(void* mutation, const void* pointer, st recordChange(mutation, pointer, bytes); auto replacement = replaceRange(pointer, bytes, false, readable, writable); apply(); - registry().ranges.swap(replacement); + replacement.Commit(); } void GuestAllocationsUnmap_nid_postfix(void* mutation, const void* pointer, std::size_t bytes, const std::function& apply) { @@ -373,11 +450,17 @@ void GuestAllocationsUnmap_nid_postfix(void* mutation, const void* pointer, std: const auto pieceEnd = std::min(end, range.allocationAddress + range.allocationBytes); auto replacement = replaceRange(reinterpret_cast(cursor), pieceEnd - cursor, true, false, false); bool last = true; - for (const auto& [base, entry] : replacement) { - if (entry->allocationAddress == range.allocationAddress) last = false; + const auto& ranges = registry().ranges; + const auto allocationEnd = range.allocationAddress + range.allocationBytes; + for (auto it = ranges.lower_bound(range.allocationAddress); it != ranges.end() && it->first < allocationEnd; ++it) { + const auto& [base, entry] = *it; + if (entry->allocationAddress == range.allocationAddress && (base < cursor || base + entry->bytes > pieceEnd)) { + last = false; + break; + } } apply(reinterpret_cast(cursor), pieceEnd - cursor, reinterpret_cast(range.allocationAddress), last); - registry().ranges.swap(replacement); + replacement.Commit(); any = true; cursor = pieceEnd; } @@ -393,4 +476,15 @@ Lease GuestAllocationsAcquire_nid_postfix() { return result; } +Lease GuestAllocationsAcquireRange_nid_no_patch(std::uintptr_t address, std::size_t bytes) { + if (address == 0 || bytes == 0 || bytes > std::numeric_limits::max() - address) return {}; + std::lock_guard lock(registry().mutex); + const auto& ranges = registry().ranges; + const auto next = ranges.upper_bound(address); + if (next == ranges.begin()) return {}; + const auto& range = std::prev(next)->second; + if (!range->readable || address - range->address >= range->bytes || bytes > range->bytes - (address - range->address)) return {}; + return {range}; +} + } diff --git a/core/libs/tests/GuestMappingHistory.cpp b/core/libs/tests/GuestMappingHistory.cpp new file mode 100644 index 000000000000..4b23b0e8f6ba --- /dev/null +++ b/core/libs/tests/GuestMappingHistory.cpp @@ -0,0 +1,164 @@ +#include "prx/libc/include/GuestAllocations.hpp" +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using namespace GuestAllocations; + +namespace { + +void Require(bool value, std::source_location where = std::source_location::current()) { + if (value) return; + std::fprintf(stderr, "Mapping history check failed at %s:%u\n", where.file_name(), where.line()); + std::abort(); +} + +auto Generation() { return GuestAllocationsGeneration_nid_postfix(); } +auto Validate(std::uintptr_t address, std::size_t bytes, std::uint64_t since) { + return GuestAllocationsValidateMapping_nid_no_patch(address, bytes, since); +} + +void MappingChanges() { + constexpr std::uintptr_t base = 0x700000000; + constexpr std::size_t bytes = 65536; + auto* pointer = reinterpret_cast(base); + const auto initial = Generation(); + { + Mutation mutation; + mutation.Add(pointer, bytes, true, true); + } + Require(Validate(base, bytes, initial) == 0); + const auto mapped = Generation(); + Require(Validate(base, bytes, mapped) == mapped); + Require(Validate(base - 1, 1, initial) == mapped); + Require(Validate(base + bytes, 1, initial) == mapped); + Require(Validate(base - 1, 2, initial) == 0); + Require(Validate(base + bytes - 1, 2, initial) == 0); + { + Mutation mutation; + mutation.Protect(reinterpret_cast(base + 4096), 4096, true, false, [] {}); + } + Require(Validate(base, 4096, mapped) == Generation()); + Require(Validate(base + 4096, 1, mapped) == 0); + Require(Validate(base, bytes, mapped) == 0); + const auto beforeUnmap = Generation(); + { + Mutation mutation; + mutation.Unmap(reinterpret_cast(base + 8192), 4096, [](const void*, std::size_t, const void*, bool) {}); + } + Require(Validate(base, 8192, beforeUnmap) == Generation()); + Require(Validate(base + 8192, 1, beforeUnmap) == 0); + const auto protectedAt = Generation(); + { + Mutation mutation; + } + Require(Validate(base, bytes, protectedAt) == Generation()); + GuestAllocationsInvalidate_nid_postfix(base + 3 * bytes, bytes); + Require(Validate(base, bytes, protectedAt) == Generation()); + GuestAllocationsInvalidate_nid_postfix(base + bytes - 1, 1); + Require(Validate(base, bytes, protectedAt) == 0); + const auto beforeReplace = Generation(); + { + Mutation mutation; + mutation.Remove(pointer); + mutation.Add(pointer, bytes, true, true); + } + Require(Validate(base, bytes, beforeReplace) == 0); + const auto beforeRemove = Generation(); + { + Mutation mutation; + mutation.Remove(pointer); + } + Require(Validate(base, bytes, beforeRemove) == 0); + Require(Validate(base, bytes, 0) == 0); + Require(Validate(base, 0, Generation()) == 0); + Require(Validate(std::numeric_limits::max(), 2, Generation()) == 0); + Require(Validate(base, bytes, Generation() + 1) == 0); +} + +void HistoryOverflow() { + constexpr std::uintptr_t base = 0x710000000; + const auto before = Generation(); + for (unsigned i = 0; i < 2048; ++i) GuestAllocationsInvalidate_nid_postfix(base, 1); + Require(Validate(base + 1, 1, before) == 0); + const auto recent = Generation(); + GuestAllocationsInvalidate_nid_postfix(base, 1); + Require(Validate(base + 1, 1, recent) == Generation()); + Require(Validate(base, 1, recent) == 0); + const auto batch = Generation(); + { + Mutation mutation; + for (unsigned i = 0; i < 2048; ++i) mutation.Add(reinterpret_cast(base + i * 4096), 4096, true, true); + } + Require(Validate(base, 1, batch) == 0); + Require(Validate(base + 2047 * 4096, 1, batch) == 0); + Require(Validate(base, 2048 * 4096, Generation()) == Generation()); + { + Mutation mutation; + for (unsigned i = 0; i < 2048; ++i) mutation.Remove(reinterpret_cast(base + i * 4096)); + } +} + +void ReferenceHistory() { + struct Change { std::uint64_t generation; std::uintptr_t begin; std::size_t bytes; }; + std::vector changes; + std::mt19937 random(0x72c94); + constexpr std::uintptr_t base = 0x720000000; + for (unsigned i = 0; i < 12000; ++i) { + const auto address = base + random() % 1048576; + const auto bytes = 1 + random() % 16384; + GuestAllocationsInvalidate_nid_postfix(address, bytes); + changes.push_back({Generation(), address, bytes}); + for (unsigned query = 0; query < 8; ++query) { + const auto index = changes.size() - 1 - random() % std::min(changes.size(), 64); + const auto since = changes[index].generation; + const auto begin = base + random() % 1048576; + const auto size = 1 + random() % 32768; + bool unchanged = true; + for (auto j = index + 1; j < changes.size(); ++j) { + const auto& change = changes[j]; + if (change.begin < begin + size && begin < change.begin + change.bytes) unchanged = false; + } + Require(Validate(begin, size, since) == (unchanged ? Generation() : 0)); + } + } +} + +void ConcurrentChanges() { + constexpr std::size_t workers = 8; + std::barrier gate(static_cast(workers)); + std::array threads; + const auto initial = Generation(); + constexpr std::uintptr_t base = 0x730000000; + for (std::size_t worker = 0; worker < workers; ++worker) { + threads[worker] = std::thread([&, worker] { + for (unsigned pass = 0; pass < 200; ++pass) { + const auto since = Generation(); + gate.arrive_and_wait(); + GuestAllocationsInvalidate_nid_postfix(base + worker * 4096, 4096); + gate.arrive_and_wait(); + Require(Validate(base + worker * 4096, 4096, since) == 0); + Require(Validate(base + workers * 4096, 4096, since) != 0); + gate.arrive_and_wait(); + } + }); + } + for (auto& thread : threads) thread.join(); + Require(Generation() - initial == workers * 200); +} + +} + +int main() { + MappingChanges(); + HistoryOverflow(); + ReferenceHistory(); + ConcurrentChanges(); + std::puts("Mapping history preserves range identity, boundaries, replacement, overflow and concurrent publication"); +}