Files
betterxen/shims/xgameruntime/task_queue.cpp
T
ates caf043e5d4 WIP experiment: translated console pipelines, runtime gaps, CLZERO loop
Local experiment on worktree-ffx-loader-experiment, to be split before review:
- d3d12_xs: opt-in translation of deserialized console VS/PS pairs
  (BX_CONSOLE_SHADER_CACHE), descriptor markers resolved at submission,
  constants copied to an upload ring, derived pipelines inherit the
  translation, GetFrameStatisticsX from the GDK structures.
- scripts/console-shader/translate.py: straight-line gfx1030 to HLSL.
- xgameruntime: XUserDuplicateHandle, XAsyncRun, XTaskQueue duplicate,
  port and composite, XGameSaveGetContainerInfo and
  XGameSaveEnumerateContainerInfoByName.
- AcpHal: commands are acknowledged (message queue, notification word),
  following VIctory's audio module (GPL-3.0-or-later).
- runtime_veh: a CLZERO loop completes in one trap; a storage write fault
  on unmapped memory is retried for up to two seconds.
- VEH diagnostics files taken from the #635/#659 branches.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-29 08:28:55 +03:00

407 lines
15 KiB
C++

#include "task_queue.h"
#include <algorithm>
#include <chrono>
#include <condition_variable>
#include <mutex>
#include <new>
#include <unordered_map>
namespace bx::gdk {
class Queue : public std::enable_shared_from_this<Queue> {
public:
struct Lane {
Queue* owner;
DispatchMode mode;
PTP_WORK worker = nullptr;
std::mutex mutex;
std::condition_variable ready;
std::unique_ptr<Task> first;
Task* last = nullptr;
// Keep the queue alive while Windows has outstanding worker callbacks.
QueueRef worker_owner;
size_t workers = 0;
bool serial_running = false;
bool closed = false;
Lane(Queue* owner, DispatchMode mode) : owner(owner), mode(mode) {}
~Lane() {
if (worker) CloseThreadpoolWork(worker);
while (first) pop();
}
HRESULT initialize() {
if (mode == DispatchMode::parallel || mode == DispatchMode::serialized) {
worker = CreateThreadpoolWork(run_worker, this, nullptr);
if (!worker) return HRESULT_FROM_WIN32(GetLastError());
}
return S_OK;
}
bool push(std::unique_ptr<Task> task, bool is_completion) {
std::unique_lock lock(mutex);
if (closed && !is_completion) return false;
if (mode == DispatchMode::immediate || (closed && mode == DispatchMode::manual)) {
// No lane storage on these paths, so the submitting thread waits out
// the remainder of the delay and then runs the callback itself.
const uint64_t due_ms = task->due_ms;
lock.unlock();
wait_until(due_ms);
task->run(owner->shared_from_this());
return true;
}
auto* tail = task.get();
(last ? last->next : first) = std::move(task);
last = tail;
ready.notify_one();
if (mode == DispatchMode::parallel) schedule();
schedule_serial();
return true;
}
void schedule() {
if (workers++ == 0) worker_owner = owner->shared_from_this();
SubmitThreadpoolWork(worker);
}
bool due() const { return first && (first->due_ms == 0 || GetTickCount64() >= first->due_ms); }
// Sleep out the remainder of a GetTickCount64 deadline. Saturating: the
// deadline can pass between the check and the clock read, and an unsigned
// subtraction there would wrap to ~584 million years.
static void wait_until(uint64_t due_ms) {
for (;;) {
const uint64_t now = GetTickCount64();
if (due_ms == 0 || now >= due_ms) return;
const uint64_t left = due_ms - now;
// INFINITE would mean "wait forever", so a `left` of exactly
// 0xFFFFFFFF would never wake to re-check the deadline.
Sleep(finite_sleep_chunk_ms(left));
}
}
// FIFO: the head holds the lane until it is due, so a later task never
// overtakes a delayed one. Wait only until that deadline, never spin.
std::chrono::steady_clock::time_point head_due() const {
const uint64_t now = GetTickCount64();
const uint64_t left = first->due_ms > now ? first->due_ms - now : 0;
return std::chrono::steady_clock::now() + std::chrono::milliseconds(left);
}
void schedule_serial() {
if (mode == DispatchMode::serialized && first && !serial_running && workers == 0) {
schedule();
}
}
std::unique_ptr<Task> pop() {
auto task = std::move(first);
first = std::move(task->next);
if (!first) last = nullptr;
return task;
}
void close(const QueueRef& queue) {
std::unique_lock lock(mutex);
closed = true;
ready.notify_all();
if (mode != DispatchMode::manual) return;
while (first) {
auto task = pop();
lock.unlock();
task->cancel(queue);
lock.lock();
}
}
bool dispatch(uint32_t timeout) {
if (mode == DispatchMode::immediate) return false;
std::unique_lock lock(mutex);
const auto has_task = [this] { return closed || (due() && !serial_running); };
if (timeout == INFINITE) {
while (!has_task()) {
if (first && !serial_running) {
ready.wait_until(lock, head_due());
} else {
ready.wait(lock);
}
}
} else {
const auto deadline = std::chrono::steady_clock::now() + std::chrono::milliseconds(timeout);
while (!has_task()) {
if (std::chrono::steady_clock::now() >= deadline) return false;
auto wake = deadline;
if (first && !serial_running) {
wake = std::min(wake, head_due());
}
ready.wait_until(lock, wake);
}
}
if (closed) return false;
auto task = pop();
if (mode == DispatchMode::serialized) serial_running = true;
lock.unlock();
task->run(owner->shared_from_this());
if (mode == DispatchMode::serialized) {
lock.lock();
serial_running = false;
schedule_serial();
ready.notify_all();
}
return true;
}
static void CALLBACK run_worker(PTP_CALLBACK_INSTANCE, void* context, PTP_WORK) {
auto& lane = *static_cast<Lane*>(context);
QueueRef queue;
std::unique_lock lock(lane.mutex);
queue = lane.worker_owner;
while (lane.first && !lane.serial_running) {
// A delayed head must not run early. Wait on the condition variable
// until its deadline (or a push changes the head) instead of popping
// it, so FIFO order holds and nothing is dropped. Close drains what
// was already accepted, as it did before delays existed.
if (!lane.closed && !lane.due()) {
lane.ready.wait_until(lock, lane.head_due());
continue;
}
auto task = lane.pop();
const bool serial = lane.mode == DispatchMode::serialized;
lane.serial_running = serial;
lock.unlock();
task->run(queue);
lock.lock();
lane.serial_running = false;
if (!serial) break;
}
if (--lane.workers == 0) lane.worker_owner.reset();
}
};
Queue(DispatchMode work, DispatchMode completion) : lanes{{this, work}, {this, completion}} {}
Lane lanes[2];
// A composite queue (XTaskQueueCreateComposite) has no lanes of its own in use: each port
// forwards to a port of another queue.
QueueRef forward[2];
Port forward_port[2] = {Port::work, Port::completion};
};
// Follows composite forwarding to the queue and port that hold the lane.
static void resolve_lane(QueueRef& queue, Port& port) {
for (int depth = 0; depth < 8 && queue; ++depth) {
const auto index = static_cast<uint32_t>(port);
if (!queue->forward[index]) return;
const Port next_port = queue->forward_port[index];
queue = queue->forward[index];
port = next_port;
}
}
namespace {
std::mutex queues_mutex;
std::unordered_map<uintptr_t, QueueRef> handles;
uintptr_t next_handle = 1;
// XTaskQueuePortHandle values (even numbers, so they never collide with queue handles).
std::unordered_map<uintptr_t, std::pair<QueueRef, Port>> port_handles;
uintptr_t next_port_handle = 2;
QueueRef process_queue;
HRESULT make_queue(DispatchMode work, DispatchMode completion, QueueRef& queue) {
auto candidate = std::make_shared<Queue>(work, completion);
for (auto& lane : candidate->lanes) {
const HRESULT hr = lane.initialize();
if (FAILED(hr)) return hr;
}
queue = std::move(candidate);
return S_OK;
}
void* add_handle(const QueueRef& queue) {
const auto id = next_handle;
next_handle += 2;
handles.emplace(id, queue);
return reinterpret_cast<void*>(id);
}
struct CallbackTask final : Task {
using Callback = void (CALLBACK*)(void*, bool);
Callback callback;
void* context;
CallbackTask(Callback callback, void* context) : callback(callback), context(context) {}
void run(const QueueRef&) override { callback(context, false); }
void cancel(const QueueRef&) override { callback(context, true); }
};
} // namespace
QueueRef acquire_queue(void* handle) {
std::lock_guard lock(queues_mutex);
if (!handle) {
try {
if (!process_queue) make_queue(DispatchMode::parallel, DispatchMode::parallel, process_queue);
} catch (const std::bad_alloc&) {
return {};
}
return process_queue;
}
const auto it = handles.find(reinterpret_cast<uintptr_t>(handle));
return it == handles.end() ? QueueRef{} : it->second;
}
bool submit(const QueueRef& queue, Port port, std::unique_ptr<Task> task, bool is_completion) {
QueueRef target = queue;
resolve_lane(target, port);
return target->lanes[static_cast<uint32_t>(port)].push(std::move(task), is_completion);
}
} // namespace bx::gdk
using namespace bx::gdk;
extern "C" {
HRESULT WINAPI XTaskQueueCreate(DispatchMode work, DispatchMode completion, void** out) {
if (!out) return E_POINTER;
*out = nullptr;
if (work > DispatchMode::immediate || completion > DispatchMode::immediate) return E_INVALIDARG;
try {
QueueRef queue;
const auto hr = make_queue(work, completion, queue);
if (FAILED(hr)) return hr;
std::lock_guard lock(queues_mutex);
*out = add_handle(queue);
return S_OK;
} catch (const std::bad_alloc&) {
return E_OUTOFMEMORY;
}
}
void WINAPI XTaskQueueCloseHandle(void* handle) {
QueueRef queue;
bool close_queue = false;
{
std::lock_guard lock(queues_mutex);
const auto it = handles.find(reinterpret_cast<uintptr_t>(handle));
if (it == handles.end()) return;
queue = std::move(it->second);
close_queue = queue != process_queue;
handles.erase(it);
// Duplicated handles share the queue: only the last close shuts its lanes down.
for (const auto& other : handles) {
if (other.second == queue) close_queue = false;
}
}
// The frozen ABI exposes no termination or duplicate-handle API. Drain manual
// completion callbacks on close and let accepted pool work finish normally.
if (close_queue) {
for (auto& lane : queue->lanes) lane.close(queue);
}
}
bool WINAPI XTaskQueueDispatch(void* handle, Port port, uint32_t timeout) {
if (!handle || port > Port::completion) return false;
auto queue = acquire_queue(handle);
if (!queue) return false;
resolve_lane(queue, port);
return queue->lanes[static_cast<uint32_t>(port)].dispatch(timeout);
}
// Not exported: reached through IXGameRuntimeCore (com_dispatch.cpp).
HRESULT WINAPI bx_xtq_duplicate_handle(void* handle, void** out) {
if (!out) return E_POINTER;
*out = nullptr;
const auto queue = acquire_queue(handle);
if (!queue) return E_HANDLE;
try {
std::lock_guard lock(queues_mutex);
*out = add_handle(queue);
return S_OK;
} catch (const std::bad_alloc&) {
return E_OUTOFMEMORY;
}
}
HRESULT WINAPI bx_xtq_get_port(void* handle, Port port, void** out) {
if (!out) return E_POINTER;
*out = nullptr;
if (port > Port::completion) return E_INVALIDARG;
const auto queue = acquire_queue(handle);
if (!queue) return E_HANDLE;
try {
std::lock_guard lock(queues_mutex);
const auto id = next_port_handle;
next_port_handle += 2;
port_handles.emplace(id, std::make_pair(queue, port));
*out = reinterpret_cast<void*>(id);
return S_OK;
} catch (const std::bad_alloc&) {
return E_OUTOFMEMORY;
}
}
HRESULT WINAPI bx_xtq_create_composite(void* work_port, void* completion_port, void** out) {
if (!out) return E_POINTER;
*out = nullptr;
try {
std::lock_guard lock(queues_mutex);
const auto work = port_handles.find(reinterpret_cast<uintptr_t>(work_port));
const auto completion = port_handles.find(reinterpret_cast<uintptr_t>(completion_port));
if (work == port_handles.end() || completion == port_handles.end()) return E_HANDLE;
// Immediate lanes: never used, every submit and dispatch is forwarded.
auto queue = std::make_shared<Queue>(DispatchMode::immediate, DispatchMode::immediate);
queue->forward[0] = work->second.first;
queue->forward_port[0] = work->second.second;
queue->forward[1] = completion->second.first;
queue->forward_port[1] = completion->second.second;
*out = add_handle(queue);
return S_OK;
} catch (const std::bad_alloc&) {
return E_OUTOFMEMORY;
}
}
HRESULT WINAPI XTaskQueueSubmitDelayedCallback(void* handle, Port port, uint32_t delay_ms, void* context,
CallbackTask::Callback callback);
HRESULT WINAPI XTaskQueueSubmitCallback(void* handle, Port port, void* context, CallbackTask::Callback callback) {
return XTaskQueueSubmitDelayedCallback(handle, port, 0, context, callback);
}
HRESULT WINAPI XTaskQueueSubmitDelayedCallback(void* handle, Port port, uint32_t delay_ms, void* context,
CallbackTask::Callback callback) {
if (!handle || port > Port::completion || !callback) return E_INVALIDARG;
const auto queue = acquire_queue(handle);
if (!queue) return E_HANDLE;
auto task = std::unique_ptr<Task>(new (std::nothrow) CallbackTask(callback, context));
if (!task) return E_OUTOFMEMORY;
// delay_ms == 0 is due now, which is the common case and matches the old
// immediate-submit behaviour. A nonzero delay is a GetTickCount64 deadline.
task->due_ms = delay_ms == 0 ? 0 : GetTickCount64() + delay_ms;
return submit(queue, port, std::move(task)) ? S_OK : E_HANDLE;
}
bool WINAPI XTaskQueueGetCurrentProcessTaskQueue(void** out) {
if (!out) return false;
*out = nullptr;
const auto queue = acquire_queue(nullptr);
if (!queue) return false;
try {
std::lock_guard lock(queues_mutex);
*out = add_handle(queue);
return true;
} catch (const std::bad_alloc&) {
return false;
}
}
} // extern "C"