Merge pull request #178 from oneandonlydean/fix/agc-label-waits-after-submission

fix(agc): satisfy label waits from stores made after their submission
This commit is contained in:
boykopovar
2026-10-01 10:50:47 +03:00
committed by GitHub
4 changed files with 208 additions and 14 deletions
@@ -95,6 +95,7 @@ bool WaitSatisfiedUnchecked(std::span<const std::uint32_t> packet);
// Whether a WAIT_REG_MEM's compare holds for `value` (the 4 or 8 bytes a label the recorder still
// holds will store), without reading memory.
bool WaitComparesValue(std::span<const std::uint32_t> packet, std::uint64_t value);
std::size_t WaitAwaitedBytes(std::span<const std::uint32_t> packet);
// A label write (RELEASE_MEM with a data select, WRITE_DATA to memory): the destination and the
// bytes it stores, so the write can be recorded on the GPU behind the work it signals. Packets
// without a memory destination decode to nothing. No allocation per label (tens of thousands per
@@ -203,6 +203,8 @@ struct Submission {
// Record-order stamp (Driver::eventSerial) taken when the game submitted: a WAIT_REG_MEM of this
// submission trusts only labels the recorder noted with a newer stamp (see Recorder::NoteLabel).
std::uint64_t received = 0;
std::vector<std::uint64_t> labelWrites;
std::set<std::size_t> heldAtSubmit;
std::chrono::steady_clock::time_point enqueuedAt{};
const std::uint32_t* rewindTail = nullptr;
std::size_t rewindWords = 0;
@@ -510,6 +512,7 @@ private:
stopping = true;
for (auto& [queue, worker] : workers) {
worker.pending.clear();
worker.unfinishedWrites.clear();
worker.queued.store(0, std::memory_order_release);
}
}
@@ -591,6 +594,7 @@ public:
require(wait != nullptr, "video output returned a null rendering wait");
submission.renderingWaits.emplace(cursor, std::move(wait));
}
noteHeldAtSubmit(submission, cursor);
if (words[0] == FlipPacketHeader) {
const auto output = outputs.find(words[1]);
require(output != outputs.end(), "flip references an unregistered video output");
@@ -740,6 +744,7 @@ public:
for (const auto& [offset, flip] : item.flips) flip->Fail(failure);
}
worker.pending.clear();
worker.unfinishedWrites.clear();
worker.queued.store(0, std::memory_order_release);
}
}
@@ -941,6 +946,7 @@ private:
std::deque<Submission> pending;
// pending.size(), readable without `mutex` (the worker's submission-end decision).
std::atomic<std::uint64_t> queued{0};
std::unordered_map<std::uint64_t, std::uint32_t> unfinishedWrites;
std::thread thread;
};
std::map<std::uint32_t, QueueWorker> workers;
@@ -1584,6 +1590,44 @@ private:
std::map<std::uint32_t, QueueState> queues;
std::map<std::uint32_t, std::shared_ptr<IVideoOutput>> outputs;
DevicePointer device;
struct LabelStore {
std::uint64_t stamp = 0;
std::uint32_t value = 0;
};
static constexpr std::size_t LabelStoreHistory = 4;
std::mutex labelStoresMutex;
std::unordered_map<std::uint64_t, std::array<LabelStore, LabelStoreHistory>> labelStores;
void noteLabelStore(std::uint64_t address, std::span<const std::byte> bytes, std::uint64_t stamp) {
if (bytes.empty() || bytes.size() > 64 || bytes.size() % 4 != 0 || address % 4 != 0) return;
std::lock_guard lock(labelStoresMutex);
for (std::size_t offset = 0; offset < bytes.size(); offset += 4) {
auto& history = labelStores[address + offset];
std::shift_right(history.begin(), history.end(), 1);
history[0].stamp = stamp;
std::memcpy(&history[0].value, bytes.data() + offset, 4);
}
}
bool storedSince(std::span<const std::uint32_t> packet, std::uint64_t address, std::size_t bytes, std::uint64_t received) {
std::lock_guard lock(labelStoresMutex);
const auto low = labelStores.find(address);
if (low == labelStores.end()) return false;
const auto high = bytes == 8 ? labelStores.find(address + 4) : labelStores.end();
if (bytes == 8 && high == labelStores.end()) return false;
for (const auto& store : low->second) {
if (store.stamp <= received) continue;
std::uint64_t value = store.value;
if (bytes == 8) {
const auto upper = std::find_if(high->second.begin(), high->second.end(), [&](const LabelStore& other) { return other.stamp == store.stamp; });
if (upper == high->second.end()) continue;
value |= static_cast<std::uint64_t>(upper->value) << 32u;
}
if (Pm4::WaitComparesValue(packet, value)) return true;
}
return false;
}
std::vector<std::shared_ptr<VulkanDevice>> replacedDevices;
std::stop_token shutdownToken = LibcShutdownToken_nid_postfix();
DeviceUseGate deviceReplacement;
@@ -1604,10 +1648,47 @@ private:
return worker;
}
void noteHeldAtSubmit(Submission& submission, std::size_t cursor) {
const auto packet = std::span<const std::uint32_t>(submission.commands).subspan(cursor, std::min<std::size_t>(Pm4::PacketWords(submission.commands[cursor]), submission.commands.size() - cursor));
const auto opcode = (packet[0] >> 8u) & 0xffu;
if ((packet[0] >> 30u) != 3u) return;
if (opcode == 0x49 || opcode == 0x37) {
if (const auto label = Pm4::DecodeLabelWrite(packet)) {
const auto bytes = label->Bytes();
if (label->address % 4 == 0 && bytes.size() <= 64) {
for (std::size_t offset = 0; offset < bytes.size(); offset += 4) submission.labelWrites.push_back(label->address + offset);
}
}
return;
}
if ((opcode != 0x3c && opcode != 0x93) || packet.size() < 7 || ((packet[1] >> 4u) & 3u) != 1u) return;
const auto address = packet[2] | (static_cast<std::uint64_t>(packet[3]) << 32u);
const std::size_t bytes = Pm4::WaitAwaitedBytes(packet);
if (address % 4 != 0 || !GuestMemory::Accessible(reinterpret_cast<const void*>(address), bytes)) return;
const auto worker = workers.find(submission.queue);
for (std::size_t offset = 0; offset < bytes; offset += 4) {
const auto dword = address + offset;
if (std::find(submission.labelWrites.begin(), submission.labelWrites.end(), dword) != submission.labelWrites.end()) return;
if (worker != workers.end() && worker->second.unfinishedWrites.contains(dword)) return;
}
std::uint64_t value = *reinterpret_cast<const volatile std::uint32_t*>(address);
if (bytes == 8) value |= static_cast<std::uint64_t>(*reinterpret_cast<const volatile std::uint32_t*>(address + 4)) << 32u;
if (Pm4::WaitComparesValue(packet, value)) submission.heldAtSubmit.insert(cursor);
}
static void forgetUnfinishedWrites(QueueWorker& worker, const Submission& submission) {
for (const auto dword : submission.labelWrites) {
const auto found = worker.unfinishedWrites.find(dword);
if (found == worker.unfinishedWrites.end()) continue;
if (--found->second == 0) worker.unfinishedWrites.erase(found);
}
}
// Caller holds `mutex`.
void enqueue(Submission submission) {
const auto queue = submission.queue;
auto& worker = workers[queue];
for (const auto dword : submission.labelWrites) ++worker.unfinishedWrites[dword];
worker.pending.push_back(std::move(submission));
worker.queued.fetch_add(1, std::memory_order_acq_rel);
if (!worker.thread.joinable()) worker.thread = std::thread([this, queue] { run(queue); });
@@ -5178,12 +5259,15 @@ private:
bool first = true;
for (const auto& label : labels) {
const auto bytes = std::span<const std::byte>(label.bytes).first(label.size);
const int reason = localDevice != nullptr ? localDevice->WriteLabelOnGpu(label.address, bytes, ++eventSerial, queue, first) : 4;
const auto stamp = ++eventSerial;
const int reason = localDevice != nullptr ? localDevice->WriteLabelOnGpu(label.address, bytes, stamp, queue, first) : 4;
first = false;
countLabelOutcome(reason);
if (reason == 0 || reason == 5 || reason == 6) continue;
if (reason != 1 && localDevice != nullptr) localDevice->WaitIdle();
GuestMemory::Write(label.address, bytes, 4);
if (reason != 0 && reason != 5 && reason != 6) {
if (reason != 1 && localDevice != nullptr) localDevice->WaitIdle();
GuestMemory::Write(label.address, bytes, 4);
}
noteLabelStore(label.address, bytes, stamp);
}
++labelGroups;
static const bool profile = std::getenv("APS5_PROFILE_DRAW") != nullptr;
@@ -5448,7 +5532,7 @@ private:
}
// WAIT_REG_MEM: another queue or the CPU produces the value; the other queues run on their own threads.
void waitMemory(std::span<const std::uint32_t> packet, std::uint32_t queue, const PacketHistory& context, std::uint64_t received) {
void waitMemory(std::span<const std::uint32_t> packet, std::uint32_t queue, const PacketHistory& context, std::uint64_t received, bool heldAtSubmit) {
// The timeout counts from the last sign of GPU progress: while any queue is executing packets,
// the producer may still be on its way (shader compiles alone take hundreds of milliseconds).
auto start = std::chrono::steady_clock::now();
@@ -5456,9 +5540,8 @@ private:
// Names this worker's thread in the [lock] GpuMutex wait report.
GuestMemory::TagGpuLockThread(queue);
auto& outcomes = waitOutcomes();
const bool wide = ((packet[0] >> 8u) & 0xffu) == 0x93u;
const std::uint64_t awaited = packet[2] | (static_cast<std::uint64_t>(packet[3]) << 32u);
const std::size_t awaitedBytes = wide ? 8 : 4;
const std::size_t awaitedBytes = Pm4::WaitAwaitedBytes(packet);
static const bool traceGpu = std::getenv("APS5_TRACE_GPU") != nullptr;
if (traceGpu) std::fprintf(stderr, "[gpu] %.1f queue 0x%x waits 0x%llx == 0x%x (now 0x%x)\n", TraceMs(), queue, static_cast<unsigned long long>(packet[2] | (static_cast<std::uint64_t>(packet[3]) << 32u)), packet[4],
*reinterpret_cast<const volatile std::uint32_t*>(packet[2] | (static_cast<std::uint64_t>(packet[3]) << 32u)));
@@ -5487,6 +5570,7 @@ private:
++outcomes.atEntry;
return;
}
if (heldAtSubmit || storedSince(packet, awaited, awaitedBytes, received)) return;
// Debug aids: APS5_NO_LABEL_SHORTCUT=1 never satisfies a wait from the pending-label table;
// APS5_NO_WAIT_OVERLAP_SUBMIT=1 submits the open batch at every wait, as before, instead of
// only when it writes the awaited range.
@@ -5732,6 +5816,7 @@ private:
bool spinning = pauseSpin;
std::uint32_t polls = 0;
while (!Pm4::WaitSatisfiedUnchecked(packet)) {
if (storedSince(packet, awaited, awaitedBytes, received)) return;
++polls;
if (spinning) {
_mm_pause();
@@ -5757,9 +5842,12 @@ private:
static std::uint64_t timeouts = 0;
if (++timeouts % 20 == 0) std::fprintf(stderr, "[gpu] %llu GPU waits have timed out\n", static_cast<unsigned long long>(timeouts));
if (!reported.insert(packet[2] | (static_cast<std::uint64_t>(packet[3]) << 32u)).second) return;
std::fprintf(stderr, "[gpu] queue 0x%x WAIT_REG_MEM at 0x%llx timed out after %dms (function %u ref 0x%x mask 0x%x value 0x%x)\n", queue,
static_cast<unsigned long long>(packet[2] | (static_cast<std::uint64_t>(packet[3]) << 32u)), WaitTimeoutMs(), packet[1] & 7u, packet[4], packet[5],
*reinterpret_cast<const volatile std::uint32_t*>(packet[2] | (static_cast<std::uint64_t>(packet[3]) << 32u)));
const bool wide = ((packet[0] >> 8u) & 0xffu) == 0x93u;
const std::uint64_t reference = wide ? packet[4] | (static_cast<std::uint64_t>(packet[5]) << 32u) : packet[4];
const std::uint64_t mask = wide ? packet[6] | (static_cast<std::uint64_t>(packet[7]) << 32u) : packet[5];
const std::uint64_t current = wide ? *reinterpret_cast<const volatile std::uint64_t*>(awaited) : *reinterpret_cast<const volatile std::uint32_t*>(awaited);
std::fprintf(stderr, "[gpu] queue 0x%x WAIT_REG_MEM%s at 0x%llx timed out after %dms (function %u ref 0x%llx mask 0x%llx value 0x%llx)\n", queue, wide ? "_64" : "",
static_cast<unsigned long long>(awaited), WaitTimeoutMs(), packet[1] & 7u, static_cast<unsigned long long>(reference), static_cast<unsigned long long>(mask), static_cast<unsigned long long>(current));
const auto address = packet[2] | (static_cast<std::uint64_t>(packet[3]) << 32u);
for (const auto& record : writeHistory()) {
if (record.length != 0 && record.target <= address && address < record.target + std::max<std::uint64_t>(record.length, 4))
@@ -6008,7 +6096,8 @@ private:
// submission the game made before this point. Without a device (reason 4)
// the packet drains nothing and Pm4::Execute stores it, as before.
recordDeferredLabels(localDevice.get(), submission.queue);
const auto reason = localDevice != nullptr ? localDevice->WriteLabelOnGpu(label->address, bytes, ++eventSerial, submission.queue) : 4;
const auto stamp = ++eventSerial;
const auto reason = localDevice != nullptr ? localDevice->WriteLabelOnGpu(label->address, bytes, stamp, submission.queue) : 4;
wroteOnGpu = reason == 0 || reason == 5 || reason == 6;
if (reason == 1) {
// Idle recorder: stored here, still under the mutex, as
@@ -6018,6 +6107,7 @@ private:
GuestMemory::Write(label->address, bytes, 4);
wroteOnGpu = true;
}
if (wroteOnGpu) noteLabelStore(label->address, bytes, stamp);
Graphics::Recorder::CloseLabelGroup(GuestMemory::TrackerGeneration());
countLabelOutcome(reason);
++immediateLabels;
@@ -6064,7 +6154,9 @@ private:
// Earlier labels of this queue go first (queue order); the stamp is taken
// under the mutex like a label's.
recordDeferredLabels(localDevice.get(), submission.queue);
const auto reason = localDevice != nullptr ? localDevice->WriteLabelOnGpu(store->address, bytes, ++eventSerial, submission.queue) : 4;
const auto stamp = ++eventSerial;
const auto reason = localDevice != nullptr ? localDevice->WriteLabelOnGpu(store->address, bytes, stamp, submission.queue) : 4;
if (reason == 0 || reason == 1 || reason == 5 || reason == 6) noteLabelStore(store->address, bytes, stamp);
if (reason == 0 || reason == 5 || reason == 6) {
if (reason == 0) ++storesOnGpu;
else ++storesBehindCompletions;
@@ -6204,7 +6296,7 @@ private:
} else if (opcode == 0x3c || opcode == 0x93) {
static const bool traceGpu = std::getenv("APS5_TRACE_GPU") != nullptr;
const auto waitStart = std::chrono::steady_clock::now();
timed(&WorkerProfile::waitMs, [&] { waitMemory(packet, submission.queue, recent, submission.received); });
timed(&WorkerProfile::waitMs, [&] { waitMemory(packet, submission.queue, recent, submission.received, submission.heldAtSubmit.contains(cursor)); });
if (traceGpu && std::chrono::steady_clock::now() - waitStart > std::chrono::milliseconds(200)) {
// List the rest of the submission to show what the stalled queue would have done next.
for (std::size_t next = cursor + count, shown = 0; next < submission.commands.size() && shown < 48; ++shown) {
@@ -6275,7 +6367,12 @@ private:
} else if (sampleDump) {
dumpSampleCounters(packet[2] | (static_cast<std::uint64_t>(packet[3]) << 32u));
} else if (opcode != 0x42 && opcode != 0x46 && opcode != 0x58) {
if (!wroteOnGpu) Pm4::Execute(packet, queue);
if (!wroteOnGpu) {
Pm4::Execute(packet, queue);
if (opcode == 0x49 || opcode == 0x37) {
if (const auto label = Pm4::DecodeLabelWrite(packet)) noteLabelStore(label->address, label->Bytes(), ++eventSerial);
}
}
if (endOfPipeInterrupt) AgcDriverDeliverEopInterrupt(submission.queue);
}
if (drawPacket) Graphics::Recorder::CountRecordedWork();
@@ -6395,6 +6492,7 @@ private:
std::lock_guard lock(mutex);
rethrowFailure();
markCompleted(submission.serial);
forgetUnfinishedWrites(workers.at(id), submission);
// Only WaitIdle waits for a completion (idle workers wait for work, notified at
// its enqueue): the notify is skipped while nobody is in it.
notify = idleWaiters != 0;
@@ -457,6 +457,11 @@ bool WaitComparesValue(std::span<const std::uint32_t> packet, std::uint64_t valu
return waitCompares(packet, wide, value);
}
std::size_t WaitAwaitedBytes(std::span<const std::uint32_t> packet) {
const bool wide = ((packet[0] >> 8u) & 0xffu) == 0x93u;
return wide && (packet.size() < 8 || packet[7] != 0) ? 8 : 4;
}
std::optional<LabelWrite> DecodeLabelWrite(std::span<const std::uint32_t> packet) {
const auto opcode = (packet[0] >> 8u) & 0xffu;
if (opcode == 0x49 && packet.size() >= 7) {
@@ -7,6 +7,8 @@
#include "prx/libSceAgcDriver/Eq/include/Event.hpp"
#include "prx/libkernel/Equeue/Equeue.hpp"
#include <array>
#include <atomic>
#include <chrono>
#include <cstdio>
#include <limits>
#include <stdexcept>
@@ -184,6 +186,91 @@ void testEndOfPipeInterrupts() {
check(sceKernelDeleteEqueue(eq) == 0, "event queue deletion failed");
}
std::array<std::uint32_t, 5> writeData(volatile std::uint32_t* address, std::uint32_t value) {
const auto target = reinterpret_cast<std::uintptr_t>(address);
return {0xc0033700, 0x00100200, static_cast<std::uint32_t>(target), static_cast<std::uint32_t>(static_cast<std::uint64_t>(target) >> 32u), value};
}
std::array<std::uint32_t, 7> waitEqual(volatile std::uint32_t* address, std::uint32_t value) {
const auto target = reinterpret_cast<std::uintptr_t>(address);
return {0xc0053c00, 0x13, static_cast<std::uint32_t>(target), static_cast<std::uint32_t>(static_cast<std::uint64_t>(target) >> 32u), value, 0xffffffffu, 0x19};
}
std::array<std::uint32_t, 9> waitEqual64(volatile std::uint32_t* address, std::uint64_t value, std::uint64_t mask) {
const auto target = reinterpret_cast<std::uintptr_t>(address);
return {0xc0079300, 0x13, static_cast<std::uint32_t>(target), static_cast<std::uint32_t>(static_cast<std::uint64_t>(target) >> 32u), static_cast<std::uint32_t>(value), static_cast<std::uint32_t>(value >> 32u), static_cast<std::uint32_t>(mask), static_cast<std::uint32_t>(mask >> 32u), 0x19};
}
void submit(std::uint32_t queue, const std::vector<std::uint32_t>& words) {
Packet packet{const_cast<std::uint32_t*>(words.data()), static_cast<std::uint32_t>(words.size()), 0, {}};
check((queue == 0 ? sceAgcDriverSubmitDcb(&packet) : sceAgcDriverSubmitAcb(queue, &packet)) == 0, "label submit failed");
}
std::chrono::milliseconds waitFor(volatile std::uint32_t* address, std::uint32_t value, const char* message) {
const auto start = std::chrono::steady_clock::now();
while (*address != value) {
check(std::chrono::steady_clock::now() - start < std::chrono::seconds(10), message);
std::this_thread::sleep_for(std::chrono::microseconds(100));
}
return std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now() - start);
}
template<std::size_t... N>
std::vector<std::uint32_t> commands(const std::array<std::uint32_t, N>&... packets) {
std::vector<std::uint32_t> words;
(words.insert(words.end(), packets.begin(), packets.end()), ...);
return words;
}
void testLabelStoredSinceSubmission() {
alignas(64) static volatile std::uint32_t gate = 0, label = 0, done = 0, late = 0;
submit(0x20, commands(waitEqual(&gate, 1), waitEqual(&label, 1), writeData(&done, 1)));
submit(0, commands(writeData(&label, 1)));
waitFor(&label, 1, "producer label never landed");
label = 0;
gate = 1;
check(waitFor(&done, 1, "consumer never passed its waits") < std::chrono::milliseconds(500), "a label stored after the wait's submission did not satisfy it");
AgcDriverWaitIdle_nid_postfix();
submit(0x20, commands(waitEqual(&label, 1), writeData(&late, 1)));
check(waitFor(&late, 1, "consumer never passed its wait") >= std::chrono::milliseconds(900), "a label stored before the wait's submission satisfied it");
AgcDriverWaitIdle_nid_postfix();
}
void testWideLabelStoredSinceSubmission() {
alignas(64) static volatile std::uint32_t gate = 0, done = 0, late = 0;
alignas(64) static volatile std::uint32_t label[2] = {0, 0x5eed};
submit(0x20, commands(waitEqual(&gate, 1), waitEqual64(label, 1, 0xffffffffu), writeData(&done, 1)));
submit(0, commands(writeData(label, 1)));
waitFor(label, 1, "producer label never landed");
label[0] = 0;
gate = 1;
check(waitFor(&done, 1, "consumer never passed its waits") < std::chrono::milliseconds(500), "a 32-bit label stored after a low-dword 64-bit wait's submission did not satisfy it");
AgcDriverWaitIdle_nid_postfix();
gate = 0;
submit(0x20, commands(waitEqual(&gate, 1), waitEqual64(label, 1, ~0ull), writeData(&late, 1)));
submit(0, commands(writeData(label, 1)));
waitFor(label, 1, "producer label never landed");
label[0] = 0;
gate = 1;
check(waitFor(&late, 1, "consumer never passed its wait") >= std::chrono::milliseconds(900), "a 32-bit store satisfied a 64-bit wait whose high dword never matched");
AgcDriverWaitIdle_nid_postfix();
}
void testLabelHeldAtSubmission() {
alignas(64) static volatile std::uint32_t gate = 0, label = 1, done = 0, reset = 0;
submit(0x20, commands(waitEqual(&gate, 1), waitEqual(&label, 1), writeData(&done, 1)));
label = 0;
gate = 1;
check(waitFor(&done, 1, "consumer never passed its waits") < std::chrono::milliseconds(500), "a label held when the wait was submitted did not satisfy it");
AgcDriverWaitIdle_nid_postfix();
gate = 0;
label = 1;
submit(0x20, commands(waitEqual(&gate, 1), writeData(&label, 0), waitEqual(&label, 1), writeData(&reset, 1)));
gate = 1;
check(waitFor(&reset, 1, "consumer never passed its wait") >= std::chrono::milliseconds(900), "a label its own queue stored first counted as held at the submission");
AgcDriverWaitIdle_nid_postfix();
}
void testWorkerFailure() {
std::array<std::uint32_t, 5> words{0xc0031500, 1, 1, 1, 0x41};
Packet packet{words.data(), static_cast<std::uint32_t>(words.size()), 0, {}};
@@ -209,6 +296,9 @@ int main() {
testClearState();
testSubmissions();
testEndOfPipeInterrupts();
testLabelStoredSinceSubmission();
testLabelHeldAtSubmission();
testWideLabelStoredSinceSubmission();
testWorkerFailure();
check(expectFailure([] { LibcRunShutdown_nid_postfix(); }).find("required shader register") != std::string::npos, "shutdown lost worker failure");
std::puts("AGC driver submit tests passed");