XGameRuntime: fix XAsync/XTaskQueue termination deadlocks, double-cleanup race, and XErrorReport lock #97

Merged
raylitebull merged 1 commit from upstream-pr/98 into main 2026-11-23 11:25:27 +00:00
raylitebull commented 2026-11-23 11:11:10 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by raylitebull on 2026-11-23T11:11:10Z.


Summary

Fixes deterministic deadlocks, a double-cleanup race, completion-ordering races, and port-state bugs in crates/xcl/src/hle/xgameruntime/{xasync.rs, taskqueue.rs, api.rs}:

  1. Atomic termination check on submission (taskqueue.rs, xasync.rs):

    • Replaced separate terminated/inflight atomics with state: Mutex<QueueState { terminated: bool, inflight: [usize; 2] }> + idle_cv: Condvar under strict lock order p.items / timer -> q.state.
    • submit_now / submit_delayed now atomically reject submissions once terminated without incrementing inflight or enqueuing work.
    • Fixes a deterministic deadlock where XTaskQueueTerminate(q, true, ...) on a MODE_MANUAL completion port drained PORT_COMPLETION, then ran canceled delayed async work callbacks whose XAsyncComplete re-submitted onto PORT_COMPLETION and left inflight > 0 forever. Also stops callbacks from running on already-terminated MODE_THREAD_POOL queues.
  2. XTaskQueueDispatch(q, port, INFINITE) wakeup on termination (taskqueue.rs):

    • dispatch() checks !q.is_terminated() in its wait loop and returns false once empty and terminated.
    • XTaskQueueTerminate calls cv.notify_all() on both ports so threads blocked on INFINITE wake promptly.
  3. XAsyncComplete publish ordering, single-consumer OP_CLEANUP, and payload reclaim (xasync.rs):

    • Replaced {done, cleaned} booleans with an explicit Phase state machine (Pending -> Completing -> Done -> Consuming -> Consumed).
    • XAsyncComplete transitions Pending -> Completing, runs OP_CLEANUP unlocked when result_size == 0, writes FLAG_DONE and removes s if cleaned, and only then publishes Done/Consumed before signaling waiters or submitting completion_cb (preventing premature destruction of stack XAsyncBlocks or FLAG_CONSUMED clobbering).
    • XAsyncGetResult atomically claims Done -> Consuming under lock so concurrent XAsyncGetResult calls cannot run OP_CLEANUP twice (eliminating double-free UB; losing callers receive E_ILLEGAL_METHOD_CALL).
    • begin_with_fixups reclaims Box<Payload> when XAsyncBegin returns an error.
  4. Per-port XTaskQueueIsEmpty & XTaskQueueRegisterWaiter bounds/termination (taskqueue.rs):

    • Tracked inflight per port ([usize; 2]) so XTaskQueueIsEmpty(q, PORT_COMPLETION) does not report false when only PORT_WORK has items.
    • XTaskQueueRegisterWaiter validates port <= 1 (E_INVALIDARG instead of panicking inside waiter_fired) and waiter_fired ignores terminated queues.
  5. XErrorReport mutex deadlock (api.rs):

    • Copied the (callback, context) tuple out of ERROR_CB before invoking it so re-entrant XErrorSetCallback / XErrorReport calls do not self-deadlock.

Testing

All race and deadlock fixes include multi-iteration stress tests with barriers and short timeouts (would hang/fail on origin/main, pass deterministically here):

  • terminate_manual_completion_port_with_delayed_async_does_not_deadlock (50 iterations, 2s watchdog + already-terminated pool check)
  • complete_finishes_cleanup_and_header_before_publishing_done (50 iterations zero-payload + 50 iterations FLAG_CONSUMED preservation)
  • concurrent_get_result_runs_cleanup_exactly_once (100 iterations × 4 threads on counting provider + 50 iterations × 4 threads on begin_with)
  • complete_synchronously_inside_begin_zero_and_nonempty_payload (sync XAsyncComplete inside XAsyncOp::Begin on MODE_IMMEDIATE queue)
  • begin_with_fixups_drops_payload_on_begin_failure
  • dispatch_infinite_wakes_and_returns_false_on_terminate (50 iterations across both ports, 2s timeout)
  • is_empty_tracks_work_and_completion_ports_independently
  • register_waiter_validates_port_and_ignores_terminated_queue
  • xerror_report_allows_reentrant_set_callback_and_report (2s timeout)

Verified after rebasing onto origin/main (60599a9): cargo build --workspace and cargo test --workspace -- --test-threads=4 pass with 0 failures and 0 new warnings.

