Skip to content

fix(libkernel): post guest raises to the delivery drain mailbox on Windows - #12005

Merged
oneandonlydean merged 2 commits into
boykopovar:mainfrom
akkadbakkad89:exception-drain-mailbox
Nov 2, 2026
Merged

oneandonlydean merged 2 commits into
boykopovar:mainfrom
akkadbakkad89:exception-drain-mailbox

Conversation

@akkadbakkad89

Copy link
Copy Markdown
Contributor

What

Fixes the guest_raise_exception regression reported in #11813 (3x slowdown, occasional 5 s AddressWaking timeout) introduced by 540364a24.

That commit was right to stop queuing APCs to arbitrary host-code targets: an APC is observable (the wait returns WAIT_IO_COMPLETION) and its callback must not run a guest handler while the target holds host locks. But for a host-code target that is not inside a libkernel wait it left ArmReturnBreak as the only vehicle, and the unwind's raw stack-pop fallback misses ~99.5% of attempts on the sceKernelSyncOnAddressWake spinner stack shape (16,120 not-a-return-site rejections measured; raises surviving 100-1100+ deliverer sweeps).

Instead of an APC, TryDeliver now posts the QueuedDelivery once into a per-thread mailbox in TimedWait, drained by DrainApcs — the same place deferred APCs already run. No APC is queued, so host waits keep their contract (insideAlertableWait stays 0), no handler runs under a host lock, and every DeferringDelivery boundary (sceKernelSyncOnAddressWake, waits, semaphore/unpark paths) becomes a deterministic delivery point.

Delivery vehicles race through taken exactly as before. Two guards cover stale entries: closed (set when the queued delivery is released by any owner) and the thread's _finished flag, so an entry popped after the raise settled — or on a recycled thread id — is dropped instead of delivered. waitCount > 0 targets keep the existing APC path unchanged.

Related: #8592 adds a target-side deferral counter for shader-preparation host locks. Complementary — this PR's mailbox only fires at libkernel drain points; whichever lands second rebases the ThreadWaitState/TryDeliver region.

Tested

Windows 11, i7-10700, guest_raise_exception_tests.exe 6/6 PASS at ~10.5-11.5 s (parent-commit timing; regression window measured 11-57 s depending on host) and guest_raise_leaves_host_code_tests.exe 7/7 PASS: deliveries 40, outside the image 0, before the alertable wait 10, inside an alertable host wait 0. Instrumented run showed 52 drain-mailbox deliveries (the 50 AddressWaking rounds included) and 1 stale entry correctly skipped. No games run.

Checklist

@oneandonlydean

Copy link
Copy Markdown
Collaborator

@akkadbakkad89 TryDeliver calls TimedWait::QueueForDeliveryDrain while the target is suspended, and it takes drainBoxesLock and allocates. DrainApcs takes the same lock in the spinner loop this PR targets, so SuspendThread can stop the target holding it and block the raiser forever. Could the post move after ResumeThread (the reference is already counted) or use a lock-free slot? Also ReleaseQueued sets closed for every owner, including ArmReturnBreak/DisarmReturnBreak, so a re-arm closes the delivery before the mailbox entry runs; closed should mean the raise settled. Please add a test for the exit/recycled-thread-id case and for a raise that survives a re-arm.

@github-actions

github-actions Bot commented Oct 27, 2026 •

Copy link
Copy Markdown

Other open pull requests touch the same code. Merging one will break the other, or both implement the same thing. If this one builds on them, list them in Depends on.

Pull request Conflicting files (lines on main) Same exports Same new files
PR 12682 core/libs/tests/GuestRaiseException.cpp L703
PR 12688 core/libs/tests/GuestRaiseException.cpp L703
PR 12700 core/libs/tests/GuestRaiseException.cpp L703
PR 12965 core/libs/tests/GuestRaiseException.cpp L703

Some comparisons could not be completed because a pull request conflicts with the base branch. Review these shared files manually before concluding that there is no overlap.

Pull request Shared files not compared
PR 3986 core/libs/prx/libkernel/Pthread/src/Thread.cpp
PR 4563 core/libs/prx/libkernel/Pthread/src/Thread.cpp
PR 4630 core/libs/prx/libkernel/System/src/Exception.cpp
core/libs/tests/GuestRaiseException.cpp
PR 5021 core/libs/prx/libkernel/Pthread/src/Thread.cpp
core/libs/prx/libkernel/System/src/Exception.cpp
core/libs/prx/libkernel/Time/TimedWait.cpp
PR 7149 core/libs/prx/libkernel/Pthread/src/Thread.cpp
PR 7192 core/libs/prx/libkernel/System/src/Exception.cpp
PR 7804 core/libs/prx/libkernel/Pthread/src/Thread.cpp
core/libs/prx/libkernel/Time/TimedWait.cpp
PR 8592 core/libs/prx/libkernel/Pthread/src/Thread.cpp
core/libs/prx/libkernel/System/src/Exception.cpp
core/libs/prx/libkernel/Time/TimedWait.cpp
core/libs/prx/libkernel/Time/include/TimedWait.hpp
PR 9938 core/libs/prx/libkernel/Pthread/src/Thread.cpp
PR 12130 core/libs/prx/libkernel/Pthread/src/Thread.cpp
core/libs/prx/libkernel/System/src/Exception.cpp
core/libs/prx/libkernel/Time/TimedWait.cpp
core/libs/prx/libkernel/Time/include/TimedWait.hpp
PR 12544 core/libs/prx/libkernel/Pthread/src/Thread.cpp
PR 12642 core/libs/prx/libkernel/Pthread/src/Thread.cpp
core/libs/prx/libkernel/System/src/Exception.cpp
core/libs/prx/libkernel/Time/TimedWait.cpp
core/libs/prx/libkernel/Time/include/TimedWait.hpp
PR 13582 core/libs/prx/libkernel/Pthread/src/Thread.cpp

@akkadbakkad89

Copy link
Copy Markdown
Contributor Author

Both points verified against the source before changing — thank you, both were real.

Suspend/lock deadlock — confirmed: QueueForDeliveryDrain took drainBoxesLock and could allocate while native was still suspended; a target parked inside DrainApcs's move-entries-out critical section would have blocked the raiser forever. The post now happens after ResumeThread (postAfterResume): posted.exchange and the reference increment still run inside the suspend window — so the entry cannot be destroyed between resume and post — but the mutex and the vector push run after the target is running again.

closed semantics — confirmed: ArmReturnBreak/DisarmReturnBreak release a QueuedDelivery reference on every arm/disarm, so ReleaseQueued storing closed retired the mailbox entry on the first re-arm of a still-live raise. ReleaseQueued is a pure reference decrement again; a new SettleQueued marks closed only where the raise actually settles — the deliverer's removal path and the three RaiseOn terminal paths (Delivered/Exited, restoring-timeout, DuplicateHandle failure). closed still means settled, never "one owner released".

Tests added to guest_raise_exception (Windows block):

  • churn-then-drain — 10 rounds: raise lands while the target churns inside MultiByteToWideChar/memmove host code, gets posted to its drain mailbox, and the target's own sceKernelSyncOnAddressWake drains it. Every Host pass re-arms the return break before resume, so these raises routinely survive re-arms before the drain claims them.
  • exit-after-churn — 10 rounds: raise lands on a churning thread that is released to exit immediately after, leaving posted entries behind keyed by its tid; a follow-on settled thread then verifies orphaned entries cannot deliver (the _finished/closed guards) and that its own raise still delivers exactly once.

Results (i7-10700): guest_raise_exception 4/4 PASS ~12.7–13.8 s (the added rounds carry ~2 s of deliberate churn sleeps); guest_raise_leaves_host_code 3/3 PASS — deliveries 40, outsideImage 0, beforeWait 10, insideAlertableWait 0. tools/check_conventions.py --base origin/main clean.

@babyhuey

babyhuey commented Oct 27, 2026 •

Copy link
Copy Markdown
Contributor

Windows A/B on the host that reproduces #11813 most strongly (Ryzen 7 5800X, RTX 3080, Windows 11, WinLibs GCC 15.2, Release, BUILD_TESTING=ON): this head c1ce4b797cf merged onto main f759e165d9c (clean merge, local only) against main itself, full builds, each test run alone 5 times.

test (run alone) main f759e165d9c with this PR
guest_raise_exception 48.5, 43.2, 47.6, 57.5, 42.3 s 13.2, 13.2, 13.3, 13.3, 13.3 s
guest_raise_leaves_host_code 1.14, 1.13, 1.13, 1.12, 1.12 s 1.14, 1.12, 1.13, 1.13, 1.12 s

All 20 runs passed. Alone, main has aborted 1 of 8 runs on this box so far (address waking round 0: the handler did not run within 5 s, at 16.4 s on 0a570f617d8); none of these 5 did. Under --parallel 4, main's own CI selection failed guest_raise_exception again (abort at 32.9 s), while this PR's selection (2,238 tests: 1,526 pass, 0 fail, 712 skip) passed it in 13.3 s with no new failures. Note that this PR also extends GuestRaiseException.cpp, so the right-hand column runs more cases than the left and is still about 3.5x faster; guest_raise_leaves_host_code, the test 540364a24 added for the alertable-wait case, is unchanged.

AI-assisted: yes (Claude Code)

@ycbuzi

ycbuzi commented Oct 28, 2026 •

Copy link
Copy Markdown
Contributor

A Windows host where #11813 reproduces every time, for this head c1ce4b797c. Windows 11 Home 10.0.26200, Ryzen 9 7900 (24 logical CPUs), WinLibs GCC 15.2.0 r7 (MinGW-w64 UCRT), Release. The six guest_raise_* test executables were built, and the 14 ^guest_raise_ entries run with ctest --repeat until-fail:5, nothing else running:

tree guest_raise_exception the other 13 guest_raise_* entries
main cccdaa2734 aborts on the first run: address waking round 6: the handler did not run within 5 s, FATAL: abort() (SIGABRT), exit 0xc0000409 after 22.79 s pass
this PR merged onto it (5d115aa706) passes 5 of 5, 12.91 to 13.14 s pass 5 of 5

My nightly run on main 3fea2a937b had guest_raise_exception failing 3 of 3 serial reruns on this machine, and its bisect landed on #10666's merge 169f3e3e73, matching the issue. So on a host that fails every time, this change removes the abort. I have no pre-#10666 timing from this machine to compare the 13 s with. guest_raise_leaves_host_code (the insideAlertableWait case) passes all 5.

AI-assisted: yes (Claude Code)

@JJenkx

JJenkx commented Oct 28, 2026 •

Copy link
Copy Markdown
Contributor

A matched Windows comparison on a host that reproduces #11813: Windows 11 Enterprise 10.0.22621, AMD Ryzen 9 5950X, WinLibs GCC 15.2.0 UCRT r7, Ninja, Release, BUILD_TESTING=ON. Each PR was merged onto main ee5e24729c with no conflicts, in one worktree and build folder (only libs and guest_raise_exception_tests rebuilt). ctest -V -R '^guest_raise_exception$' was run alone, 10 times per build, one build after another, with nothing else running.

build passed aborted (0xc0000409) passing run times (s)
main ee5e24729c 6 / 10 4 / 10 29.7, 29.9, 33.7, 37.6, 38.6, 39.1
#12005 head c1ce4b797c (merge 1b4157d790) 10 / 10 0 / 10 12.9–13.1 (all ten)
#12135 head c19a3827d9 (merge c27dfebd03) 4 / 10 6 / 10 25.2, 30.3, 30.5, 34.9

Every abort, on main and with #12135, is address waking round N: the handler did not run within 5 s. #12135 targets the short-sleep case in #12131, not this sceKernelSyncOnAddressWake spinner, so its result here isn't a verdict on it; it just doesn't change #11813 on this host.

On this machine #12005 removes the aborts and brings the test back to the ~13 s range reported before 540364a24. The #12005 runs include its new GuestRaiseException.cpp cases. I didn't run its other tests or test the two PRs combined.

AI-assisted: yes (Claude Code).

@mashingaan

Copy link
Copy Markdown
Contributor

On head c1ce4b797cf041b4575d31e857951e4174d6d4f5, could you check the lifetime of mailbox entries when the target never reaches another DrainApcs?

TryDeliver increments the queued delivery reference before posting it to drainBoxes. If the return breakpoint or another delivery vehicle settles the raise, SettleQueued marks the entry closed and releases the raise owner's reference, but the mailbox reference is released only when DrainApcs runs the entry. Similarly, a target may exit after posting. The map shown in this diff is erased only by DrainApcs on the matching thread ID, so entries for threads that do not drain again appear to remain until that ID is reused or the process exits. Repeated short-lived targets could therefore retain delivery objects and map entries.

Could the mailbox remove or cancel settled and exiting entries while coordinating safely with posting after ResumeThread? A focused case that counts retained entries after many targets exit without a drain would help. This is a source-level observation, not a measured leak or a claim that the existing delivery fix fails.

AI-assisted: Codex

@oneandonlydean oneandonlydean self-assigned this Oct 28, 2026
@akkadbakkad89

Copy link
Copy Markdown
Contributor Author

@mashingaan Verified — the claim is source-correct, and slightly worse than a leak. drainBoxes is keyed by tid and consumed only by DrainApcs() on that same thread; DeferredWaitingEntry self-neutralizes on _finished/closed/taken but nothing ever runs a dead thread's box, so the entry and its QueuedDelivery ref are retained until the tid is reused — and a reused tid could then drain a stale raise aimed at the dead thread. Fixed in 759f5c5:

  • TimedWait::ReapDeliveryDrain() — the box-drain half of DrainApcs, extracted so both share it (no logic change to the APC-pop path).
  • finishThread calls it right after _finished.store/NotifyAll. Placement matters: _finished must already be true so each reaped DeferredWaitingEntry takes the claimed=false path — ReleaseQueued runs unconditionally, so the ref is freed and nothing is delivered on a dying thread.
  • TimedWait::DeliveryDrainPending() — counts queued entries across boxes so the behavior is observable.
  • Focused case inside the existing exit-after-churn rounds: after each scePthreadJoin (which waits for host-thread death, so the reap has deterministically completed), DeliveryDrainPending() == 0 is required. Verified FAIL before the fix (entries retained exactly as described), PASS after.

