Skip to content
This repository was archived by the owner on Nov 16, 2026. It is now read-only.
Draft
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
7 changes: 4 additions & 3 deletions include/rex/graphics/command_processor.h
Original file line number Diff line number Diff line change
Expand Up @@ -84,8 +84,8 @@ class CommandProcessor {
CommandProcessor(GraphicsSystem* graphics_system, system::KernelState* kernel_state);
virtual ~CommandProcessor();

uint32_t counter() const { return counter_; }
void increment_counter() { counter_++; }
uint32_t counter() const { return counter_.load(std::memory_order_relaxed); }
void increment_counter() { counter_.fetch_add(1, std::memory_order_relaxed); }

// What the GPU thread is doing right now, for hang reports. Any thread.
std::string DescribeState() const;
Expand Down Expand Up @@ -259,7 +259,8 @@ class CommandProcessor {
// MicroEngine binary from PM4_ME_INIT
std::vector<uint32_t> me_bin_;

uint32_t counter_ = 0;
// Both the vblank worker and command processor increment this counter.
std::atomic<uint32_t> counter_{0};

uint32_t primary_buffer_ptr_ = 0;
uint32_t primary_buffer_size_ = 0;
Expand Down
5 changes: 3 additions & 2 deletions include/rex/graphics/graphics_system.h
Original file line number Diff line number Diff line change
Expand Up @@ -118,8 +118,9 @@ class GraphicsSystem : public system::IGraphicsSystem {
std::unique_ptr<::rex::ui::GraphicsProvider> provider_;
bool provider_supports_presentation_ = false;

uint32_t interrupt_callback_ = 0;
uint32_t interrupt_callback_data_ = 0;
// Publish callback address and its user data together. Interrupts may run on
// the vblank/GPU workers while the guest replaces this pair.
std::atomic<uint64_t> interrupt_callback_state_{0};

std::atomic<bool> vsync_worker_running_;
system::object_ref<system::XHostThread> vsync_worker_thread_;
Expand Down
166 changes: 153 additions & 13 deletions src/core/timer_queue.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,10 @@
*/

#include <algorithm>
#include <condition_variable>
#include <cstdlib>
#include <forward_list>
#include <mutex>

#include <disruptorplus/multi_threaded_claim_strategy.hpp>
#include <disruptorplus/ring_buffer.hpp>
Expand All @@ -27,6 +30,121 @@ namespace rex::thread {

using WaitItem = TimerQueueWaitItem;

// Snapshot the opt-in before starting this queue's thread. Blocking preserves
// deadlines, but OS wakeup jitter can differ from the default phased spin wait.
// Keep this private so timer and runtime ABI layouts do not change.
class TimerWaitStrategy {
public:
// Closure is distinct from a timeout or a published sequence. In particular,
// waking a stopped consumer must never make an uninitialized ring slot valid.
struct Stopped {};

TimerWaitStrategy() : blocking_(std::getenv("REX_TIMER_WAIT_BLOCKING") != nullptr) {}

bool stopped() const { return stopped_.load(std::memory_order_acquire); }

void Stop() {
// Use the publication handshake for closure too, so stop cannot be lost
// between a blocking wait's predicate check and release of the mutex.
std::lock_guard lock(mutex_);
stopped_.store(true, std::memory_order_release);
cv_.notify_all();
}

dp::sequence_t wait_until_published(
dp::sequence_t sequence, size_t count,
const std::atomic<dp::sequence_t>* const sequences[]) {
if (!blocking_) {
ThrowIfStopped();
dp::spin_wait spinner;
auto result = dp::minimum_sequence_after(sequence, count, sequences);
while (dp::difference(result, sequence) < 0) {
ThrowIfStopped();
spinner.spin_once();
result = dp::minimum_sequence_after(sequence, count, sequences);
}
ThrowIfStopped();
return result;
}
dp::sequence_t result;
std::unique_lock lock(mutex_);
cv_.wait(lock, [&] {
result = dp::minimum_sequence_after(sequence, count, sequences);
return stopped() || dp::difference(result, sequence) >= 0;
});
ThrowIfStopped();
return result;
}

template <typename Rep, typename Period>
dp::sequence_t wait_until_published(
dp::sequence_t sequence, size_t count,
const std::atomic<dp::sequence_t>* const sequences[],
const std::chrono::duration<Rep, Period>& timeout) {
if (!blocking_) {
return wait_until_published(sequence, count, sequences,
std::chrono::high_resolution_clock::now() + timeout);
}
return wait_until_published(sequence, count, sequences,
std::chrono::steady_clock::now() + timeout);
}

template <typename Clock, typename Duration>
dp::sequence_t wait_until_published(
dp::sequence_t sequence, size_t count,
const std::atomic<dp::sequence_t>* const sequences[],
const std::chrono::time_point<Clock, Duration>& deadline) {
if (!blocking_) {
ThrowIfStopped();
dp::spin_wait spinner;
auto result = dp::minimum_sequence_after(sequence, count, sequences);
while (dp::difference(result, sequence) < 0) {
ThrowIfStopped();
if (spinner.next_spin_will_yield() && deadline < Clock::now()) return result;
spinner.spin_once();
result = dp::minimum_sequence_after(sequence, count, sequences);
}
ThrowIfStopped();
return result;
}
dp::sequence_t result;
std::unique_lock lock(mutex_);
const auto ready = [&] {
result = dp::minimum_sequence_after(sequence, count, sequences);
return stopped() || dp::difference(result, sequence) >= 0;
};
// The empty queue has no deadline. Avoid converting time_point::max() to
// a platform timeout, which may overflow and turn an idle wait into a poll.
if (deadline == std::chrono::time_point<Clock, Duration>::max()) {
cv_.wait(lock, ready);
} else {
cv_.wait_until(lock, deadline, ready);
}
ThrowIfStopped();
return result;
}

void signal_all_when_blocking() {
if (!blocking_) {
return;
}
// Publishers store their sequence before entering this lock. Taking the
// same lock as the predicate prevents a lost wake between check and wait.
std::lock_guard lock(mutex_);
cv_.notify_all();
}

private:
void ThrowIfStopped() const {
if (stopped()) throw Stopped{};
}

const bool blocking_;
std::atomic<bool> stopped_{false};
std::mutex mutex_;
std::condition_variable cv_;
};

class TimerQueue {
public:
using clock = WaitItem::clock;
Expand All @@ -45,12 +163,9 @@ class TimerQueue {

~TimerQueue() {
dispatch_thread_.request_stop();

// Kick dispatch thread to check stop token
auto wait_item = std::make_shared<WaitItem>(nullptr, nullptr, this, clock::time_point::min(),
clock::duration::zero());
wait_item->Disarm();
QueueTimer(std::move(wait_item));
// Shutdown cannot depend on spare capacity in the producer ring. An active
// callback completes normally; an idle consumer leaves its publication wait.
wait_strategy_.Stop();

// std::jthread auto-joins on destruction
}
Expand All @@ -65,11 +180,20 @@ class TimerQueue {
set_current_thread_name("rex::thread::TimerQueue");

while (!stop_token.stop_requested()) {
// Callback ingress belongs only to this consumer. Defer it to the next
// iteration, rather than waiting for this same thread to free ring space.
deferred_wait_items_.sort(comp);
wait_queue_.merge(deferred_wait_items_, comp);
{
// Consume new wait items and add them to sorted wait queue
dp::sequence_t available = claim_strategy_.wait_until_published(
next_sequence, next_sequence - 1,
wait_queue_.empty() ? clock::time_point::max() : wait_queue_.front()->due_);
dp::sequence_t available;
try {
available = claim_strategy_.wait_until_published(
next_sequence, next_sequence - 1,
wait_queue_.empty() ? clock::time_point::max() : wait_queue_.front()->due_);
} catch (const TimerWaitStrategy::Stopped&) {
break;
}

// Check for timeout
if (available != next_sequence - 1) {
Expand Down Expand Up @@ -124,12 +248,27 @@ class TimerQueue {
}

std::weak_ptr<WaitItem> QueueTimer(std::shared_ptr<WaitItem> wait_item) {
// The queue is permanently closed during teardown. Callers must still keep
// the queue alive for the whole call; closure does not extend its lifetime.
if (wait_strategy_.stopped()) return {};
auto wait_item_weak = std::weak_ptr<WaitItem>(wait_item);

// Mitigate callback flooding
wait_item->due_ = std::max(clock::now() - wait_item->interval_, wait_item->due_);

auto sequence = claim_strategy_.claim_one();
if (std::this_thread::get_id() == dispatch_thread_id()) {
deferred_wait_items_.push_front(std::move(wait_item));
return wait_item_weak;
}

dp::sequence_t sequence;
try {
sequence = claim_strategy_.claim_one();
} catch (const TimerWaitStrategy::Stopped&) {
// A stopped claim is never published. The ring is permanently closed,
// so the reserved sequence cannot leave a hole in a running queue.
return {};
}
buffer_[sequence] = std::move(wait_item);
claim_strategy_.publish(sequence);

Expand All @@ -142,13 +281,14 @@ class TimerQueue {
// This ring buffer will be used to introduce timers queued by the public API
static constexpr size_t kWaitCount = 512;
dp::ring_buffer<std::shared_ptr<WaitItem>> buffer_;
dp::spin_wait_strategy wait_strategy_;
dp::multi_threaded_claim_strategy<dp::spin_wait_strategy> claim_strategy_;
dp::sequence_barrier<dp::spin_wait_strategy> consumed_;
TimerWaitStrategy wait_strategy_;
dp::multi_threaded_claim_strategy<TimerWaitStrategy> claim_strategy_;
dp::sequence_barrier<TimerWaitStrategy> consumed_;

// This is a _sorted_ (ascending due_) list of active timers managed by a
// dedicated thread
std::forward_list<std::shared_ptr<WaitItem>> wait_queue_;
std::forward_list<std::shared_ptr<WaitItem>> deferred_wait_items_;
std::jthread dispatch_thread_;
};

Expand Down
4 changes: 2 additions & 2 deletions src/graphics/command_processor.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1086,7 +1086,7 @@ bool CommandProcessor::ExecutePacketType3_XE_SWAP(memory::RingBuffer* reader, ui
// rather than delaying the frame itself.
LimitFramerate();

++counter_;
increment_counter();
return true;
}

Expand Down Expand Up @@ -1404,7 +1404,7 @@ bool CommandProcessor::ExecutePacketType3_EVENT_WRITE_SHD(memory::RingBuffer* re
uint32_t data_value;
if ((initiator >> 31) & 0x1) {
// Write counter (GPU vblank counter?).
data_value = counter_;
data_value = counter();
} else {
// Write value.
data_value = value;
Expand Down
26 changes: 24 additions & 2 deletions src/graphics/d3d12/pipeline_cache.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -356,6 +356,16 @@ void PipelineCache::InitializeShaderStorage(const std::filesystem::path& cache_r
shader_storage_file_header.magic == shader_storage_magic &&
rex::byte_swap(shader_storage_file_header.version_swapped) == ShaderStoredHeader::kVersion) {
uint64_t shader_storage_valid_bytes = sizeof(shader_storage_file_header);
const bool shader_storage_end_seeked =
rex::filesystem::Seek(shader_storage_file_, 0, SEEK_END);
const int64_t shader_storage_file_end =
shader_storage_end_seeked ? rex::filesystem::Tell(shader_storage_file_) : -1;
const bool shader_storage_size_valid =
shader_storage_file_end >= int64_t(shader_storage_valid_bytes) &&
rex::filesystem::Seek(shader_storage_file_, int64_t(shader_storage_valid_bytes), SEEK_SET);
if (!shader_storage_size_valid) {
REXGPU_WARN("Shader storage: unable to determine readable file size; skipping cache load");
}
// Load and translate shaders written by previous Xenia executions until the
// end of the file or until a corrupted one is detected.
ShaderStoredHeader shader_header;
Expand Down Expand Up @@ -447,11 +457,21 @@ void PipelineCache::InitializeShaderStorage(const std::filesystem::path& cache_r
};
std::vector<std::unique_ptr<rex::thread::Thread>> shader_translation_threads;

while (true) {
while (shader_storage_size_valid) {
if (!fread(&shader_header, sizeof(shader_header), 1, shader_storage_file_)) {
break;
}
size_t ucode_byte_count = shader_header.ucode_dword_count * sizeof(uint32_t);
const uint64_t payload_offset = shader_storage_valid_bytes + sizeof(shader_header);
// A corrupt 31-bit count must not allocate gigabytes before fread can
// discover the truncated payload. Validate against this open file first.
if (payload_offset > uint64_t(shader_storage_file_end) ||
shader_header.ucode_dword_count >
(uint64_t(shader_storage_file_end) - payload_offset) / sizeof(uint32_t)) {
REXGPU_WARN("Shader storage: truncated payload at byte {}; discarding corrupt suffix",
shader_storage_valid_bytes);
break;
}
ucode_dwords.resize(shader_header.ucode_dword_count);
if (shader_header.ucode_dword_count &&
!fread(ucode_dwords.data(), ucode_byte_count, 1, shader_storage_file_)) {
Expand Down Expand Up @@ -520,7 +540,9 @@ void PipelineCache::InitializeShaderStorage(const std::filesystem::path& cache_r
REXGPU_INFO("Translated {} shaders from the storage in {} milliseconds", shaders_translated,
(rex::chrono::Clock::QueryHostTickCount() - shader_storage_initialization_start) *
1000 / rex::chrono::Clock::QueryHostTickFrequency());
rex::filesystem::TruncateStdioFile(shader_storage_file_, shader_storage_valid_bytes);
if (shader_storage_size_valid) {
rex::filesystem::TruncateStdioFile(shader_storage_file_, shader_storage_valid_bytes);
}
} else {
rex::filesystem::TruncateStdioFile(shader_storage_file_, 0);
shader_storage_file_header.magic = shader_storage_magic;
Expand Down
Loading