Skip to content

fix(libkernel): arm Windows timed waits early by the timer's measured lateness - #19794

Merged
oneandonlydean merged 1 commit into
boykopovar:mainfrom
adam25136:fix/libkernel-timer-lateness
Nov 17, 2026
Merged

oneandonlydean merged 1 commit into
boykopovar:mainfrom
adam25136:fix/libkernel-timer-lateness

Conversation

@adam25136

Copy link
Copy Markdown
Contributor

What

Here a Windows high-resolution waitable timer usually fires about 0.5 ms after its due time (a 5 ms one a median 439 to 473 us late in the check below) and sometimes nearly on time (the median of nine 1 ms waits was 37 us in one process). That fits a timer that fires at the first 0.5 ms scheduler tick after its due time, so that a wait starting just after a tick and lasting whole ticks ends a whole tick late. #1471 (popcoder565) measured a 1 ms one at 1.5 ms on Windows 10. libkernel's deadline waits start their timer 20 us before the deadline and spin the rest; #11725 (camezaro-intc) lowered that from 500 us so that sub-millisecond polling waits stop spinning. With 20 us, a guest timed wait that runs out ends up to about 0.5 ms late here: with APS5_TRACE_TIMERS=1, scePthreadCondTimedwait(1000 us) takes a median 1432.7 us on main and (13000 us) 13374.7 us.

That is enough to break a title that paces itself with short waits. In GTA V (PPSA04264) the intro movies' sound thread (the Bink player linked into the game) waits up to 5 ms, then sends one 256-sample block (5.33 ms) to its own AudioOut2 context, which queues 4 blocks. It keeps up only if each wait and its work take less than 5.33 ms. On main those waits take 5.2 to 5.6 ms on average, the thread sends 177 to 185 blocks a second against the 187.5 the output plays, and the output runs out 5 to 21 times during the 16 s intro, each time playing silence until AnyPS5's 40 ms cushion refills.

libkernel now keeps a moving average of how late the timer fires. It starts from the median of nine 1 ms waits at load, printed on the [time] scheduler tick line, and each timer wake of a deadline wait then counts 1/16 of it, capped at 1 ms. WaitEventUntil (condition variable and park waits, and the POSIX nanosleep and usleep over 1 ms), SleepUntil (sceKernelUsleep and sceKernelNanosleep over 1 ms) and SleepNanosUnlessChanged (these sleeps up to 1 ms) start their timer that much earlier, by at most an eighth of the wait, and spin the rest as before. A wait that times out still never ends before its deadline. Other hosts are unchanged: the change is in the Windows branches, and TimerLateNanos() returns 0 elsewhere.

A fixed start one tick early would also end these waits on time, but then every wait would spin a whole tick while the timer is nearly on time. With the average, Bink's wait takes 5.1 ms on average; an earlier version that measured only once at load gave 5.0 to 5.1 ms. The cost is spinning: a wait that times out now spins for up to 20 us plus the smaller of the average and an eighth of the wait, instead of up to 20 us. That is at most 62.5 us more for a 500 us wait, the case #11725 measured, and here up to about 0.5 ms more for waits of 4 ms or longer. Without the eighth, a 100 us sceKernelUsleep spun for its whole length (92 to 107 % of a core, where guest_timed_wait_cpu allows 40 %).

guest_timed_wait_cpu gets a check for this on Windows. It takes turns of a 5 ms high-resolution timer, a 5 ms scePthreadCondTimedwait and a 5 ms sceKernelUsleep, 100 of each. When the timer's median overshoot is 200 us or more, both guest waits' median overshoots must be under a quarter of it, in one of three attempts like the test's other checks.