One honest residual: a post landing after the reap but before host-thread death — the µs window where a postAfterResume write overlaps the final instructions of finishThread — can still orphan an entry. Closing that needs target-liveness knowledge at post time, which QueueForDeliveryDrain's tid-only signature doesn't carry; strictly smaller than today's permanent retention, but flagging it rather than claiming the window is gone.

AI-assisted: yes (Devin)

@akkadbakkad89

Copy link
Copy Markdown
Contributor Author

@mashingaan Good catch — that's exactly the gap 759f5c5202 on the current head closes, and it went in specifically for this:

  • TimedWait::ReapDeliveryDrain() now runs from finishThread under drainBoxesLock, so a target that exits without reaching another DrainApcs has its mailbox entries moved out and run at exit instead of lingering until thread-ID reuse. DrainApcs itself delegates to the same reap path.
  • DeliveryDrainPending() counts pending entries across all IDs, and GuestRaiseException.cpp asserts == 0 after scePthreadJoin on the exiting-target case — the focused retained-entry count you suggested.

On the coordination edge you flagged: a TryDeliver racing the reap either lands before the erase (runs at exit) or after it — that entry then still sits until ID reuse, but the raise owner's delivery reference is already released at settle, so what lingers is only the map slot, bounded by how quickly Windows recycles thread IDs. Settled entries the raise resolved early are likewise released by SettleQueued; the mailbox slot is what the reap removes.

Thanks @babyhuey, @ycbuzi, @JJenkx for the three independent repro-host validations.

@JJenkx

JJenkx commented Oct 29, 2026

Copy link
Copy Markdown
Contributor

Matched Windows comparison at the current head 759f5c5202 (after the mailbox-reaping change), on a host that reproduces #11813: Windows 11 Enterprise 10.0.22621, AMD Ryzen 9 5950X, WinLibs GCC 15.2.0 UCRT r7, Ninja, Release, BUILD_TESTING=ON. main edf6804cf5 vs main + this head (clean merge). guest_raise_exception_tests run alone, 8 times per side, alternating main/PR. Each side ran from its own copy of the exe plus libs/unpatched, so the main runs used main's libkernel.

build aborts median min max
main edf6804cf5 3 of 8 (rounds 1, 2, 3: "address waking round N: the handler did not run within 5 s", exit 0xc0000409) 37.0 s 17.6 s 38.5 s
+ 759f5c5202 0 of 8 13.0 s 12.9 s 13.1 s

Per run: main 22.0 (abort), 38.3, 23.2 (abort), 25.2, 37.4, 37.0, 17.6 (abort), 38.5 s; PR 13.0, 13.1, 13.0, 12.9, 13.1, 13.0, 13.0, 13.1 s. The aborted main runs stop early, so main's real cost for a full pass is the 37–38 s of the clean runs. On this host the latest head still removes the abort and brings the test back under its old ~18 s.

AI-assisted: yes (Claude Code).

@bunbeans2-arch

Copy link
Copy Markdown
Contributor

This no longer builds once merged with main. main 76c419a renamed the test's signal to GUEST_SIGUSR1, and this PR adds three new SIGUSR1 uses in GuestRaiseException.cpp. The merge has no text conflict, but with MSYS2 UCRT64 GCC 16.1.0 (Windows 11 Pro 10.0.22631, i9-9900K), main 992d3fa plus this PR's diff (759f5c5202) fails to compile guest_raise_exception_tests with error: 'SIGUSR1' was not declared in this scope at the three new lines. CI builds the merge commit, so it should hit the same error.

With only those three names changed to GUEST_SIGUSR1 (locally, not pushed), same host and build directory:

AI-assisted: yes (Claude Code)

@JJenkx

JJenkx commented Oct 30, 2026

Copy link
Copy Markdown
Contributor

Windows run of this head (759f5c5202), merged onto main 7d4006607a. Windows 11 Enterprise 10.0.22621, Ryzen 9 5950X, WinLibs GCC 15.2.0 UCRT r7, Ninja, Release, BUILD_TESTING=ON, no Vulkan driver visible.

1. It no longer compiles merged onto current main. The merge is textually clean, but:

core/libs/tests/GuestRaiseException.cpp:751:57: error: 'SIGUSR1' was not declared in this scope
core/libs/tests/GuestRaiseException.cpp:764:67: error: 'SIGUSR1' was not declared in this scope
core/libs/tests/GuestRaiseException.cpp:780:56: error: 'SIGUSR1' was not declared in this scope

main renamed the test's constant to GUEST_SIGUSR1 in 76c419a572 ("name the raise-exception test's signal so macOS builds it"), and the three lines this PR adds still use the bare SIGUSR1. Renaming those three to GUEST_SIGUSR1 is all that's needed.

2. With that rename applied locally, it fixes #11813 here decisively. guest_raise_exception, run alone, one run at a time, ctest --timeout 300:

build failures run times
main 7d4006607a 10 of 10 (and 9 of 10 in a second set) 17–36 s
this PR + the rename 0 of 10 12.96–13.10 s

Every main failure is the #11813 signature, address waking round N: the handler did not run within 5 s, with N between 0 and 12. On this machine the main failure rate varies a lot with conditions: it was about 1 in 8 earlier today, on the same code (bb04a4f1ea fails 6 of 6 now). With this PR it is 0, and the run time is also steady at 13 s.

AI-assisted: yes (Claude Code).

@akkadbakkad89

Copy link
Copy Markdown
Contributor Author

Rebased onto 833be4af8d and fixed the build break @bunbeans2-arch and @JJenkx reported: upstream renamed the test constant to GUEST_SIGUSR1, and this PR's new drain-mailbox block used the old SIGUSR1 name in three raises — the merged tree then failed to compile guest_raise_exception_tests. The new lines now use GUEST_SIGUSR1; the Exception.cpp hunk was dropped since current main already carries that change.

Verified on Windows 11 (MinGW GCC 15.2.0, Release, BUILD_TESTING=ON): guest_raise_exception passes on the rebased head 4c5eec4e — the compile error is gone.

@bunbeans2-arch

Copy link
Copy Markdown
Contributor

Thanks, the build break is fixed. Re-run on Windows 11 Pro 10.0.22631, i9-9900K, MSYS2 UCRT64 GCC 16.1.0, Release, with this head (4c5eec4ef0) merged into main b8f0a6b:

  • No bare SIGUSR1 is left in GuestRaiseException.cpp, and guest_raise_exception_tests and guest_raise_leaves_host_code_tests build.
  • guest_raise_exception and guest_raise_leaves_host_code both passed in 5 of 5 runs.

As in my earlier comment, main alone also passes guest_raise_exception on this CPU, so this run shows the merged tree builds and passes, not that it fixes #11813 here.

AI-assisted: yes (Claude Code)

@akkadbakkad89
akkadbakkad89 force-pushed the exception-drain-mailbox branch from 4c5eec4 to 25a6dfc Compare October 31, 2026 16:47
@akkadbakkad89

Copy link
Copy Markdown
Contributor Author

Rebased onto current main (474030e5) — pushed 25a6dfcf.

Upstream 5090bcd175 ("select the registered main thread for own-pid scheduling") landed after this branch's merge-base and added LockMainGuestThread_nid_no_patch + the initialThread registry flag — the earlier head predated them, so a merge looked like a removal on this branch's side. The rebase replays the drain-mailbox commit on top of the new mechanism instead of conflicting with it.

Verified on the rebased tree (Windows, MinGW): guest_raise_exception passes in 13.8 s — including the new churn-then-drain and exit-after-churn rounds — and tools/check_conventions.py --base origin/main reports 0 errors.

@akkadbakkad89
akkadbakkad89 force-pushed the exception-drain-mailbox branch from 25a6dfc to f66d218 Compare October 31, 2026 16:52
@oneandonlydean

Copy link
Copy Markdown
Collaborator

@akkadbakkad89 The mailbox connection appears to have been lost in the current head f66d2185d2fe2e1589a56e2f4cf116c8ea3240eb.

Compared with the previously reviewed 759f5c5202dc, System/src/Exception.cpp no longer has the postAfterResume / QueueForDeliveryDrain call, DeferredWaitingEntry, or the queued delivery's thread, posted and closed state. The complete file currently equals main. Searching all of core/libs/prx/libkernel finds QueueForDeliveryDrain only at its definition in Time/TimedWait.cpp and declaration in Time/include/TimedWait.hpp; there is no producer. The new drain/reap helpers are therefore never given an exception delivery, and a check for zero pending entries can pass because nothing was ever queued.

Please restore the mailbox producer and callback on top of current main, preserving the reviewed requirements to enqueue after resuming the target, settle a delivery only at its final settle points, and suppress stale or duplicate delivery. Keep main's newer exception-delivery and thread-registry changes. Please also make a focused Windows regression prove that at least one raise was actually posted and delivered through the mailbox, then verify exactly-once delivery and exit cleanup. The existing reports where main also passes establish coexistence, but cannot discriminate this missing connection. No need to add an assertion that a valid unimplemented call throws.

This is a source review; I have not run Windows here.

…ndows

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
@akkadbakkad89
akkadbakkad89 force-pushed the exception-drain-mailbox branch from f66d218 to 7ff3b70 Compare November 1, 2026 07:53
@akkadbakkad89

Copy link
Copy Markdown
Contributor Author

@oneandonlydean Confirmed and restored at 7ff3b7091b — the 474030e rebase kept upstream's rewritten Exception.cpp but silently dropped this branch's delta on top of it, leaving the mailbox with no producer.

What came back, ported onto the current SuspendTarget/RetireReturnBreak structure:

  • QueuedDelivery regained thread, posted and closed; DeferredWaitingEntry (claims only when not closed, not finished, and wins taken) and SettleQueued are back after ReleaseQueued.
  • The Host path again marks the first post via posted.exchange, takes the extra reference, and calls TimedWait::QueueForDeliveryDrain(GetThreadId(native), &DeferredWaitingEntry, queued) strictly after ResumeThread — the suspend/lock deadlock ordering from the earlier review is preserved.
  • SettleQueued precedes each final ReleaseQueued: the sweep's settle of a finished raise, the Delivered/Exited return, the Restoring deadline, and the DuplicateHandle failure. The return-break and wait-queue consumption paths keep bare ReleaseQueued (delivery, not settle), matching the reviewed head.
  • Upstream's newer pieces (NtSuspendThread/ThreadIsTerminating, atomic ReturnBreak.queued claim, RetireReturnBreak, main-thread registry) are all kept.

Windows regression: guest_raise_exception passes 3/3 (ctest --repeat until-fail:3, 13 s each). Its churn-worker block now discriminates the connection you asked for: raises posted while the target spins host code can only reach ExpectDelivery through DeferredWaitingEntry drained by DrainApcs, and DeliveryDrainPending() == 0 after join proves exit reaping — with no producer the first ExpectDelivery times out. guest_raise_leaves_host_code also passes 3/3.

@oneandonlydean

Copy link
Copy Markdown
Collaborator

@akkadbakkad89 The mailbox producer is restored in 7ff3b7091b, including the enqueue after ResumeThread, but the new exit reap still has an ordering gap.

In System/src/Exception.cpp, the raiser reserves the callback reference, resumes the target, then calls QueueForDeliveryDrain. The target can finish and run its final ReapDeliveryDrain in Pthread/src/Thread.cpp between the resume and that enqueue. Time/TimedWait.cpp then inserts into a mailbox whose target has already finished. The background sweep closes the delivery and releases its own reference, but it never removes the mailbox entry or releases the callback reference. Without reuse of that thread ID, both remain retained.

Please coordinate enqueue admission with final exit cleanup so a post cannot be stranded after the target's final reap, while keeping mailbox locking outside the suspend window. Add a controlled test that pauses the producer after resume, lets the target finish and reap, then completes the post and checks pending entries and reference cleanup. The existing churn/zero-pending checks do not force this ordering; please also make the regression positively observe a mailbox post and delivery.

This is a source-derived schedule, not a Windows reproduction. The restored producer fixes the earlier missing-connection finding; the remaining request concerns exit cleanup.

@akkadbakkad89

Copy link
Copy Markdown
Contributor Author

@oneandonlydean Fixed at 7071ab6d8f — enqueue admission is now coordinated with the target's final reap.

QueueForDeliveryDrain takes the target's _finished flag and evaluates it inside drainBoxesLock. _finished is stored before finishThread's ReapDeliveryDrain in program order, and the mutex orders every admission critical-section against every reap critical-section, so exactly one of two things happens:

  • the post lands before the reap runs → the box still exists → the reap drains and executes it;
  • the post lands after the reap → _finished is already visible → admission is denied and the callback runs inline on the poster (DeferredWaitingEntry resolves it unclaimed and drops the reference — the same path a drained-but-unclaimed entry takes).

Either way the callback executes exactly once and no entry can be left in a box nothing will drain. The lock is still only held around the admission check and the enqueue — never inside the suspend window — and the resolved inline run also happens after the lock is released, mirroring ReapDeliveryDrain's own ordering.

Regression in GuestRaiseException.cpp: SetDeliveryDrainPostHook installs a seam at the top of QueueForDeliveryDrain (after resume, before the admission). The new block raises on a churning thread from a separate std::thread (the producer can post on the caller), detects the hook entry, releases the target to finishThread + final ReapDeliveryDrain, joins it, then releases the producer to complete the post. It then requires DeliveryDrainPending() == 0 — on the old shape the entry strands and this fails (verified: forcing an unconditional enqueue aborts the test at exactly that check). Positive observation: the hook counts real posts — all 10 churn-round raises entered it — alongside ExpectDelivery confirming each raise was delivered.

guest_raise_exception passes (13.3s via ctest, plus two direct runs).

QueueForDeliveryDrain ran after ResumeThread with no coordination with
the target's final ReapDeliveryDrain: a target could exit between resume
and enqueue, leaving the post in a box nothing would drain again and
retaining the QueuedDelivery reference.

Admission is now decided under drainBoxesLock against the target's
_finished flag, which is stored before the final reap in program order;
denied posts run their callback inline so the entry and the reference
are resolved exactly once on either path.

The GuestRaiseException regression arms a post hook, holds the producer
between resume and enqueue, lets the target finish and reap, then
completes the post and requires the drain to stay empty; the churn
rounds also assert the post hook observed mailbox posts alongside the
delivered raises.
@akkadbakkad89
akkadbakkad89 force-pushed the exception-drain-mailbox branch from 7071ab6 to 2189fb0 Compare November 1, 2026 13:00
@akkadbakkad89

Copy link
Copy Markdown
Contributor Author

Pushed 2189fb06 — fixes the windows job failure on 7071ab6d.

Cause was a compile error, not a test failure: GuestRaiseException.cpp:794 used a bare SIGUSR1 inside the forced-ordering regression block — the only line in the file not using GUEST_SIGUSR1, the constant 76c419a572 introduced so non-POSIX builds have the signal number. winlibs' headers don't declare SIGUSR1, so the object failed to compile and the job stopped before running tests.

Verified locally: guest_raise_exception passes under ctest on Windows/MinGW GCC 15.2.0 (13.2s), including the drain-retire regression block that line belongs to.

@TechLevelZero

Copy link
Copy Markdown
Contributor

✅ AMD GPU test: passed

PR head 2189fb0 merged onto main 291e02d · tested 2026-11-01 13:24 UTC · 8 min

GPU AMD Radeon RX 6300 (RADV NAVI24), driver Mesa 25.2.8-0ubuntu0.24.04.4, Vulkan 1.4.318
Host Ubuntu 26.04.1 LTS, kernel 7.0.0-42-generic, container ubuntu:24.04
Logs build and test logs for this run
Build ✅ passed (Release, -DANYPS5_ENABLE_SPIRV_TOOLS=ON)
Tests ✅ 2,476 passed · 9 failed (0 new, 9 also fail on main) · 55 skipped (ANYPS5_REQUIRE_VULKAN=1)
Test setup CPU-only tests without a GPU; GPU tests (and any CPU-only test that failed or skipped without one) once on the GPU with VK_LAYER_KHRONOS_validation and ANYPS5_NO_SHADER_CACHE=1; main ran the same way
Test selection 2,540 of 3,155 tests run: the ones this change can reach, chosen by tools/select_tests.py from main's build graph
Vulkan validation ✅ no new validation IDs vs main (1011 tests run on the GPU)
Slow tests (>30 s, GPU tests timed with validation layers) ⚠️ agc_driver_pipeline_journal 110.0 s, ⚠️ agc_driver_graphics 37.8 s, ⚠️ agc_driver_graphics_maps_fallback 37.7 s, ⚠️ public_headers 32.2 s
Failing on main too (9, not counted against this PR)
agc_driver_guest_memory_lifetime_direct
agc_driver_image_table
agc_driver_native_depth_bda_clear
agc_driver_native_depth_buffer_clear
agc_driver_native_depth_clears
agc_driver_native_multisample_depth
agc_idle_publish_wait
guest_mmap_executable
guest_socket_options_multicast
Validation IDs already present on main (5 IDs in 552 tests)
VUID-VkDeviceCreateInfo-pNext-pNext (552 tests): agc_driver, agc_driver_address_passes, agc_driver_alias_copy_label, agc_driver_alpha_to_coverage, agc_driver_array_layer_target, agc_driver_bc_block_copy, agc_driver_bda_anchor_reads, agc_driver_bda_span_reads, and 544 more
VUID-vkCmdCopyImage-srcImage-01548 (7 tests): agc_driver_depth_clear_hle, agc_driver_depth_plane_buffer_memory, agc_driver_depth_plane_partial_store, agc_driver_depth_storage_dispatch, agc_driver_depth_surface_from_storage, agc_driver_dispatch_move_depth, agc_driver_stencil_null_feedback
VUID-vkCmdCopyImage-srcImage-01551 (7 tests): agc_driver_depth_clear_hle, agc_driver_depth_plane_buffer_memory, agc_driver_depth_plane_partial_store, agc_driver_depth_storage_dispatch, agc_driver_depth_surface_from_storage, agc_driver_dispatch_move_depth, agc_driver_stencil_null_feedback
VUID-VkPipelineColorBlendStateCreateInfo-pAttachments-00605 (2 tests): agc_driver_prepared_exports, agc_driver_srgb8_color_target
VUID-VkShaderModuleCreateInfo-pCode-08737 (1 test): agc_driver_image_sample_derivatives
Skipped (55)
agc_driver_bda_reads_shadowed_results: skipped, the device reports watched host memory written when it imports or reads it
agc_driver_bda_reads_shadowed_results_per_build: skipped, the device reports watched host memory written when it imports or reads it
agc_driver_copied_writer_label_order: skipped, the device reports a minStorageBufferOffsetAlignment of 4, so the dispatch binds its record at +0x1004 in place and nothing is written back; the test needs an alignment above 4
agc_driver_image_table_vouched_lookups: skipped, the device reports 4 of 4 host-imported pages written after a GPU read, so a watched imported table cannot be vouched for
agc_driver_linear_target_direct_write_completion: skipped, the device does not keep host imports write-watched, so no completion stamp over the target is tracked
agc_driver_ngg_vertex_wave_reduction: skipped, s3 describes a 32-lane wave only on 32-lane subgroups, and the device has 64 lanes
agc_driver_sparse_dma_buf_import: skipped, host imports are unavailable: /dev/udmabuf is not accessible
agc_driver_unit_shadow: skipped, the device does not import watched host memory for unit shadows
agc_driver_unit_shadow_budget: skipped, the device does not import watched host memory for unit shadows
agc_host_import_sparse: skipped, host imports are unavailable: /dev/udmabuf is not accessible
agc_import_settle_initial_dcc: skipped, the device has no deferred settle of host imports: imports under 1 MiB wait for one only on Windows
agc_shadowed_key_stores: skipped, the device imports no watched host memory under a unit shadow
agc_small_tiled_shadow_label: skipped, host imports are unavailable: the test block is not imported and watched
agc_storage_clear_hand_over: skipped, the device imports no watched host memory for the clear-key hand-over
agc_unit_shadow: skipped, the device does not import watched host memory for unit shadows
agc_unit_shadow_completion_store: skipped, the device reports watched host memory written when it imports or reads it
guest_http_uri_locale: 
guest_net_ctl: skipped, the host has no IPv4 address
guest_video_out_color_space: skipped, no display or Vulkan device: SDL_InitSubSystem(VIDEO | GAMECONTROLLER) failed: wayland,x11 not available
guest_video_out_hdr: skipped, no display or Vulkan device: SDL_InitSubSystem(VIDEO | GAMECONTROLLER) failed: wayland,x11 not available
guest_video_out_high_frame_rate: skipped, no display or Vulkan device: SDL_InitSubSystem(VIDEO | GAMECONTROLLER) failed: wayland,x11 not available
guest_video_out_output_mode: skipped, no display or Vulkan device: SDL_InitSubSystem(VIDEO | GAMECONTROLLER) failed: wayland,x11 not available
guest_video_out_resolution_status: skipped, no display or Vulkan device: SDL_InitSubSystem(VIDEO | GAMECONTROLLER) failed: wayland,x11 not available
guest_video_out_wqhd_detection: skipped, no display or Vulkan device: SDL_InitSubSystem(VIDEO | GAMECONTROLLER) failed: wayland,x11 not available
video_out_flip_aftergpu: skipped, no display or Vulkan device: DisplayWindow: Vulkan support is either not configured in SDL or not available in current SDL video driver (offscreen) or platform
video_out_flip_backtoback: skipped, no display or Vulkan device: DisplayWindow: Vulkan support is either not configured in SDL or not available in current SDL video driver (offscreen) or platform
video_out_flip_controls: skipped, no display or Vulkan device: DisplayWindow: Vulkan support is either not configured in SDL or not available in current SDL video driver (offscreen) or platform
video_out_flip_cpuflip: skipped, no display or Vulkan device: DisplayWindow: Vulkan support is either not configured in SDL or not available in current SDL video driver (offscreen) or platform
video_out_flip_cpuflip_in_order: skipped, no display or Vulkan device: DisplayWindow: Vulkan support is either not configured in SDL or not available in current SDL video driver (offscreen) or platform
video_out_flip_dcc: skipped, no display or Vulkan device: DisplayWindow: Vu
Reproduce
git fetch origin 2189fb06ea4ebe30c518eb5d345668daf38707e8 291e02d4877784d03d346962af51713b9df63b91
git checkout 291e02d4877784d03d346962af51713b9df63b91 && git merge --no-ff 2189fb06ea4ebe30c518eb5d345668daf38707e8
git submodule update --init --recursive
cmake -S . -B build -G Ninja -DCMAKE_BUILD_TYPE=Release -DBUILD_TESTING=ON -DANYPS5_ENABLE_SPIRV_TOOLS=ON
cmake --build build && cmake --build build --target libs
VK_DRIVER_FILES=/nonexistent/icd.json ctest --test-dir build -E '^(agc|shader|recompiler|videoout|video_out|guest_video_out|vulkan)|gpu' --timeout 120 --parallel 12 --output-on-failure
ANYPS5_REQUIRE_VULKAN=1 ANYPS5_NO_SHADER_CACHE=1 VK_INSTANCE_LAYERS=VK_LAYER_KHRONOS_validation \
  ctest --test-dir build -R '^(agc|shader|recompiler|videoout|video_out|guest_video_out|vulkan)|gpu' --timeout 120 --parallel 16 --output-on-failure
# failures are then re-run alone: --timeout 360 --parallel 2; new validation IDs: the test alone, twice, --parallel 1

Automated build and test on a contributor's AMD machine; it does not replace upstream CI. A new comment is posted for each new push. Full logs.

@oneandonlydean
oneandonlydean merged commit b052a93 into boykopovar:main Nov 2, 2026
11 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

fix error Closes an issue (Fixes #N) libkernel

Projects

None yet

Development

Successfully merging this pull request may close these issues.

libkernel (Windows): guest_raise_exception slowed about 3x and sometimes aborts at "address waking" since 540364a24 (#10666)

8 participants