fix(libkernel): give a sleep nested in an APC its own timer on Windows #1520

Merged
popcoder565 merged 1 commit from upstream-pr/1520 into main 2026-10-10 01:07:46 +00:00
popcoder565 commented 2026-10-08 11:01:47 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by popcoder565 on 2026-10-08T11:01:47Z.


What

On Windows, a sceKernelRaiseException handler that sleeps left the thread it interrupted asleep for good, if that thread was itself sleeping.

SleepUntil, PollSleepUntil and SleepNanosCoarse each wait on one thread_local high-resolution timer through TimerWait. When a thread is blocked in an alertable TimedWait wait, a raise runs the handler as an APC inside that wait (#760). If the thread was sleeping and the handler sleeps too, the handler's TimerWait re-arms the same timer. The handler's own wait then consumes the signal, because it is a synchronization timer. When the handler returns, the interrupted sleep waits again on a timer that will not fire, so it never returns.

TimerWait now counts how deep it is on the thread. A nested call creates its own timer for that wait and closes it afterwards. The outermost call keeps using the thread's timer, so nothing changes outside an APC.

I found this while testing #1476 on Windows; #1476 fixes the same reuse for Condition waiters. Unity's GC handler waits in sceKernelSyncOnAddressWait, which is #1476's case, so this one only bites a handler that sleeps. If #1476's author would rather fold this in, I'll close this PR.

The new test guest_raise_nested_sleep is Windows only, like guest_raise_exception. A thread sleeps 1 s in sceKernelUsleep, a raise runs a handler that sleeps 20 ms, and the 1 s sleep must return within 1 to 2 s. It has its own file, so it doesn't add to the overlapping changes in GuestRaiseException.cpp.

Tested

Windows 10 (19045), MinGW-w64 GCC 15.2.0 (WinLibs r7), Release, Intel Core i7-12700H.

Build guest_raise_nested_sleep With APS5_COARSE_TIMED_WAITS=1
main 4a14093a, without the fix aborts after 5.2 s in 3 of 3 runs (the interrupted sleep has not returned) aborts in 2 of 2 runs
This change 20 of 20 pass, 1.03 s each 3 of 3 pass

Full ctest: 437 of 438 pass. The one failure is agc_driver_srgb8_color_target (#1434).

Not run on Linux. The change is inside #ifdef _WIN32, and the test is registered on Windows only.

Checklist

  • Based on current main; no other open PR implements the same functions
  • One topic per PR; follow-ups go in a new PR
  • No comments in code except technical debt
  • Unimplemented paths throw (NotImplemented_nid_no_patch); silent stubs are listed in TechnicalDebt
  • No notes, investigation .md files or images added to the repository (attach them to this PR)
  • New third-party code is a submodule built from source
  • Generic behaviour, not specific to one title
  • Depends on: none
  • AI-assisted: yes

🤖 Generated with Claude Code

<!-- greyfinch-sync:boykopovar/AnyPS5:issue:4785750385 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/1520). Originally posted by [popcoder565](https://github.com/popcoder565) on 2026-10-08T11:01:47Z. --- ### What On Windows, a `sceKernelRaiseException` handler that sleeps left the thread it interrupted asleep for good, if that thread was itself sleeping. `SleepUntil`, `PollSleepUntil` and `SleepNanosCoarse` each wait on one `thread_local` high-resolution timer through `TimerWait`. When a thread is blocked in an alertable `TimedWait` wait, a raise runs the handler as an APC inside that wait (#760). If the thread was sleeping and the handler sleeps too, the handler's `TimerWait` re-arms the same timer. The handler's own wait then consumes the signal, because it is a synchronization timer. When the handler returns, the interrupted sleep waits again on a timer that will not fire, so it never returns. `TimerWait` now counts how deep it is on the thread. A nested call creates its own timer for that wait and closes it afterwards. The outermost call keeps using the thread's timer, so nothing changes outside an APC. I found this while testing #1476 on Windows; #1476 fixes the same reuse for `Condition` waiters. Unity's GC handler waits in `sceKernelSyncOnAddressWait`, which is #1476's case, so this one only bites a handler that sleeps. If #1476's author would rather fold this in, I'll close this PR. The new test `guest_raise_nested_sleep` is Windows only, like `guest_raise_exception`. A thread sleeps 1 s in `sceKernelUsleep`, a raise runs a handler that sleeps 20 ms, and the 1 s sleep must return within 1 to 2 s. It has its own file, so it doesn't add to the overlapping changes in `GuestRaiseException.cpp`. ### Tested Windows 10 (19045), MinGW-w64 GCC 15.2.0 (WinLibs r7), Release, Intel Core i7-12700H. | Build | `guest_raise_nested_sleep` | With `APS5_COARSE_TIMED_WAITS=1` | |---|---|---| | `main` 4a14093a, without the fix | aborts after 5.2 s in 3 of 3 runs (the interrupted sleep has not returned) | aborts in 2 of 2 runs | | This change | 20 of 20 pass, 1.03 s each | 3 of 3 pass | Full ctest: 437 of 438 pass. The one failure is `agc_driver_srgb8_color_target` (#1434). Not run on Linux. The change is inside `#ifdef _WIN32`, and the test is registered on Windows only. ### Checklist - [x] Based on current `main`; no other open PR implements the same functions - [x] One topic per PR; follow-ups go in a new PR - [x] No comments in code except [technical debt](https://github.com/boykopovar/AnyPS5/blob/main/docs/dev/CONVENTIONS.md) - [x] Unimplemented paths throw (`NotImplemented_nid_no_patch`); silent stubs are listed in [TechnicalDebt](https://github.com/boykopovar/AnyPS5/blob/main/docs/dev/TechnicalDebt.md#silent-stubs) - [x] No notes, investigation `.md` files or images added to the repository (attach them to this PR) - [x] New third-party code is a submodule built from source - [x] Generic behaviour, not specific to one title - [x] Depends on: none - [x] AI-assisted: yes 🤖 Generated with [Claude Code](https://claude.com/claude-code)
klosixgaming-arch commented 2026-10-08 11:23:24 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by klosixgaming-arch on 2026-10-08T11:23:24Z.

Review: APPROVED


Excellent fix for a subtle Windows-specific concurrency bug. This addresses an important edge case that could cause threads to hang indefinitely when sleeping inside exception handlers.

Strengths:

  • Clear identification of the root cause: nested TimerWait calls reusing the same thread-local timer, causing the handler's wait to consume the signal meant for the interrupted sleep
  • Clean solution using RAII (Nesting struct) with proper cleanup and depth tracking
  • Comprehensive test coverage including timing verification (ensuring the outer sleep completes within expected bounds)
  • Good documentation of related issues (#1476) in TechnicalDebt.md

Technical notes:

  • The approach of creating separate timers for nested waits is correct and efficient
  • Proper handling of edge cases (depth > 1, cleanup on exit)
  • Test properly verifies both that the handler runs and that the outer sleep completes correctly

This will improve reliability for titles that use exception handlers with sleep operations. Ready to merge.

<!-- greyfinch-sync:boykopovar/AnyPS5:review:5455792370 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/1520#pullrequestreview-5455792370). Originally posted by [klosixgaming-arch](https://github.com/klosixgaming-arch) on 2026-10-08T11:23:24Z. **Review:** APPROVED --- Excellent fix for a subtle Windows-specific concurrency bug. This addresses an important edge case that could cause threads to hang indefinitely when sleeping inside exception handlers. **Strengths:** - Clear identification of the root cause: nested `TimerWait` calls reusing the same thread-local timer, causing the handler's wait to consume the signal meant for the interrupted sleep - Clean solution using RAII (`Nesting` struct) with proper cleanup and depth tracking - Comprehensive test coverage including timing verification (ensuring the outer sleep completes within expected bounds) - Good documentation of related issues (#1476) in TechnicalDebt.md **Technical notes:** - The approach of creating separate timers for nested waits is correct and efficient - Proper handling of edge cases (depth > 1, cleanup on exit) - Test properly verifies both that the handler runs and that the outer sleep completes correctly This will improve reliability for titles that use exception handlers with sleep operations. Ready to merge.
Dextroid17 commented 2026-10-08 18:46:58 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by Dextroid17 on 2026-10-08T18:46:58Z.


Verified from the outside, because this one cannot be tested on Linux at all (its CMake target does not exist there — ninja: unknown target 'guest_raise_nested_sleep_tests' on this machine, since the block is Windows-only), so the Windows CI job is the only place it can run:

  merge onto current main (2b297842)                     no conflicts
  Build run for this head (37767374928), windows job
     Start 388: guest_raise_nested_sleep
     Test #388: guest_raise_nested_sleep ... Passed 1.03 sec

So the test is registered and executed rather than skipped — which is worth stating explicitly, because a test that exits 77 or is never run still leaves the job green (that is the hole #1028 addresses).

The change itself reads correctly: Nesting increments depth in its constructor, so depth > 1 is true exactly for a wait nested inside another on the same thread, and the nesting's own timer is closed in the destructor after the wait has returned. Replacing the Waiter linked-list of nested waiters with thread_local depth also removes the allocation per nesting level.

One small question, the only silent path I can see: if CreateHighResolutionTimer() fails, own is null and timer = nesting.own points the nested wait at no timer, so that level falls back to the thread's shared one — the original behaviour, but now silent. Should that be a hard failure, or is falling back the intended degradation to record in the debt file?

Written with AI assistance.

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6066749993 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/1520#issuecomment-6066749993). Originally posted by [Dextroid17](https://github.com/Dextroid17) on 2026-10-08T18:46:58Z. --- Verified from the outside, because this one cannot be tested on Linux at all (its CMake target does not exist there — `ninja: unknown target 'guest_raise_nested_sleep_tests'` on this machine, since the block is Windows-only), so the Windows CI job is the only place it can run: ``` merge onto current main (2b297842) no conflicts Build run for this head (37767374928), windows job Start 388: guest_raise_nested_sleep Test #388: guest_raise_nested_sleep ... Passed 1.03 sec ``` So the test is registered *and* executed rather than skipped — which is worth stating explicitly, because a test that exits 77 or is never run still leaves the job green (that is the hole #1028 addresses). The change itself reads correctly: `Nesting` increments `depth` in its constructor, so `depth > 1` is true exactly for a wait nested inside another on the same thread, and the nesting's own timer is closed in the destructor after the wait has returned. Replacing the `Waiter` linked-list of nested waiters with `thread_local` depth also removes the allocation per nesting level. One small question, the only silent path I can see: if `CreateHighResolutionTimer()` fails, `own` is null and `timer = nesting.own` points the nested wait at no timer, so that level falls back to the thread's shared one — the original behaviour, but now silent. Should that be a hard failure, or is falling back the intended degradation to record in the debt file? Written with AI assistance.
popcoder565 commented 2026-10-09 02:56:09 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by popcoder565 on 2026-10-09T02:56:09Z.


@Dextroid17 thanks for checking it.

If the nested timer can't be created: the nested wait doesn't fall back to the shared timer. timer = nesting.own sets it to null, and if (!timer) return false; returns before SetWaitableTimer. All three callers (SleepNanosCoarse, SleepUntil, PollSleepUntil) then sleep with AlertableSleep in whole milliseconds, the same fallback they already take when the thread's own timer is null.

Creating the timer fails only when the process runs out of handles or memory, or on Windows 10 before 1803, which doesn't support CREATE_WAITABLE_TIMER_HIGH_RESOLUTION. On those versions every sleep already takes the millisecond path. So I'd keep the fallback: it's coarser, but it never hangs.

Rechecked after #1476 merged (Windows 10 19045, GCC 15.2.0 WinLibs r7, Release, this PR merged onto main f1451396):

  • This PR: guest_raise_nested_sleep passes 3/3 (1.04–1.06 s), and guest_raise_exception passes 3/3.
  • With TimedWait.cpp from main: guest_raise_nested_sleep fails 2/2, because the outer sleep still hasn't returned 5 s after the handler ran.

#1476 gives each nested condition wait its own waiter and timer. The sleep paths still share one timer per thread, and that's what this PR covers.

🤖 Addressed by Claude Code

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6073308703 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/1520#issuecomment-6073308703). Originally posted by [popcoder565](https://github.com/popcoder565) on 2026-10-09T02:56:09Z. --- @Dextroid17 thanks for checking it. **If the nested timer can't be created:** the nested wait doesn't fall back to the shared timer. `timer = nesting.own` sets it to null, and `if (!timer) return false;` returns before `SetWaitableTimer`. All three callers (`SleepNanosCoarse`, `SleepUntil`, `PollSleepUntil`) then sleep with `AlertableSleep` in whole milliseconds, the same fallback they already take when the thread's own timer is null. Creating the timer fails only when the process runs out of handles or memory, or on Windows 10 before 1803, which doesn't support `CREATE_WAITABLE_TIMER_HIGH_RESOLUTION`. On those versions every sleep already takes the millisecond path. So I'd keep the fallback: it's coarser, but it never hangs. **Rechecked after #1476 merged** (Windows 10 19045, GCC 15.2.0 WinLibs r7, Release, this PR merged onto `main` f1451396): - This PR: `guest_raise_nested_sleep` passes 3/3 (1.04–1.06 s), and `guest_raise_exception` passes 3/3. - With `TimedWait.cpp` from `main`: `guest_raise_nested_sleep` fails 2/2, because the outer sleep still hasn't returned 5 s after the handler ran. #1476 gives each nested condition wait its own waiter and timer. The sleep paths still share one timer per thread, and that's what this PR covers. _🤖 Addressed by [Claude Code](https://claude.com/claude-code)_
adriadam10 commented 2026-10-10 01:07:43 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by adriadam10 on 2026-10-10T01:07:43Z.


Checked the diff (nesting depth per thread, nested wait owns and closes its timer, outermost keeps the thread's timer; failure to create it falls back to the millisecond sleep in all three callers). Local Linux build and ctest are unaffected (the code and the test are Windows-only); the Windows job on this head runs and passes guest_raise_nested_sleep, as @Dextroid17 confirmed from the log, and the author's before/after runs show it aborting without the change. Merging.

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6091994792 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/1520#issuecomment-6091994792). Originally posted by [adriadam10](https://github.com/adriadam10) on 2026-10-10T01:07:43Z. --- Checked the diff (nesting depth per thread, nested wait owns and closes its timer, outermost keeps the thread's timer; failure to create it falls back to the millisecond sleep in all three callers). Local Linux build and ctest are unaffected (the code and the test are Windows-only); the Windows job on this head runs and passes `guest_raise_nested_sleep`, as @Dextroid17 confirmed from the log, and the author's before/after runs show it aborting without the change. Merging.
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
boykopovar/AnyPS5!1520
No description provided.