Skip to content

fix(libkernel): answer vm.loadavg with the host's load averages - #12436

Merged
adriadam10 merged 3 commits into
boykopovar:mainfrom
milescoviello:fix/vm-loadavg
Oct 30, 2026
Merged

adriadam10 merged 3 commits into
boykopovar:mainfrom
milescoviello:fix/vm-loadavg

Conversation

@milescoviello

@milescoviello milescoviello commented Oct 28, 2026 •

Copy link
Copy Markdown
Contributor

What

ProsperoCraft (PPSA99874 01.000.117, the catalog's Minecraft Java launcher with a Java 25 runtime) aborts 3 s after start:

terminate called after throwing an instance of 'std::runtime_error'
  what():  sysctl_nid_postfix: unsupported MIB 2.2

MIB {2, 2} is FreeBSD's vm.loadavg (CTL_VM, VM_LOADAVG). The runtime's libjvm.so has its own getloadavg, which os::loadavg jumps to. It is FreeBSD libc's: sysctl({2, 2}, &loadavg, &size) with size 24, then each ldavg[i] / fscale as a double, or -1 if sysctl fails. sysctl here throws for any MIB it doesn't know under a known top-level node, so the title ends there.

How

sysctl {2, 2} now answers like FreeBSD 11.4's read-only node (sysctl_vm_loadavg): the 24-byte struct loadavg, three 32-bit fixed-point averages and an 8-byte fscale. fscale is 2048, FreeBSD's FSCALE (1 << FSHIFT, FSHIFT 11). The averages are the host's 1, 5 and 15 minute loads from getloadavg, rounded to that scale. Windows has no load average, so there they are 0.

  • A write returns EPERM, as FreeBSD's sysctl_root does for a node without CTLFLAG_WR. A short buffer gets ENOMEM through the existing CopyOut.
  • {2, 2, n} returns ENOTDIR, like the other leaves (IsLeafMib).
  • sysctlbyname("vm.loadavg") and sysctlnametomib("vm.loadavg") map to {2, 2}.

What the console returns was not measured, so docs/dev/debt/libkernel.md gets a vm.loadavg entry under Unknown function info that says so, next to kern.boottime.

Tested

Linux (Ubuntu 26.04.1, GCC 15.2), on main 750cf6cf48:

  • New case in guest_system_configuration: the size query by MIB and by name gives 24; a read gives fscale 2048 and, off Windows, averages within 1.0 of the host's getloadavg; the by-name read matches; sysctlnametomib writes {2, 2} and nothing past it; a write returns EPERM; {2, 2, 0} returns ENOTDIR. errno is kept on success. It passes 3 of 3 (ef9c7a06a5). The test alone on main (60da3ec100) fails: sysctl_nid_postfix: unsupported MIB 2.2.
  • Review fix (ea0b9c1272, from ebosido444-ai's review): the answer's 4 padding bytes after ldavg are now zero, and each scaled average is clamped to UINT32_MAX before the conversion. The test checks that the padding is 0, and that every ldavg value is exactly host * 2048 + 0.5 for the host averages read just before or just after the call. That replaces the earlier ±1.0 bound. It passes 3 of 3, and all 942 ^guest_ tests pass at ea0b9c1272. The exact check catches a wrong scale, but not a lost + 0.5 on glibc: getloadavg there divides the kernel's 11-bit fixed-point loads, so every host load × 2048 is a whole number, and rounding and truncation agree (XairRrR's mutation run).
  • Area: all 942 ^guest_ tests pass at ea0b9c1272. The head 20d8e0c35d adds only a debt entry line: the averages are also 0 when getloadavg returns fewer than 3 (XairRrR's review).
  • ProsperoCraft (PPSA99874 01.000.117), release libraries of this head, 120 s with pad input: it gets past the sysctl call. The JVM then stops on its own a moment later: Native memory allocation (mprotect) failed to protect 49152 bytes. Error detail: memory to guard stack pages (stackOverflow.cpp:113). Its primordial thread runs on the host process's main stack (stack(0x00007ffe107c1000,0x00007ffe10fbf000) in its hs_err file), which guest mprotect doesn't cover. That is a separate stop. With this PR, fix(linux): enter the guest entry on a main stack at the console's address #7532 (hugodearaujo, the guest entry on a main stack at the console's address) and fix(libkernel): start thread stacks on a 16 KiB page boundary on Linux #9684 (NevesHenry, 16 KiB-aligned thread stacks) merged together (27e6cd782a), ProsperoCraft runs the full 120 s: its Instances screen, new-instance form and on-screen keyboard follow the input (#7532, #9684).
  • Windows 11 VM (WinLibs GCC 15.2, Release): guest_system_configuration passes 3 of 3 at this head (ea0b9c1272) and on main 750cf6cf48.

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: PPSA99874 Game bring-up: ProsperoCraft (PPSA99874): runs 120 s with #12436, #7532 and #9684 #12710 (ProsperoCraft, past its start-up abort)
  • GPUs tested: n/a
  • AI-assisted: yes

🤖 Generated with Claude Code

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

Copy link
Copy Markdown
Contributor Author

@KernelPanicNT a question for your firmware 10.01 kernel data (#9199), if you have a moment. Is FreeBSD's vm.loadavg there, as number 2 under vm with kind CTLTYPE_STRUCT | CTLFLAG_RD | CTLFLAG_MPSAFE and handler sysctl_vm_loadavg? If it is, what does averunnable.fscale hold? This PR answers it as FreeBSD 11.4 does, with fscale 2048. The debt entry says the console wasn't measured, and your data would settle at least the node and the scale.

AI-assisted: yes (Claude Code)

@MarcZX10

Copy link
Copy Markdown
Contributor

I reviewed head ef9c7a06a5e1. The new {2,2} path is limited to read-only vm.loadavg, and the by-name and name-to-MIB routes map to that same MIB. Its ABI layout is consistent with the FreeBSD 11.4 struct loadavg cited in the PR: three 32-bit fixed-point values followed by a native 64-bit long, giving 24 bytes on the PS5's 64-bit ABI. The code records the console result as unmeasured, while the test checks MIB/by-name length, fscale, host-load proximity, errno preservation, leaf behavior, and write rejection. I found no concrete issue in the diff.

Local git diff --check and the current-main conventions check pass. I did not independently build/run guest_system_configuration in this session; the PR describes Linux and Windows runs. Hosted conventions, eligibility, intake, labels and report checks were pending, so this is a COMMENTED review, not an approval.

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

I reviewed the exact head ef9c7a06a5 and compared the new vm.loadavg path with the documented FreeBSD struct loadavg layout: three 32-bit fixed-point values followed by 64-bit fscale, with MIB/name conversion and read-only handling routed through existing sysctl helpers. The added test covers size query, host values, by-name parity, errno preservation, trailing MIB components, and writes. I found no concrete issue in the changed path. Hosted conventions and Windows checks pass; the PR body reports the Linux 942-test suite and Windows focused suite, which I could not independently rerun here because this checkout's full CMake configuration is missing SDL2/XRandR support.

@github-actions

github-actions Bot commented Oct 28, 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 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 7135 docs/dev/debt/libkernel.md
PR 7149 docs/dev/debt/libkernel.md
PR 7192 docs/dev/debt/libkernel.md
PR 7447 docs/dev/debt/libkernel.md
PR 7464 docs/dev/debt/libkernel.md
PR 7509 docs/dev/debt/libkernel.md
PR 7804 docs/dev/debt/libkernel.md
PR 8605 docs/dev/debt/libkernel.md
PR 9156 docs/dev/debt/libkernel.md
PR 9242 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 9326 docs/dev/debt/libkernel.md
PR 9389 docs/dev/debt/libkernel.md
PR 9557 docs/dev/debt/libkernel.md
PR 9566 docs/dev/debt/libkernel.md
PR 9843 docs/dev/debt/libkernel.md
PR 10442 docs/dev/debt/libkernel.md
PR 10552 docs/dev/debt/libkernel.md
PR 10645 docs/dev/debt/libkernel.md
PR 11002 docs/dev/debt/libkernel.md
PR 11215 docs/dev/debt/libkernel.md
PR 11625 docs/dev/debt/libkernel.md
PR 11827 docs/dev/debt/libkernel.md
PR 11939 docs/dev/debt/libkernel.md
PR 12104 docs/dev/debt/libkernel.md
PR 12560 docs/dev/debt/libkernel.md
PR 12688 docs/dev/debt/libkernel.md
PR 12700 docs/dev/debt/libkernel.md
PR 12741 docs/dev/debt/libkernel.md
PR 12965 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.

Approved at exact head ef9c7a06a5. I reviewed the vm.loadavg path against the documented FreeBSD 11.4 layout (three 32-bit fixed-point values plus 64-bit fscale), verified the {2,2} and vm.loadavg mappings, read-only EPERM handling, and the trailing-component leaf behavior. The added tests cover size query, by-name parity, fscale/host values, errno preservation, name-to-MIB output, writes, and trailing components. Hosted Windows, conventions, eligibility, intake, labels, and report checks pass. The PR reports the Linux 942-test suite and ProsperoCraft run; I did not independently rerun those locally. Console loadavg behavior remains explicitly documented as unmeasured.

@ebosido444-ai

Copy link
Copy Markdown
Contributor

The conversion arithmetic is right (fscale 2048, + 0.5 rounding); two ways it can still report the wrong number.

  1. core/libs/prx/libkernel/System/src/SystemConfiguration.cpp:122 — static_cast<std::uint32_t>(averages[index] * static_cast<double>(load.fscale) + 0.5) is unclamped. A load of 2097152.0 or more exceeds UINT32_MAX after scaling, and a floating-to-integer conversion whose value is out of range is undefined, so the field wraps: a host load of 2097152 reports 0.000, i.e. idle. Clamping to UINT32_MAX before the cast keeps the answer monotonic.

  2. SystemConfiguration.cpp:118 with :115 — GuestLoadAverage load{{0, 0, 0}, 1 << 11} initializes ldavg and fscale, and the static_assert(sizeof(GuestLoadAverage) == 24) confirms the struct is 12 bytes of ldavg, 4 bytes of padding, then fscale. The braced initializer leaves the padding indeterminate, and CopyOut(&load, sizeof(load), …) at :412 copies all 24 bytes, so the guest reads four uninitialized stack bytes that change between calls. Zero-initialize the object (GuestLoadAverage load{}; then assign the members) so the padding is deterministic.

Neither is observable through the loose test bound at core/libs/tests/GuestSystemConfiguration.cpp:537, which accepts anything within ±1.0 of the host value: 1.0 → 2048 and 0.75 → 1536 as exact bits would catch a lost + 0.5 and a doubled scale, which that tolerance cannot.

GuestLoadAverage's braced initializer left its four bytes of padding after ldavg indeterminate, and the sysctl copies all 24 bytes to the guest. The scaled value of a load over UINT32_MAX / 2048 was converted out of range. The test now checks the padding and the exact fscale 2048 scaling against the host averages read just before and after the call.

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

Copy link
Copy Markdown
Contributor Author

@ebosido444-ai thanks, both are right. ea0b9c1272:

  • zeroes the whole GuestLoadAverage before filling it, so the 4 bytes after ldavg are 0 on every call;
  • converts through ScaledLoad, which clamps to UINT32_MAX (and to 0 for a negative or NaN value) before the cast.

The test now checks both:

  • Bytes 12-15 of the answer must be 0. The sysctl writes into a buffer filled with 0xaa first, but the bytes come from the host struct, so on the old code this check only fails when the stack happened to hold non-zero bytes there.
  • Each ldavg value must equal host * 2048 + 0.5 exactly, for the host averages read just before or just after the call. That catches a lost + 0.5 or a doubled scale.

The clamp isn't reachable through the sysctl on a real host, so no test covers it.

Tested at ea0b9c1272: guest_system_configuration passes 3 of 3 on Linux and all 942 ^guest_ tests pass. On the Windows 11 VM it passes 3 of 3 at the head and on its main base 750cf6cf48.

AI-assisted: yes (Claude Code)

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

Reviewed — approved

The vm.loadavg answer merges cleanly, builds, and guest_system_configuration passes on the merged tree and fails on main's implementation as it should. One non-blocking point: on current glibc the new exact-value check cannot detect a lost + 0.5.

What I ran

Head ea0b9c12728948765792fd62433a846bfe4b0dc0, merged with --no-ff onto main b433c40f2f46aa2e59e19806010a839ac8572d64 in a clean worktree. Arch Linux 7.2.11-zen, GCC 16.2.1, glibc 2.44, Intel Core i9-14900KF. The build and tests ran in a sandbox with no network.

git merge --no-ff refs/review/12436                      # onto origin/main, no conflicts
git diff --check origin/main...refs/review/12436
python3 tools/check_conventions.py --base origin/main
cmake --build build -j10 --target guest_system_configuration_tests
cmake --build build -j10 --target libs
cmake --build build -j10 --target guest_getrlimit_tests
ctest --test-dir build -R '^guest_system_configuration$' --output-on-failure   # 3 times
ctest --test-dir build -R '^guest_(system_configuration|getrlimit)' --output-on-failure
# negative control: SystemConfiguration.cpp restored from origin/main, test kept from the PR
# mutation: "+ 0.5" removed from ScaledLoad, rebuilt, test rerun
strace ./la    # a 3-line program that calls getloadavg and prints each value * 2048

Results

Check Result
Merge onto main Clean (docs/dev/debt/libkernel.md auto-merged)
git diff --check Clean
check_conventions.py All conventions checks passed
Build guest_system_configuration_tests, libs OK
guest_system_configuration Passed, 3 of 3 runs (0.03 s each)
guest_getrlimit (the other test that uses sysctl) Passed
Negative control (main's SystemConfiguration.cpp) Fails as expected: sysctl_nid_postfix: unsupported MIB 2.2
Mutation: drop + 0.5 in ScaledLoad Test still passes (see the non-blocking finding below)
Negative control output
terminate called after throwing an instance of 'std::runtime_error'
  what():  sysctl_nid_postfix: unsupported MIB 2.2
Why the rounding mutation survives: glibc 2.44 getloadavg
sysinfo({uptime=224727, loads=[1321376, 871456, 753664], ...}) = 0

getloadavg makes one sysinfo call and returns loads[i] / 65536.0. Linux keeps the load averages with 11 fractional bits and shifts them left by 5 for sysinfo, so every load × 2048 is an exact integer (1321376 / 32 = 41293). In six separate runs of the program, every printed load × 2048 was a whole number, for example 41427.0000 26281.0000 23170.0000.

Negative control

I restored core/libs/prx/libkernel/System/src/SystemConfiguration.cpp from origin/main, kept the PR's test, and rebuilt. guest_system_configuration aborted with unsupported MIB 2.2, the same failure the description reports. After I restored the merged file, it passed again.

Findings

Blocking

None.

Non-blocking

  1. On Linux, the exact-value check does not detect a lost + 0.5. The reply to ebosido444-ai's review says the exact comparison at GuestSystemConfiguration.cpp:543-544 "catches a lost + 0.5". On this host it does not. I removed + 0.5 from ScaledLoad and the test still passed. glibc 2.44 builds getloadavg from sysinfo, which carries the kernel's 11-bit fixed-point loads (details above). So average * 2048 is always a whole number, and rounding and truncation give the same result. The check still catches a wrong scale, and the conversion itself is correct. The test just cannot observe the rounding through the host. If you want rounding coverage, one option is to test the conversion on fixed inputs such as 1.0003 → 2049 (2048 without the rounding). Another is to drop the claim from the description.
  2. A failing getloadavg gives zeros that look like an idle machine. At SystemConfiguration.cpp:131-132, if getloadavg returns anything but 3, the averages stay 0 and the call succeeds. With glibc's sysinfo path this practically never happens, so it is minor. Throwing there, or listing the case next to the Windows zeros in the debt entry, would match the rule against silent made-up success.

ebosido444-ai's two earlier findings (unclamped conversion, uninitialized padding) are fixed at this head. ScaledLoad clamps to [0, UINT32_MAX] and the struct is zeroed with memset before it is filled. I agree with MarcZX10's reading of the layout: 3 × uint32_t, 4 padding bytes, then an 8-byte fscale, 24 bytes in total, which matches FreeBSD 11.4's struct loadavg on amd64. The write path returns EPERM before anything is copied out, like sysctl_root for a node without CTLFLAG_WR. {2, 2, n} returns ENOTDIR through IsLeafMib.

Not verified

  • Windows build and test (no Windows host here; the PR reports a Windows 11 VM run).
  • ProsperoCraft (PPSA99874): I did not launch any title.
  • The padding check against the old brace-initialised code. As the author notes, it depends on leftover stack contents, so I did not try to reproduce it.
  • What the console returns for vm.loadavg. The debt entry already records it as unmeasured.

…vg's debt entry

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

Copy link
Copy Markdown
Contributor Author

@XairRrR thanks for the mutation run and the strace. You're right on both points:

  1. My reply above overstated what the exact check covers. On glibc, getloadavg gives the kernel's 11-bit fixed-point loads divided out, so host * 2048 is always a whole number. A lost + 0.5 then rounds the same as before, and the test can't see it through the host. The check still catches a wrong scale. I corrected the description and left the conversion as it is; ScaledLoad is a file-local helper, and I'd rather not export it only for this.
  2. A failed getloadavg now has a line in the debt entry next to the Windows zeros: the averages are 0 when it returns fewer than 3 averages, and the call still succeeds. That commit is 20d8e0c35d, docs only. Nothing in the code or the test changed, so the earlier test runs still describe it.

AI-assisted: yes (Claude Code)

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

Re-checked — approved

The only new commit, 20d8e0c35d, adds the failed-getloadavg case to the vm.loadavg debt entry, and the description no longer claims that the exact check catches a lost + 0.5. Both of my earlier non-blocking points are addressed.

What changed since my last review

  • One commit, 20d8e0c35d (docs(libkernel): ...). It changes only docs/dev/debt/libkernel.md. git diff ea0b9c1272..20d8e0c35d shows one line edited in the vm.loadavg entry, and no code, test or build files changed.
  • The description's Tested section now says the exact check catches a wrong scale but not a lost + 0.5 on glibc. It also mentions the new head.
  • The author replied to both points from my last review.

What I ran

Head 20d8e0c35d4088cfed7cd1163b4dee1bc6847eed, merged with --no-ff onto main b433c40f2f46aa2e59e19806010a839ac8572d64 in a clean worktree. No code changed, so I did not rebuild or rerun tests. The build, test, negative control and mutation results from my previous review on ea0b9c1272 still apply to the same code.

git log --oneline ea0b9c1272..refs/review/12436
git diff ea0b9c1272 refs/review/12436
git merge-tree --write-tree origin/main refs/review/12436   # exit 0, no conflicts
git merge --no-ff refs/review/12436                         # onto origin/main, libkernel.md auto-merged
git diff --check origin/main...refs/review/12436            # clean
python3 tools/check_conventions.py --base origin/main       # All conventions checks passed.

Previous findings

  1. Exact-value check cannot see a lost + 0.5 on glibc: Resolved. The author agreed and removed the claim from the description instead of changing the test. That settles the point, because the conversion itself was already correct.
  2. A failing getloadavg gives zeros that look like an idle machine: Resolved. The debt entry now says the averages are 0 when getloadavg returns fewer than 3 and that the call still succeeds. This matches HostLoadAverage at core/libs/prx/libkernel/System/src/SystemConfiguration.cpp:125-135: the struct is zeroed and the averages are filled only when getloadavg(averages, 3) == 3. "Fewer than 3" also covers the -1 error return.

New findings

Blocking

None.

Non-blocking

None.

Not verified

  • I did not rebuild or rerun tests at this head. Only a docs line changed, so the results for ea0b9c1272 carry over.
  • The Windows run and the ProsperoCraft (PPSA99874) run are author-reported. I did not launch any title.
  • What the console returns for vm.loadavg is still unmeasured, as the debt entry records.

@adriadam10
adriadam10 merged commit ec709ce into boykopovar:main Oct 30, 2026
13 of 14 checks passed
@adriadam10

Copy link
Copy Markdown
Collaborator

Checked the {2, 2} / vm.loadavg / sysctlnametomib paths against FreeBSD 11.4's struct loadavg and sysctl_vm_loadavg (24 bytes, fscale 2048, read-only EPERM, ENOTDIR on a trailing component), the zeroed padding and the UINT32_MAX clamp, the new test (it throws on main) and the debt entry; merged.

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

Labels

docs libkernel unblocks title Names a title ID on the Unblocks line

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants