Skip to content

fix(libkernel): measure the TSC frequency on one CPU - #9461

Merged
adriadam10 merged 2 commits into
boykopovar:mainfrom
milescoviello:fix/tsc-calibration-one-cpu
Oct 25, 2026
Merged

adriadam10 merged 2 commits into
boykopovar:mainfrom
milescoviello:fix/tsc-calibration-one-cpu

Conversation

@milescoviello

@milescoviello milescoviello commented Oct 21, 2026 •

Copy link
Copy Markdown
Contributor

What

sceKernelGetTscFrequency (and sceKernelGetCpuFrequency, which returns the same value) measures the TSC rate once per process. It reads the TSC and the monotonic clock, sleeps 20 ms and reads both again. If the thread moves to another CPU during the sleep, the second TSC value comes from another CPU's counter. Where those counters aren't in step, the result is wrong for the rest of the process.

On a Windows 11 VM (KVM, Intel i7-7700 host, 4 vCPUs), vCPU 0's TSC runs about 3.76 billion ticks (about 1.04 s at 3.6 GHz) ahead of vCPUs 1 to 3. I repeated the same 20 ms measurement 12 times there, letting the thread move freely:

  • 10 rounds gave 3.60 GHz;
  • 1 gave 180.4 GHz (the thread moved onto vCPU 0);
  • 1 had a negative tick delta (it moved off vCPU 0), which converts to 0.

On main, guest_current_cpu fails in 6 of 10 runs there, because sceKernelGetCpuFrequency() returns 0. A title that divides by the frequency, or converts TSC deltas to time with it, misbehaves for the whole session.

The calibration now pins its thread to the CPU it is running on, for the 20 ms, and restores the previous affinity afterwards. On Windows that's SetThreadAffinityMask with GetCurrentProcessorNumber; on Linux, sched_getcpu with pthread_setaffinity_np. macOS is unchanged. guest_current_cpu also checks that the frequency lies between 100 MHz and 10 GHz, so the 180 GHz case fails the test as well as 0.

Guest code that runs rdtsc itself still sees the skew on such a host; this only fixes the reported frequency.

If the pin can't be set, the measurement runs unpinned, as on main; the libkernel debt file records that (7cae619, after @MarcZX10's review).