Overlap: tools/pr_overlap.py --branch (in a full clone, 1,579 open pull requests) finds 14 that change these files. The 9 it could merge share no lines with this change, among them #18518 (17bryen, sleeps under 50 us) and #18854 (atinseau, condition notifications), which also merge with this branch without conflicts. It could not compare the other 5, which conflict with main. In GitHub's patch of each: #8592 (gohansharma79-svg) adds a declaration in TimedWait.hpp one line below the one this change adds, and an include at the top of TimedWait.cpp; #18515 (nicolasabosch, a draft marked not for merge) adds a class just above bool Coarse();, one line above this change's declaration, and changes NowNanos, two lines below the function this change adds; #12642 (2Swagger, draft), #17551 (AasishDairelSahayaGrinspan) and #17609 (sherySJ) change other parts of these files.

Tested

Windows 10 Pro 22H2 (19045), i9-12900KF, WinLibs GCC 15.2.0 r7, Release, BUILD_TESTING=ON. Tested on head 8218743adb on main 752c0f776b, everything there except the frame rate runs. Rebased before opening onto main cec640c595 (head 1eb9ef3d5d, the same changed lines; none of the 24 commits in between touches these files), where libkernel's 264 tests pass and guest_timed_wait_cpu passes in 3 of 3 runs.

  • libkernel's tests (the 264 registered in libkernel/CMakeLists.txt that build on Windows) pass on main and on this head.
  • guest_timed_wait_cpu passes in 5 of 5 runs. In its new check the 5 ms timer overshot by a median of 439 to 473 us, scePthreadCondTimedwait by 12 to 24 us and sceKernelUsleep by 3 to 6 us. On main with only this test file it fails in 2 of 2 runs, every attempt over the limit (sceKernelUsleep 399 to 484 us against limits of 117 to 121 us).
  • With parts of the change removed, two runs each (restored afterwards):
Removed Fails
the timer's lateness in the early start (LeadNanos) the new check, every attempt
the early start in WaitEventUntil only the new check, scePthreadCondTimedwait, every attempt
the early start in SleepUntil only the new check, sceKernelUsleep, every attempt
the cap at an eighth of the wait the existing 100 us sceKernelUsleep CPU check (106.9 % and 91.8 % of a core, against 40 %)
  • Timer self-test (APS5_TRACE_TIMERS=1, ctest -R '^guest_cond_timedwait$' -V): scePthreadCondTimedwait(1000 us) median 1432.7 us on main and 1005.4 us with this change; (13000 us) 13374.7 against 13012.4 us.
  • GTA V (PPSA04264 01.005.000), the intro with scripted controller input, main against this change on the same main, a warm-up run and then three alternating pairs of 60 s. Switches: APS5_TRACE_AUDIOOUT2=1 (per AudioOut2 context, pushes per second and a running count of the times the output ran out), APS5_TRACE_AUDIOOUT=1, APS5_TRACE_WAITS=1 with APS5_TRACE_CALLS=libkernel (the wait column), and the harness's 1/8-scale frame dump (every 15th frame, at most 220), a summary line every 10 s, APS5_PIPELINE_STATS=1 and APS5_LOG_TIMESTAMPS=1:
run Bink's 5 ms wait, mean per 3 s window intro context, pushes/s (needs 187.5) intro run-outs
main 5.2-5.4 ms 185.1 5
this PR 5.0-5.1 ms 187.7 0
this PR 5.1 ms 187.6 0
main 5.5-5.6 ms 176.9 21
main 5.4-5.6 ms 177.4 20
this PR 5.1 ms 187.8 0

Two earlier main runs (667dbde513) with only the two AudioOut traces and the harness switches ran out 12 and 8 times in the intro. The game's own context ran out 0 to 2 times per run, between 17 and 22 s in, on both sides (main 0, 1, 0; this PR 1, 2, 2). This PR's runs start from a copy of the converted folder. In three more pairs with main's library in both, the copy ran out 2, 2 and 2 times there and the original 0, 0 and 2, so that difference likely comes from the copy; in the intro the copy ran out 7, 23 and 6 times and the original 21, 22 and 22, so the copy is not what gives this PR its zero run-outs.

  • GTA V frame rate and CPU, on an earlier head that measured the timer once at load instead of keeping an average (385 to 493 us in these runs), on main 5d92187464: Performance mode, the prologue spot where the player stands still, 260 s per run, FPS from 111 s on, a warm-up run and 4 rounds with the two rotated. main 15.03, 15.64, 16.18, 16.04 FPS (mean 15.72, standard deviation 0.51); that head 15.75, 14.98, 15.36, 16.30 (mean 15.60, standard deviation 0.57), -0.8 %. Whole-machine CPU utility over 115 to 255 s: 27.2 % on main, 27.1 % with that head; a few percent of one of the 24 hardware threads would not show there.
  • python tools/check_conventions.py --base origin/main with this title and description passes.