<!-- greyfinch-sync:ivall/xcl:issue:5451942894 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/98). Originally posted by [raylitebull](https://github.com/raylitebull) on 2026-11-23T11:11:10Z. --- ## Summary Fixes deterministic deadlocks, a double-cleanup race, completion-ordering races, and port-state bugs in `crates/xcl/src/hle/xgameruntime/{xasync.rs, taskqueue.rs, api.rs}`: 1. **Atomic termination check on submission (`taskqueue.rs`, `xasync.rs`):** - Replaced separate `terminated`/`inflight` atomics with `state: Mutex<QueueState { terminated: bool, inflight: [usize; 2] }>` + `idle_cv: Condvar` under strict lock order `p.items` / `timer` -> `q.state`. - `submit_now` / `submit_delayed` now atomically reject submissions once terminated without incrementing `inflight` or enqueuing work. - Fixes a deterministic deadlock where `XTaskQueueTerminate(q, true, ...)` on a `MODE_MANUAL` completion port drained `PORT_COMPLETION`, then ran canceled delayed async work callbacks whose `XAsyncComplete` re-submitted onto `PORT_COMPLETION` and left `inflight > 0` forever. Also stops callbacks from running on already-terminated `MODE_THREAD_POOL` queues. 2. **`XTaskQueueDispatch(q, port, INFINITE)` wakeup on termination (`taskqueue.rs`):** - `dispatch()` checks `!q.is_terminated()` in its wait loop and returns `false` once empty and terminated. - `XTaskQueueTerminate` calls `cv.notify_all()` on both ports so threads blocked on `INFINITE` wake promptly. 3. **`XAsyncComplete` publish ordering, single-consumer `OP_CLEANUP`, and payload reclaim (`xasync.rs`):** - Replaced `{done, cleaned}` booleans with an explicit `Phase` state machine (`Pending -> Completing -> Done -> Consuming -> Consumed`). - `XAsyncComplete` transitions `Pending -> Completing`, runs `OP_CLEANUP` unlocked when `result_size == 0`, writes `FLAG_DONE` and removes `s` if cleaned, and only then publishes `Done`/`Consumed` before signaling waiters or submitting `completion_cb` (preventing premature destruction of stack `XAsyncBlock`s or `FLAG_CONSUMED` clobbering). - `XAsyncGetResult` atomically claims `Done -> Consuming` under lock so concurrent `XAsyncGetResult` calls cannot run `OP_CLEANUP` twice (eliminating double-free UB; losing callers receive `E_ILLEGAL_METHOD_CALL`). - `begin_with_fixups` reclaims `Box<Payload>` when `XAsyncBegin` returns an error. 4. **Per-port `XTaskQueueIsEmpty` & `XTaskQueueRegisterWaiter` bounds/termination (`taskqueue.rs`):** - Tracked `inflight` per port (`[usize; 2]`) so `XTaskQueueIsEmpty(q, PORT_COMPLETION)` does not report `false` when only `PORT_WORK` has items. - `XTaskQueueRegisterWaiter` validates `port <= 1` (`E_INVALIDARG` instead of panicking inside `waiter_fired`) and `waiter_fired` ignores terminated queues. 5. **`XErrorReport` mutex deadlock (`api.rs`):** - Copied the `(callback, context)` tuple out of `ERROR_CB` before invoking it so re-entrant `XErrorSetCallback` / `XErrorReport` calls do not self-deadlock. ## Testing All race and deadlock fixes include multi-iteration stress tests with barriers and short timeouts (would hang/fail on `origin/main`, pass deterministically here): - `terminate_manual_completion_port_with_delayed_async_does_not_deadlock` (50 iterations, 2s watchdog + already-terminated pool check) - `complete_finishes_cleanup_and_header_before_publishing_done` (50 iterations zero-payload + 50 iterations `FLAG_CONSUMED` preservation) - `concurrent_get_result_runs_cleanup_exactly_once` (100 iterations × 4 threads on counting provider + 50 iterations × 4 threads on `begin_with`) - `complete_synchronously_inside_begin_zero_and_nonempty_payload` (sync `XAsyncComplete` inside `XAsyncOp::Begin` on `MODE_IMMEDIATE` queue) - `begin_with_fixups_drops_payload_on_begin_failure` - `dispatch_infinite_wakes_and_returns_false_on_terminate` (50 iterations across both ports, 2s timeout) - `is_empty_tracks_work_and_completion_ports_independently` - `register_waiter_validates_port_and_ignores_terminated_queue` - `xerror_report_allows_reentrant_set_callback_and_report` (2s timeout) Verified after rebasing onto `origin/main` (`60599a9`): `cargo build --workspace` and `cargo test --workspace -- --test-threads=4` pass with 0 failures and 0 new warnings.
upstream-sync closed this pull request 2026-11-24 06:57:09 +00:00
ivall commented 2026-11-24 07:00:28 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by ivall on 2026-11-23T11:25:43Z.


Merged together with #95–#102 and checked on Windows 11 with an RX 9070: cargo test --workspace green with the retail samples (shader pack, console DLLs, texture archive), lib tests also with XCL_SPLIT_WAVE64=1; XDefiant (title screen, a scripted A reaches its "Xbox network unavailable" dialog), Unicorn Overlord and Minecraft run. Thanks!

<!-- greyfinch-sync:ivall/xcl:comment:7099631010 --> Imported from [ivall/xcl](https://github.com/ivall/xcl/pull/98#issuecomment-7099631010). Originally posted by [ivall](https://github.com/ivall) on 2026-11-23T11:25:43Z. --- Merged together with #95–#102 and checked on Windows 11 with an RX 9070: `cargo test --workspace` green with the retail samples (shader pack, console DLLs, texture archive), lib tests also with `XCL_SPLIT_WAVE64=1`; XDefiant (title screen, a scripted A reaches its "Xbox network unavailable" dialog), Unicorn Overlord and Minecraft run. Thanks!
Sign in to join this conversation.
No reviewers
No labels
No milestone
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Reference
xcl-dev/xcl!97
No description provided.