Tested

  • Rebased onto main 110a18b, with no conflicts, as head c8bb2bd31b. guest_current_cpu, guest_system_configuration and the four guest_process_time tests pass 3 of 3 on Linux (Ubuntu 26.04.1, GCC 15.2, Release), and tools/check_conventions.py is clean. The overlap scan's only line-level entry is feat(libkernel): implement __tls_get_addr #9059, which also adds one line at the same place in docs/dev/debt/libkernel.md. Both are additions, so whichever lands second keeps both. The other entries are PRs that already conflict with main. The results below are from the pre-rebase head.

  • Windows 11 VM (above), WinLibs GCC 15.2.0, Release, head c8bb2bd31b against its base main 110a18b, 5 runs each. These three tests were the only aborts (0xc0000409) in a full ctest of main d6732b5 on this VM:

    • guest_system_configuration (machdep.tsc_freq is 0): main fails 5 of 5.
    • guest_current_cpu: main fails 4 of 5.
    • guest_ampr_markers: main fails 3 of 5, at its check that sceAmprCommandBufferWriteAddressFromTimeCounter wrote a nonzero time. That value is sceKernelGetProcessTimeCounter(), which scales the elapsed time by the TSC frequency, so it's 0 when the frequency is.
    • With this change all three pass 5 of 5.
  • Windows 11 VM (above), WinLibs GCC 15.2.0, Release, guest_current_cpu, 10 runs each: main a6dcea9 fails 6 of 10 runs (sceKernelGetCpuFrequency() is 0; main's copy of the test only checks for more than 0). With this change, 10 of 10 pass, the new range check included.

  • Linux (Ubuntu 26.04.1, GCC 15.2, Release), where the TSCs are in step: guest_current_cpu, the 4 guest_process_time* tests and guest_system_configuration pass 3 of 3.

Not tested: macOS (no change there), a bare-metal host with unsynchronized TSCs.

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: none
  • GPUs tested: none needed (libkernel only)
  • AI-assisted: yes (Claude Code)

🤖 Generated with Claude Code

@MarcZX10 MarcZX10 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.

The fix pins the calibration interval to one CPU and restores the original affinity with RAII; I reviewed the Windows and Linux paths and the reported VM reproduction. The new test range also catches both the prior zero reading and the reported implausible high value. The author reports 10/10 Windows VM passes after the change and 3/3 Linux runs across the relevant tests; hosted build/test jobs are all skipped for this path, while eligibility, conventions, intake, labels and report pass. One non-blocking edge case: if either platform’s affinity query/set call fails, the helper silently leaves calibration unpinned and continues with the original potentially cross-CPU measurement. Please consider making that failure path explicit or documenting why it cannot occur on supported hosts.

@milescoviello

Copy link
Copy Markdown
Contributor Author

Thanks @MarcZX10 for the review. On the failure path: the pin always asks for the CPU the thread is already running on, and that CPU is always in its allowed set (the process affinity mask on Windows; the thread's cpuset, including a cgroup's, on Linux). So I don't know of a host where the set fails. If it did, falling back to the unpinned measurement gives the same result main gives today. I documented that fallback in the libkernel debt file (7cae619) instead of adding a retry for a case I can't produce.

AI-assisted: yes (Claude Code)

@github-actions

github-actions Bot commented Oct 21, 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 4630 docs/dev/debt/libkernel.md
PR 5021 core/libs/prx/libkernel/Time/Time.cpp
docs/dev/debt/libkernel.md
PR 6149 docs/dev/debt/libkernel.md
PR 6740 docs/dev/debt/libkernel.md
PR 6830 docs/dev/debt/libkernel.md
PR 6936 docs/dev/debt/libkernel.md
PR 7088 docs/dev/debt/libkernel.md
PR 7105 docs/dev/debt/libkernel.md
PR 7121 docs/dev/debt/libkernel.md
PR 7149 docs/dev/debt/libkernel.md
PR 7192 docs/dev/debt/libkernel.md
PR 7201 core/libs/prx/libkernel/Time/Time.cpp
PR 7447 docs/dev/debt/libkernel.md
PR 7509 docs/dev/debt/libkernel.md
PR 7804 core/libs/prx/libkernel/Time/Time.cpp
docs/dev/debt/libkernel.md
PR 8010 docs/dev/debt/libkernel.md
PR 8520 docs/dev/debt/libkernel.md
PR 8553 docs/dev/debt/libkernel.md
PR 8605 docs/dev/debt/libkernel.md
PR 9187 docs/dev/debt/libkernel.md
PR 9199 docs/dev/debt/libkernel.md
PR 9242 docs/dev/debt/libkernel.md
PR 9284 docs/dev/debt/libkernel.md
PR 9293 docs/dev/debt/libkernel.md
PR 9297 docs/dev/debt/libkernel.md
PR 9302 docs/dev/debt/libkernel.md
PR 9509 docs/dev/debt/libkernel.md
PR 9557 docs/dev/debt/libkernel.md
PR 9566 docs/dev/debt/libkernel.md
PR 9575 docs/dev/debt/libkernel.md
PR 9669 docs/dev/debt/libkernel.md
PR 9684 docs/dev/debt/libkernel.md
PR 9732 docs/dev/debt/libkernel.md
PR 9938 docs/dev/debt/libkernel.md
PR 10061 docs/dev/debt/libkernel.md
PR 10442 docs/dev/debt/libkernel.md
PR 10499 core/libs/prx/libkernel/Time/Time.cpp
docs/dev/debt/libkernel.md
PR 10621 docs/dev/debt/libkernel.md
PR 10767 docs/dev/debt/libkernel.md

@MarcZX10 MarcZX10 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.

The affinity edge case raised in the prior review is now addressed in the debt note, and the author’s updated Windows VM/Linux results are recorded. The checked head still uses base a6dcea927, 47 upstream commits behind current main (110a18ba01). Please rebase/update and rerun the focused CPU-frequency/current-CPU and process-time tests plus conventions and overlap/debt checks on current main. The overlap report has incomplete comparisons in libkernel debt and a Time.cpp warning; please verify those entries remain additive after the update. I did not rerun local tests.

@milescoviello
milescoviello force-pushed the fix/tsc-calibration-one-cpu branch from 7cae619 to c8bb2bd Compare October 22, 2026 04:52
@milescoviello

Copy link
Copy Markdown
Contributor Author

@MarcZX10 rebased onto main 110a18b as c8bb2bd31b, with no conflicts. The focused CPU-frequency, current-CPU and process-time tests pass 3 of 3, and conventions are clean.

On the overlap entries: #9059 adds one line at the same place in docs/dev/debt/libkernel.md that this PR adds one at. Both are additions, so the second to land keeps both. The Time.cpp and other debt-file entries are PRs that already conflict with main, and this PR's Time.cpp change is the one class plus the one line in sceKernelGetTscFrequency. The Tested section names the new head.

AI-assisted: yes (Claude Code)

@milescoviello

Copy link
Copy Markdown
Contributor Author

A full ctest of main on the Windows 11 VM from the description turned up two more tests this fixes: guest_system_configuration and guest_ampr_markers abort there for the same reason as guest_current_cpu. Against this PR's base (main 110a18b), 5 runs each: main fails guest_system_configuration 5 of 5, guest_current_cpu 4 of 5 and guest_ampr_markers 3 of 5. The head c8bb2bd31b passes all three 5 of 5. guest_ampr_markers checks the AMPR time-counter write, which is sceKernelGetProcessTimeCounter(), the elapsed time scaled by the TSC frequency, so it's 0 when the frequency is. Added to Tested.

AI-assisted: yes (Claude Code)

@milescoviello
milescoviello force-pushed the fix/tsc-calibration-one-cpu branch from c8bb2bd to 65e0c25 Compare October 25, 2026 00:23
@milescoviello

Copy link
Copy Markdown
Contributor Author

@MarcZX10 rebased onto current main cf528e7 as you asked; head 65e0c25e17, the same two commits, no conflicts. Linux (Ubuntu 26.04.1, GCC 15.2, Release): the 9 tests matching current_cpu|system_configuration|process_time|ampr (guest_current_cpu, guest_system_configuration, the four guest_process_time* and the three guest_ampr_*) pass 3 of 3. tools/check_conventions.py passes.

Overlap on the new base (tools/pr_overlap.py): the only direct conflict is #9059, which edits docs/dev/debt/libkernel.md at the same line (L130). Both are additions to that section, so keeping both entries resolves it whichever lands first. #4630, #5021 and #6149 conflict with main already, so the tool couldn't compare them. #5021 also touches Time.cpp: its hunks are in the include block, ClockTicksPerSecond, clock_gettime and sceKernelGettimezone. This PR's are an include, a new helper after g_timerSelfTest, and sceKernelReadTsc. So the only nearby edits are the two include additions, a few lines apart.

AI-assisted: yes (Claude Code)

milescoviello and others added 2 commits October 25, 2026 02:24
sceKernelGetTscFrequency times 20 ms of TSC ticks against the monotonic
clock. A thread that moves to another CPU during the sleep reads its end
value from another TSC. Where the TSCs of the CPUs differ, as on a Windows
VM whose vCPU 0 counts about 3.8 billion ticks ahead of the others, the
frequency came out as 0 or as 180 GHz. Pin the calibrating thread to the
CPU it runs on and restore its affinity afterwards.

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

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@milescoviello
milescoviello force-pushed the fix/tsc-calibration-one-cpu branch from 65e0c25 to de5306d Compare October 25, 2026 02:26
@milescoviello

Copy link
Copy Markdown
Contributor Author

@MarcZX10 main moved again and #9059's __tls_get_addr entry landed on the same line of docs/dev/debt/libkernel.md, so I rebased onto d8db8faef5. The new head is de5306dd29, still the same two commits. The only conflict was that debt line, and both entries are kept; the code is unchanged.

  • Linux (Ubuntu 26.04.1, GCC 15.2, Release): the same 9 tests (current_cpu|system_configuration|process_time|ampr) pass 3 of 3.
  • Windows 11 VM (GT 1030, WinLibs GCC 15.2.0, same 9 tests, 3 runs per tree):
    • On the merge base d8db8faef5, guest_current_cpu and guest_system_configuration abort with 0xc0000409: 1, 2 and 2 failures in the three runs.
    • This head passes 9 of 9 each time.
  • tools/check_conventions.py passes.

AI-assisted: yes (Claude Code)

@adriadam10 adriadam10 self-assigned this Oct 25, 2026
@adriadam10
adriadam10 dismissed MarcZX10’s stale review October 25, 2026 14:25

Dismissing a stale review: the requested changes were addressed after it (new head) and the merge queue blocks on it. Please request changes again if anything is still open.

@adriadam10
adriadam10 merged commit e1ef22e into boykopovar:main Oct 25, 2026
10 checks passed
@adriadam10

Copy link
Copy Markdown
Collaborator

Checked the Windows and Linux pin/restore paths, the unpinned fallback (recorded in the libkernel debt file) and the new 100 MHz–10 GHz range check in guest_current_cpu. The rebase and test rerun requested in the earlier review are done on the current head; merged.

@milescoviello

Copy link
Copy Markdown
Contributor Author

Thanks for checking both pin paths and the range check, and for merging, @adriadam10.

AI-assisted: yes (Claude Code)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants