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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions core/libs/prx/libSceAgcDriver/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
67 changes: 67 additions & 0 deletions core/libs/prx/libSceAgcDriver/Graphics/include/BufferCache.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
#ifndef CORE_LIBS_PRX_LIBSCEAGCDRIVER_GRAPHICS_INCLUDE_BUFFERCACHE_HPP
#define CORE_LIBS_PRX_LIBSCEAGCDRIVER_GRAPHICS_INCLUDE_BUFFERCACHE_HPP

#include <array>
#include <cstddef>
#include <cstdint>
#include <list>
#include <map>
#include <memory>
#include <tuple>

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> 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<std::uint64_t, Use, std::size_t>;
struct Entry {
std::uint64_t generation;
std::uint64_t mappingGeneration;
std::list<Key>::iterator recent;
Slice slice;
};
struct Pool {
std::list<Key> recency;
std::size_t bytes = 0;
};
std::map<Key, Entry> entries;
std::array<Pool, 2> pools;
Statistics stats;
void erase(std::map<Key, Entry>::iterator entry);
};

}

#endif
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
36 changes: 14 additions & 22 deletions core/libs/prx/libSceAgcDriver/Graphics/include/Recorder.hpp
Original file line number Diff line number Diff line change
@@ -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 <atomic>
#include <chrono>
Expand Down Expand Up @@ -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<Buffer> 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> buffer, SnapshotUse use = SnapshotUse::Storage, std::uint32_t derived = 0);
std::pair<std::shared_ptr<Buffer>, 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<Buffer> 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> buffer, SnapshotUse use = SnapshotUse::Storage, std::uint32_t derived = 0, std::size_t offset = 0);
void OnComplete(std::function<void()> 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);
Expand Down Expand Up @@ -496,6 +500,8 @@ class Recorder {
VkFence fence = VK_NULL_HANDLE;
std::vector<std::shared_ptr<void>> kept;
std::size_t keptBytes = 0;
std::shared_ptr<Buffer> drawUpload;
std::size_t drawUploadUsed = 0;
std::vector<std::function<void()>> completions;
std::vector<std::pair<std::uint64_t, std::uint64_t>> writes;
std::vector<std::uint64_t> writeNotes;
Expand Down Expand Up @@ -748,21 +754,7 @@ class Recorder {
std::array<Completed, CompletedRingSize> completed;
std::uint64_t newestSubmitted = 0;
std::chrono::steady_clock::time_point newestSubmittedAt{};
using DrawSnapshotKey = std::tuple<std::uint64_t, SnapshotUse, std::size_t>;
struct DrawSnapshot {
std::uint64_t generation;
std::uint64_t registryGeneration;
std::list<DrawSnapshotKey>::iterator recent;
std::shared_ptr<Buffer> buffer;
std::uint32_t derived;
};
struct DrawSnapshotPool {
std::list<DrawSnapshotKey> recency;
std::size_t bytes = 0;
};
std::map<DrawSnapshotKey, DrawSnapshot> drawSnapshots;
std::array<DrawSnapshotPool, 2> drawSnapshotPools;
void eraseDrawSnapshot(std::map<DrawSnapshotKey, DrawSnapshot>::iterator entry);
BufferCache bufferCache;
};

}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,9 @@ class ShaderResources {
struct Snapshot {
std::uint64_t address;
std::shared_ptr<Buffer> buffer;
std::size_t offset = 0;
std::size_t size = 0;
std::span<std::byte> Bytes() const { return buffer->Bytes().subspan(offset, size); }
};
DescriptorCache* cache = nullptr;
DescriptorCache::SetAllocation allocation;
Expand Down Expand Up @@ -243,7 +246,7 @@ class ShaderResources {
std::uint64_t address;
std::size_t size;
bool guest;
std::unique_ptr<Buffer> buffer;
std::shared_ptr<Buffer> buffer;
ShaderRecompiler::DescriptorRole role = ShaderRecompiler::DescriptorRole::ShaderData;
// Guest buffers: whether the shader may store to the range (see addGuestBuffer).
bool written = true;
Expand All @@ -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<const std::uint32_t> pendingData;
std::span<std::byte> Bytes() const { return buffer->Bytes().subspan(bufferOffset, size); }
};
struct DataPatch {
std::size_t allocation;
Expand Down Expand Up @@ -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<Allocation> allocations;
std::vector<VkDescriptorPoolSize> descriptorSizes;
std::vector<VkDescriptorBufferInfo> descriptorBuffers;
std::vector<VkDescriptorImageInfo> descriptorImages;
std::vector<VkWriteDescriptorSet> 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;
Expand Down
65 changes: 65 additions & 0 deletions core/libs/prx/libSceAgcDriver/Graphics/src/BufferCache.cpp
Original file line number Diff line number Diff line change
@@ -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 <iterator>

namespace AgcDriver::Graphics {

namespace {
std::size_t poolIndex(BufferCache::Use use) {
return use == BufferCache::Use::Storage ? 0 : 1;
}
}

void BufferCache::erase(std::map<Key, Entry>::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;
}

}
6 changes: 3 additions & 3 deletions core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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<std::size_t>(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<unsigned long long>(begin), bytes);
continue;
Expand Down
35 changes: 30 additions & 5 deletions core/libs/prx/libSceAgcDriver/Graphics/src/GuestBufferMemory.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand All @@ -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<std::uint64_t>::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) {
Expand Down Expand Up @@ -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);
}
}
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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<std::size_t>(bytes))) {
if (auto* recorder = Recorder::Active()) {
const GuestMemory::ReadSiteScope site(GuestMemory::ReadSite::BufferUpload);
const auto slice = recorder->ReadBuffer(region.begin, static_cast<std::size_t>(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
Expand Down Expand Up @@ -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) {
Expand Down
Loading
Loading