fix(agc): satisfy label waits from stores made after their submission

A title may reclaim a label (reset it to 0) as soon as the submission
that released it is done, trusting every queue waiting on it to have
passed its WAIT_REG_MEM within microseconds, as the CP polls from the
moment it reaches the wait. A worker that reaches a later wait of the
same submission long after (it records and compiles in between) found
the reset label and timed out.

A memory wait now also passes when
- a label store the driver committed (recorded on the GPU, as a
  completion action, or on the CPU) after the wait's submission gave the
  awaited bytes a value the wait accepts (the last four stores per dword,
  with their eventSerial stamps). Such a store belongs to this use of the
  label or a later one, since the title reset it before submitting.
- the awaited bytes held such a value when the game submitted, and no
  earlier packet of the queue (in the submission, or one still queued or
  running) stores to them.

A store made before the submission never satisfies a wait.
This commit is contained in:
Dean Galvin
2026-10-01 00:30:52 +13:00
parent a67b644ff6
commit 7df4ce4007
2 changed files with 169 additions and 9 deletions
@@ -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 = opcode == 0x93 ? 8 : 4;
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); });
@@ -5160,12 +5241,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;
@@ -5430,7 +5514,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();
@@ -5469,6 +5553,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.
@@ -5714,6 +5799,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();
@@ -5990,7 +6076,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
@@ -6000,6 +6087,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;
@@ -6046,7 +6134,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;
@@ -6186,7 +6276,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) {
@@ -6257,7 +6347,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();
@@ -6377,6 +6472,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;
@@ -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,66 @@ 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};
}
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 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 +271,8 @@ int main() {
testClearState();
testSubmissions();
testEndOfPipeInterrupts();
testLabelStoredSinceSubmission();
testLabelHeldAtSubmission();
testWorkerFailure();
check(expectFailure([] { LibcRunShutdown_nid_postfix(); }).find("required shader register") != std::string::npos, "shutdown lost worker failure");
std::puts("AGC driver submit tests passed");