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

Merged
milescoviello merged 2 commits from upstream-pr/9461 into main 2026-10-25 18:48:55 +00:00
milescoviello commented 2026-10-21 22:40:03 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by milescoviello on 2026-10-21T22:40:03Z.


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 (7cae6190d4, after @MarcZX10's review).

Tested

  • Rebased onto main 110a18ba01, 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 #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 110a18ba01, 5 runs each. These three tests were the only aborts (0xc0000409) in a full ctest of main d6732b51a6 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 a6dcea9279 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

<!-- greyfinch-sync:boykopovar/AnyPS5:issue:4959318881 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/9461). Originally posted by [milescoviello](https://github.com/milescoviello) on 2026-10-21T22:40:03Z. --- ### 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 (7cae6190d4, after @MarcZX10's review). ### Tested - **Rebased** onto `main` 110a18ba01, 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 #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` 110a18ba01, 5 runs each. These three tests were the only aborts (0xc0000409) in a full `ctest` of `main` d6732b51a6 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` a6dcea9279 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 <!-- Rules behind each item: https://github.com/boykopovar/AnyPS5/blob/main/CONTRIBUTING.md --> - [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 under Silent stubs in their library's [technical debt](https://github.com/boykopovar/AnyPS5/tree/main/docs/dev/debt) file - [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] Fixes: none - [x] Unblocks: none - [x] GPUs tested: none needed (libkernel only) - [x] AI-assisted: yes (Claude Code) 🤖 Generated with [Claude Code](https://claude.com/claude-code)
MarcZX10 commented 2026-10-21 22:57:39 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-10-21T22:57:39Z.

Review: APPROVED


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.

<!-- greyfinch-sync:boykopovar/AnyPS5:review:5607238754 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/9461#pullrequestreview-5607238754). Originally posted by [MarcZX10](https://github.com/MarcZX10) on 2026-10-21T22:57:39Z. **Review:** APPROVED --- 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 commented 2026-10-21 23:06:38 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by milescoviello on 2026-10-21T23:06:38Z.


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 (7cae6190d4) instead of adding a retry for a case I can't produce.

AI-assisted: yes (Claude Code)

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6328548952 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/9461#issuecomment-6328548952). Originally posted by [milescoviello](https://github.com/milescoviello) on 2026-10-21T23:06:38Z. --- 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 (7cae6190d4) instead of adding a retry for a case I can't produce. AI-assisted: yes (Claude Code)
MarcZX10 commented 2026-10-22 04:34:23 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-10-22T04:34:23Z.

Review: DISMISSED


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.

<!-- greyfinch-sync:boykopovar/AnyPS5:review:5609302222 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/9461#pullrequestreview-5609302222). Originally posted by [MarcZX10](https://github.com/MarcZX10) on 2026-10-22T04:34:23Z. **Review:** DISMISSED --- 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 commented 2026-10-22 04:53:09 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by milescoviello on 2026-10-22T04:53:09Z.


@MarcZX10 rebased onto main 110a18ba01 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)

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6333026399 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/9461#issuecomment-6333026399). Originally posted by [milescoviello](https://github.com/milescoviello) on 2026-10-22T04:53:09Z. --- @MarcZX10 rebased onto `main` 110a18ba01 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 commented 2026-10-22 09:24:24 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by milescoviello on 2026-10-22T09:24:24Z.


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 110a18ba01), 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)

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6337368505 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/9461#issuecomment-6337368505). Originally posted by [milescoviello](https://github.com/milescoviello) on 2026-10-22T09:24:24Z. --- 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` 110a18ba01), 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)
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!9461
No description provided.