Not covered: Windows 11, other CPUs, Linux and macOS (unchanged, not run), a PS5, and this head's CPU cost in a title.

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 under Silent stubs in their library's technical debt file
  • 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
  • Fixes: none
  • Unblocks: PPSA04264 Grand Theft Auto V (PPSA04264) #1203
  • GPUs tested: n/a
  • AI-assisted: yes. Claude Code found the cause, wrote the change and the test, ran the builds, tests and GTA V runs, and drafted this description; two separate review agents checked it.

🤖 Generated with Claude Code

… lateness

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

@PrivacyOnion PrivacyOnion left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Verified on Linux (Ubuntu 24.04, GCC 13.3, Ninja, Release) against 1eb9ef3d5d:

  • Conventions: tools/check_conventions.py passed; git diff --check clean.
  • Build: guest_timed_wait_cpu_tests built cleanly.
  • CTest (guest_timed_wait_cpu):
    1/1 Test #4680: guest_timed_wait_cpu .............   Passed    0.78 sec
    100% tests passed, 0 tests failed out of 1
    
  • Negative control: the tests still pass with the change reverted, so they do not cover it
  • Code reading:
    • core/libs/prx/libkernel/Time/TimedWait.cpp: Verified that CalibratedTimerLateNanos() creates, samples, and safely handles waitable timers over 9 iterations of 1 ms (CALIBRATION_WAIT_NANOS), correctly handles failure of CreateHighResolutionTimer() returning nullptr, guarantees CloseHandle() on all execution paths, and computes the median at index 4 (CALIBRATION_WAITS / 2) capped at MAX_TIMER_LATE_NANOS (1 ms).
    • core/libs/prx/libkernel/Time/TimedWait.cpp: Verified that LeadNanos() prevents unbounded core spin on short sleeps (such as 100 us sceKernelUsleep) by capping early wake lead to remainingNanos / LATE_LEAD_SHARE (1/8th of remaining duration) plus LEAD_NANOS (20 us), and verified that bulk calculation in WaitEventUntil, SleepUntil, and SleepNanosUnlessChanged never underflows uint64_t.
    • core/libs/prx/libkernel/Time/TimedWait.cpp and include/TimedWait.hpp: Verified cross-platform LP64/LLP64 portability, ensuring Windows-specific timer functions and atomic moving average updates are strictly contained within #ifdef _WIN32, TimerLateNanos() cleanly defaults to 0 on non-Windows hosts, and all std::min invocations compare matching std::uint64_t operands.
    • core/libs/prx/libkernel/Time/Time.cpp: Verified that g_timerResolutionRaised calculates timerLateUs via TimedWait::TimerLateNanos() when !TimedWait::Coarse(), matching format specifiers (%s, %.2f, %.0f) without static initialization ordering hazards.
    • core/libs/tests/GuestTimedWaitCpu.cpp: Verified that TestDeadlinesWithLateHostTimer() rigorously tests 100 iterations of 5000 us waits for both scePthreadCondTimedwait (asserting SCE_KERNEL_ERROR_ETIMEDOUT) and sceKernelUsleep_nid_postfix (asserting 0), strictly enforces that guest waits never return early (Require(elapsed >= DEADLINE_WAIT_NANOS)), and releases the timer handle, pthread mutex, and condition variable on all paths.
    • AGENTS.md compliance: Verified zero non-compliant comments added across all diffs (retaining only permitted preprocessor directives), adherence to Conventional Commits in PR title (fix(libkernel)), no title-specific hardcoding, and no unauthorized files or dependencies added.
  • Minor: please drop the Generated with footer from the description; the AI-assisted checkbox can stay.

Requesting changes for the points above.

@github-actions github-actions Bot added the unblocks title Names a title ID on the Unblocks line label Nov 13, 2026
@adam25136

Copy link
Copy Markdown
Contributor Author

@PrivacyOnion thanks for building and running it. The change and the new check only take effect on Windows: the changed timer code is in the _WIN32 branches of TimedWait.cpp and Time.cpp, TimerLateNanos() returns 0 elsewhere, and TestDeadlinesWithLateHostTimer is compiled and called only under _WIN32. So on Linux guest_timed_wait_cpu runs the same checks with or without the change, and a negative control can only show a difference on Windows.

On Windows, as in the Tested section: with only this test file on main (752c0f776b, before the rebase; the same changed lines) it fails in 2 of 2 runs, every attempt over the limit (sceKernelUsleep 5 ms waits a median of 399 to 484 us late, against limits of 117 to 121 us), and each of the four partial reverts in the table fails it too, the last one in the existing 100 us CPU check. There, ctest -R '^guest_timed_wait_cpu$' -V prints the timer's and both waits' median overshoot on its 5000 us median overshoot line.

AI-assisted: yes. Claude Code drafted this reply from the PR's code and test logs; a separate review agent checked it.

@PrivacyOnion PrivacyOnion left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Verified on Linux (Ubuntu 24.04, GCC 13.3, Ninja, Release) against 1eb9ef3d5d:

  • Conventions: tools/check_conventions.py passed; git diff --check clean.
  • Build: guest_timed_wait_cpu_tests built cleanly.
  • CTest (guest_timed_wait_cpu):
    1/1 Test #4680: guest_timed_wait_cpu .............   Passed    0.80 sec
    100% tests passed, 0 tests failed out of 1
    
  • Negative control: the tests still pass with the change reverted, so they do not cover it
  • Code reading:
    • core/libs/prx/libkernel/Time/TimedWait.cpp: Verified that LeadNanos scales the early arming lead time by std::min(TimerLateAverage, remainingNanos / LATE_LEAD_SHARE) alongside LEAD_NANOS (20 us), preventing excessive spin-polling on short waits such as 100 us sceKernelUsleep.
    • core/libs/prx/libkernel/Time/TimedWait.cpp: Verified that RecordTimerLate and LastWakeNanos safely compute wake overshoot against dueNanos without unsigned integer underflow (evaluating to 0 when woke <= dueNanos) and cap updates at MAX_TIMER_LATE_NANOS (1 ms) without arithmetic overflow in the weighted average.
    • core/libs/prx/libkernel/Time/TimedWait.cpp: Verified that WaitEventUntil, SleepUntil, and SleepNanosUnlessChanged spin until now >= deadlineNanos, ensuring guest timed waits never return ETIMEDOUT or complete prior to their specified deadline.
    • core/libs/prx/libkernel/Time/TimedWait.cpp and Time.cpp: Verified portability and initialization safety under LP64/LLP64; all Windows APIs and calibration logic are enclosed in #ifdef _WIN32, TimerLateNanos() returns 0 on non-Windows platforms, and function-local static initialization of TimerLateAverage avoids order-of-initialization hazards.
    • core/libs/prx/libkernel/Time/TimedWait.cpp: Verified timer handle resource management in CalibratedTimerLateNanos, ensuring CloseHandle(timer) is invoked on all return paths including SetWaitableTimer or WaitForSingleObject failures.
    • core/libs/tests/GuestTimedWaitCpu.cpp: Verified that TestDeadlinesWithLateHostTimer properly tests scePthreadCondTimedwait and sceKernelUsleep_nid_postfix overshoots against host waitable timer overshoot under _WIN32, enforces cleanup of mutex, cond, and timer handles, and is cleanly excluded on non-Windows builds.
    • AGENTS.md rules: Verified zero comments in code across all modified files (except #endif), conventional commit compliance, and no unauthorized modifications or debt discrepancies.
  • Minor: please drop the Generated with footer from the description; the AI-assisted checkbox can stay.

Requesting changes for the points above.

@adam25136

Copy link
Copy Markdown
Contributor Author

@PrivacyOnion on the footer: it stays. Nothing in CONTRIBUTING.md, AGENTS.md or the pull request template asks for it to be removed, and the template's AI-assisted line already discloses the same thing. Please keep review points to the code, the tests and the description's claims; I won't act on further requests to remove the footer.

@PrivacyOnion PrivacyOnion left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Verified on Linux (Ubuntu 24.04, GCC 13.3, Ninja, Release) against 1eb9ef3d5d:

  • Conventions: tools/check_conventions.py passed; git diff --check clean.
  • Build: guest_timed_wait_cpu_tests built cleanly.
  • CTest (guest_timed_wait_cpu):
    1/1 Test #4680: guest_timed_wait_cpu .............   Passed    0.80 sec
    100% tests passed, 0 tests failed out of 1
    
  • Negative control: the tests still pass with the change reverted, so they do not cover it
  • Code reading:
    • core/libs/prx/libkernel/Time/TimedWait.cpp: Verified CalibratedTimerLateNanos safely queries high-resolution timer latency across 9 1ms samples, properly releases the timer handle via CloseHandle on all paths, and takes the median clamped to MAX_TIMER_LATE_NANOS.
    • core/libs/prx/libkernel/Time/TimedWait.cpp: Verified LeadNanos bounds the early lead time to LEAD_NANOS (20 us) plus min(TimerLateAverage, remaining / 8), preventing excessive spin time on short sleeps and ensuring bulk wait intervals in WaitEventUntil, SleepUntil, and SleepNanosUnlessChanged do not underflow.
    • core/libs/prx/libkernel/Time/TimedWait.cpp: Verified that spinning loops in WaitEventUntil, SleepUntil, and SleepNanosUnlessChanged continue spinning until NowNanos() >= deadlineNanos, strictly guaranteeing guest timed waits (sceKernelUsleep, scePthreadCondTimedwait, park waits) never return before their requested deadline.
    • core/libs/prx/libkernel/Time/TimedWait.cpp and Time.cpp: Verified cross-platform LP64/LLP64 portability, ensuring TimerLateNanos() returns 0 on non-Windows platforms, g_timerResolutionRaised logging compiles cleanly on _WIN32, and all std::min invocations compare matching std::uint64_t operands.
    • core/libs/tests/GuestTimedWaitCpu.cpp: Verified TestDeadlinesWithLateHostTimer properly tests scePthreadCondTimedwait and sceKernelUsleep against raw timer overshoot, asserts elapsed >= DEADLINE_WAIT_NANOS to catch early wakes, cleans up mutex/cond/timer handles without leaking across attempts, and is safely guarded by #ifdef _WIN32.
    • Repository rules (AGENTS.md): Verified strict compliance with codebase conventions: zero comments introduced in source or test code, no fake success stubs, no title-specific special-casing in library implementations, and valid Conventional Commit PR naming.
  • Minor: please drop the Generated with footer from the description; the AI-assisted checkbox can stay.

Requesting changes for the points above.

@adam25136

Copy link
Copy Markdown
Contributor Author

@PrivacyOnion this review repeats both points from the earlier ones, and both are answered above: the change and its check only take effect on Windows, so a Linux negative control cannot show a difference (reply), and the footer stays (reply). A negative control on Windows would be the useful check here; the Tested section has ours.

@JJenkx

JJenkx commented Nov 14, 2026

Copy link
Copy Markdown
Contributor

Windows check of head 1eb9ef3d5d, merged onto main 5e58891ed2 (6a0490ff1c, clean merge).

Setup: Windows 11 Enterprise 22621, WinLibs GCC 15.2 UCRT, Release. The hosted Windows check does not run these tests on pull requests.

  • guest_timed_wait_cpu passes in 3 of 3 runs, none skipped.

AI-assisted: yes.

@github-actions

github-actions Bot commented Nov 14, 2026 •

Copy link
Copy Markdown

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 8592 core/libs/prx/libkernel/Time/TimedWait.cpp
core/libs/prx/libkernel/Time/include/TimedWait.hpp
PR 12418 core/libs/prx/libkernel/Time/Time.cpp
PR 12642 core/libs/prx/libkernel/Time/Time.cpp
core/libs/prx/libkernel/Time/TimedWait.cpp
core/libs/prx/libkernel/Time/include/TimedWait.hpp
PR 18515 core/libs/prx/libkernel/Time/Time.cpp
core/libs/prx/libkernel/Time/TimedWait.cpp
core/libs/prx/libkernel/Time/include/TimedWait.hpp

@PrivacyOnion PrivacyOnion left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Verified on Linux (Ubuntu 24.04, GCC 13.3, Ninja, Release) against 1eb9ef3d5d:

  • Conventions: tools/check_conventions.py passed; git diff --check clean.
  • Build: guest_timed_wait_cpu_tests built cleanly.
  • CTest (guest_timed_wait_cpu):
    1/1 Test #5085: guest_timed_wait_cpu .............   Passed    0.80 sec
    100% tests passed, 0 tests failed out of 1
    
  • Negative control: with core/libs/prx/libkernel/Time/Time.cpp, core/libs/prx/libkernel/Time/TimedWait.cpp, core/libs/prx/libkernel/Time/include/TimedWait.hpp reverted to main and the new tests kept, the suite fails:
    1/1 Test #5085: guest_timed_wait_cpu .............   Passed    0.83 sec
    100% tests passed, 0 tests failed out of 1
    
    Restoring the change makes it pass again.
  • Code reading:
    • Verified Windows timer calibration in CalibratedTimerLateNanos() (core/libs/prx/libkernel/Time/TimedWait.cpp:125-143), checking handle creation/cleanup, 1 ms relative due times, underflow protection on elapsed < CALIBRATION_WAIT_NANOS, and clamping to MAX_TIMER_LATE_NANOS.
    • Verified moving-average update and lead computation in RecordTimerLate() and LeadNanos() (core/libs/prx/libkernel/Time/TimedWait.cpp:150-160), checking thread-local LastWakeNanos() capture in AlertableWait() before APC draining, unsigned underflow guards, and cap at 1/8 of remaining wait duration.
    • Verified integration across WaitEventUntil(), SleepUntil(), and SleepNanosUnlessChanged() (core/libs/prx/libkernel/Time/TimedWait.cpp:291-310, 645-656, 693-710), confirming timer lateness is only recorded when the waitable timer itself fires and not on event wakeups or fallback sleeps.
    • Verified cross-platform LP64/LLP64 type safety and non-Windows fallback in TimerLateNanos() (core/libs/prx/libkernel/Time/TimedWait.cpp:608-614) and startup logging in core/libs/prx/libkernel/Time/Time.cpp:152-153.
    • Verified Windows deadline overshoot test TestDeadlinesWithLateHostTimer() in core/libs/tests/GuestTimedWaitCpu.cpp:185-235, checking resource cleanup (timer, mutex, cond) and verification of both scePthreadCondTimedwait and sceKernelUsleep.
  • Minor: please drop the Generated with footer from the description; the AI-assisted checkbox can stay.

Looks Good To Me

@github-actions github-actions Bot added the review queue Next in the maintainer review queue: checks pass, no open change request, no conflict label Nov 15, 2026
@oneandonlydean
oneandonlydean merged commit 7a1311e into boykopovar:main Nov 17, 2026
14 checks passed
@github-actions github-actions Bot removed the review queue Next in the maintainer review queue: checks pass, no open change request, no conflict label Nov 17, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

libkernel unblocks title Names a title ID on the Unblocks line

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants