fix(libkernel): retain and reuse Linux guest thread stacks #7838

Merged
MarcZX10 merged 10 commits from upstream-pr/7838 into main 2026-10-24 11:30:05 +00:00
MarcZX10 commented 2026-10-19 10:07:47 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-10-19T10:07:47Z.


What

Implements the Linux follow-up from #7700. Joined guest thread stacks and stacks reaped after detached threads remain mapped after completion and can be reused by later threads with the same mapping size. The cache is bounded to 1/1024 of detected physical RAM, clamped to 4–64 MiB; adding a mapping beyond that limit evicts the oldest cached mappings. Before a finished stack enters the cache, Linux discards its usable pages with MADV_DONTNEED while retaining the virtual mapping and guard; if page discard fails, that mapping is unmapped instead of cached. Reuse restores read/write access and reapplies the no-access guard; if a fresh mapping fails, cached finished stacks are released before retrying.

Tested

Rebased onto upstream main b85d972f42 at PR head 76a9900450. On that exact head, guest_pthread_stack passed 5/5 on Linux x86_64 (i7-13700K, Ubuntu 24.04, GCC 13.3, Release), and all 27 ^guest_pthread tests passed 3/3 with -j4. The guest_pthread_stack_tests target also builds with GCC 12.2/Ninja on this Xeon E5-1620 v2, but its CTest run aborts before assertions at the project CPU guard (missing LZCNT, BMI1/2, MOVBE, AVX2 and FMA). GCC syntax-only, git diff --check, and conventions pass.

  • Earlier before/after RSS comparison (Ubuntu 24.04, Ryzen 9 9950X, GCC 13.3, Release), implementation head 4efaf651804f65b6e41f62266aa513a121b70abd (before the later MADV_DONTNEED and detached-stack test changes): the then-current guest_pthread_stack passed 3/3. Using the same temporary measurement fixture against main ancestor e004d03ceb460c5b802b7905a8a88a2a3db26b46 and this PR, 17 joined stack sizes from 4–20 MiB across three rounds measured peak RSS of 25.3–25.8 MiB on the ancestor and 82.0–82.6 MiB on this PR; after each round the PR remained around 48.5 MiB RSS. The cache cap on that host is 60.4 MiB. Evictions unmap cached mappings, the unmap observer confirms no host-only stack registration remains, and the eviction log appears once per process. With a temporary unlimited cap, the same workload retained about 223.6 MiB and failed the expected-unmap assertion. This cap bounds cached mappings, not total process RSS or concurrent live stacks. No title or GPU run was performed.
  • A supported Linux run of head a45b29feda found the residency assertion used an unaligned mincore range; commit c07bfab494 rounded the queried range to page boundaries. On supported Linux, c07bfab494 then passed the residency check but failed the marker assertions because cached pages are intentionally zeroed by MADV_DONTNEED. Commit 49b47f9711 now verifies the worker writes the marker while live, then verifies after exit that the mapping remains registered/readable/writable and the marker page is zero. The final detached-stack assertion change was later covered by the exact-head supported-host run above.
  • Current host is an Intel Xeon E5-1620 v2. The exact guest_pthread_stack_tests target builds, but guest_pthread_stack aborts before assertions because the CPU lacks LZCNT, BMI1/2, MOVBE, AVX2 and FMA. Current GuestPthreadStack.cpp passes GCC syntax-only; git diff --check and python3 tools/check_conventions.py --base upstream/main pass.
  • On exact head d472eda748, a supported-host rerun found detached stack pages still contained their marker immediately after the host thread exited. Detached stacks are retired first and reaped at the next guest-thread creation; commit 76a9900450 moves the page-discard assertions after the existing detached-reuse creation, which triggers that reap. The updated test is covered by the exact-head supported-host run above.
  • Earlier Windows focused tests on head ece11f830 passed 3/3 each for guest_pthread_guard_size, guest_pthread_attr, guest_pthread_attr_stack and guest_pthread_stack; those are unrelated guard-size tests and do not validate this Linux cache change.
  • python3 tools/pr_overlap.py --branch codex/linux-thread-stack-reuse-7700 reported shared files it could not compare for #3986, #5021, #6044, #6879, #7149, #7201 and #7332. Manual patch review found distinct platform/features: signal masks, Windows stack handling, WebAssembly and macOS support, test organization, and AOT. No other PR implements the bounded Linux spare-stack cache; shared Thread.cpp and test paths may need coordination if those PRs merge first.

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; this Linux follow-up does not fix the Windows report in #7700
  • Unblocks: none
  • GPUs tested: n/a
  • AI-assisted: yes
<!-- greyfinch-sync:boykopovar/AnyPS5:issue:4919280106 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/7838). Originally posted by [MarcZX10](https://github.com/MarcZX10) on 2026-10-19T10:07:47Z. --- ### What Implements the Linux follow-up from #7700. Joined guest thread stacks and stacks reaped after detached threads remain mapped after completion and can be reused by later threads with the same mapping size. The cache is bounded to 1/1024 of detected physical RAM, clamped to 4–64 MiB; adding a mapping beyond that limit evicts the oldest cached mappings. Before a finished stack enters the cache, Linux discards its usable pages with `MADV_DONTNEED` while retaining the virtual mapping and guard; if page discard fails, that mapping is unmapped instead of cached. Reuse restores read/write access and reapplies the no-access guard; if a fresh mapping fails, cached finished stacks are released before retrying. ### Tested Rebased onto upstream `main` `b85d972f42` at PR head `76a9900450`. On that exact head, `guest_pthread_stack` passed 5/5 on Linux x86_64 (i7-13700K, Ubuntu 24.04, GCC 13.3, Release), and all 27 `^guest_pthread` tests passed 3/3 with `-j4`. The `guest_pthread_stack_tests` target also builds with GCC 12.2/Ninja on this Xeon E5-1620 v2, but its CTest run aborts before assertions at the project CPU guard (missing LZCNT, BMI1/2, MOVBE, AVX2 and FMA). GCC syntax-only, `git diff --check`, and conventions pass. - Earlier before/after RSS comparison (Ubuntu 24.04, Ryzen 9 9950X, GCC 13.3, Release), implementation head `4efaf651804f65b6e41f62266aa513a121b70abd` (before the later `MADV_DONTNEED` and detached-stack test changes): the then-current `guest_pthread_stack` passed 3/3. Using the same temporary measurement fixture against main ancestor `e004d03ceb460c5b802b7905a8a88a2a3db26b46` and this PR, 17 joined stack sizes from 4–20 MiB across three rounds measured peak RSS of 25.3–25.8 MiB on the ancestor and 82.0–82.6 MiB on this PR; after each round the PR remained around 48.5 MiB RSS. The cache cap on that host is 60.4 MiB. Evictions unmap cached mappings, the unmap observer confirms no host-only stack registration remains, and the eviction log appears once per process. With a temporary unlimited cap, the same workload retained about 223.6 MiB and failed the expected-unmap assertion. This cap bounds cached mappings, not total process RSS or concurrent live stacks. No title or GPU run was performed. - A supported Linux run of head `a45b29feda` found the residency assertion used an unaligned `mincore` range; commit `c07bfab494` rounded the queried range to page boundaries. On supported Linux, `c07bfab494` then passed the residency check but failed the marker assertions because cached pages are intentionally zeroed by `MADV_DONTNEED`. Commit `49b47f9711` now verifies the worker writes the marker while live, then verifies after exit that the mapping remains registered/readable/writable and the marker page is zero. The final detached-stack assertion change was later covered by the exact-head supported-host run above. - Current host is an Intel Xeon E5-1620 v2. The exact `guest_pthread_stack_tests` target builds, but `guest_pthread_stack` aborts before assertions because the CPU lacks LZCNT, BMI1/2, MOVBE, AVX2 and FMA. Current `GuestPthreadStack.cpp` passes GCC syntax-only; `git diff --check` and `python3 tools/check_conventions.py --base upstream/main` pass. - On exact head `d472eda748`, a supported-host rerun found detached stack pages still contained their marker immediately after the host thread exited. Detached stacks are retired first and reaped at the next guest-thread creation; commit `76a9900450` moves the page-discard assertions after the existing detached-reuse creation, which triggers that reap. The updated test is covered by the exact-head supported-host run above. - Earlier Windows focused tests on head `ece11f830` passed 3/3 each for `guest_pthread_guard_size`, `guest_pthread_attr`, `guest_pthread_attr_stack` and `guest_pthread_stack`; those are unrelated guard-size tests and do not validate this Linux cache change. - `python3 tools/pr_overlap.py --branch codex/linux-thread-stack-reuse-7700` reported shared files it could not compare for #3986, #5021, #6044, #6879, #7149, #7201 and #7332. Manual patch review found distinct platform/features: signal masks, Windows stack handling, WebAssembly and macOS support, test organization, and AOT. No other PR implements the bounded Linux spare-stack cache; shared `Thread.cpp` and test paths may need coordination if those PRs merge first. ### 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 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; this Linux follow-up does not fix the Windows report in #7700 - [x] Unblocks: none - [x] GPUs tested: n/a - [x] AI-assisted: yes
jotitadev commented 2026-10-19 11:10:05 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by jotitadev on 2026-10-19T11:10:05Z.

Review: COMMENTED


Ran this on Linux with the unmodified binary, since the container in Tested couldn't run it.

Exact head 916bdb06a6d3801da4700829d90fefff09b79d97, merged on main 674c25388. Linux x86_64, i7-8700 (AVX2/BMI2), Ubuntu 26.04, GCC 15.2, CMake 4.2.3, Ninja, Release, BUILD_TESTING=ON, full build.

  • guest_pthread_stack passes, 50 of 50 serial runs. The 42 pthread|thread tests pass, 5 rounds at -j6.
  • Before: the new GuestPthreadStack.cpp built against main aborts, as expected, since the stacks are not retained there.
  • Full non-GPU suite: 776/776, same as main.
  • 8 parallel copies of guest_pthread_stack_tests × 25 rounds: 0/200 failures.
  • In-process stress (temporary test, not in the PR): 6 guest threads each create 300 children with stack sizes 64/80/128 KiB, half joined and half detached, 3 rounds = 5400 threads. Each child checks that its stack doesn't overlap the stack of any other live child, checks that GuestAllocationsLookup reports it read/write, then fills 4 KiB at the deep end, sleeps 50–250 µs and checks the fill is still there. 5 of 5 runs passed. /proc/self/maps stays at about 145–153 lines from round to round (about 90–97 on main), and RSS is about 0.6 MB above main, so the spare list does not keep growing with this pattern.

The PR drops the old test's unmap observer (GuestThreadStackHostRangeOverlaps at unmap time). Unmapping now only happens in ReleaseSpareStacks and on the failed-reprotect path, and the new test doesn't reach either one.

Written with AI assistance (Claude Code). I ran the builds and tests above on my machine.

<!-- greyfinch-sync:boykopovar/AnyPS5:review:5570663684 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/7838#pullrequestreview-5570663684). Originally posted by [jotitadev](https://github.com/jotitadev) on 2026-10-19T11:10:05Z. **Review:** COMMENTED --- Ran this on Linux with the unmodified binary, since the container in Tested couldn't run it. Exact head `916bdb06a6d3801da4700829d90fefff09b79d97`, merged on `main` `674c25388`. Linux x86_64, i7-8700 (AVX2/BMI2), Ubuntu 26.04, GCC 15.2, CMake 4.2.3, Ninja, Release, `BUILD_TESTING=ON`, full build. - `guest_pthread_stack` passes, 50 of 50 serial runs. The 42 `pthread|thread` tests pass, 5 rounds at `-j6`. - Before: the new `GuestPthreadStack.cpp` built against `main` aborts, as expected, since the stacks are not retained there. - Full non-GPU suite: 776/776, same as `main`. - 8 parallel copies of `guest_pthread_stack_tests` × 25 rounds: 0/200 failures. - In-process stress (temporary test, not in the PR): 6 guest threads each create 300 children with stack sizes 64/80/128 KiB, half joined and half detached, 3 rounds = 5400 threads. Each child checks that its stack doesn't overlap the stack of any other live child, checks that `GuestAllocationsLookup` reports it read/write, then fills 4 KiB at the deep end, sleeps 50–250 µs and checks the fill is still there. 5 of 5 runs passed. `/proc/self/maps` stays at about 145–153 lines from round to round (about 90–97 on `main`), and RSS is about 0.6 MB above `main`, so the spare list does not keep growing with this pattern. The PR drops the old test's unmap observer (`GuestThreadStackHostRangeOverlaps` at unmap time). Unmapping now only happens in `ReleaseSpareStacks` and on the failed-reprotect path, and the new test doesn't reach either one. Written with AI assistance (Claude Code). I ran the builds and tests above on my machine.
simonbbby commented 2026-10-19 12:28:40 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by simonbbby on 2026-10-19T12:28:40Z.


@jotitadev I exercised the two cleanup paths your review identifies, on exact head 916bdb06a6d3801da4700829d90fefff09b79d97 (without merging another main revision).

Ubuntu 24.04 x86_64, Ryzen 9 9950X, GCC 13.3, Release, BUILD_TESTING=ON. The host CPU check stays intact. This is a native homebrew thread test, with no title or GPU run.

Temporary fault injection was confined to the stack allocator's calls: return a failure before the selected DoMapAnon or spare-stack DoMprotect, then let the existing cleanup/retry code run. Six joined 80 KiB guest threads first leave five cached mappings, covering both the spare list and its unfinished collection batch. I restored the unmap observer's GuestThreadStackHostRangeOverlaps check for every callback.

Each case passed in 3/3 fresh processes:

Injected refusal Observed behavior
First fresh mapping, using a different stack size to miss the spare list Releases all five cached mappings, retries successfully, runs and joins the requested thread
Both fresh mapping attempts Releases all five, then throws scePthreadCreate: cannot map the guest thread stack; the caller's handle remains null
Spare's read/write re-protection Releases that failed spare, allocates a fresh stack, runs and joins the thread
Spare's guard re-protection, after read/write protection succeeded Same successful cleanup/fresh-allocation path

Every unmap callback saw no overlapping host-only stack registration. The five-mapping releases produced 15 callbacks, and the one-mapping releases three: guard piece, writable piece, then whole range. After clearing injection, a further guest thread also ran and joined successfully in every process; its stack was still registered read/write and retained its low-end marker.

Two independent negative controls fail the temporary test: removing ReleaseSpareStacks() from the mapping retry, and omitting DoMunmap for the failed spare. Both lose the required unmap callbacks. These controls check that the failure-path assertions actually execute.

Both edited files are restored byte-for-byte, the checkout is clean at the same head, and the rebuilt, unmodified guest_pthread_stack passes 3/3 again. This covers the joined-stack cleanup paths above; it does not simulate kernel memory pressure, detached-thread races or title behavior, and adds no production test hook or implementation change.

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6267215689 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/7838#issuecomment-6267215689). Originally posted by [simonbbby](https://github.com/simonbbby) on 2026-10-19T12:28:40Z. --- @jotitadev I exercised the two cleanup paths your review identifies, on exact head `916bdb06a6d3801da4700829d90fefff09b79d97` (without merging another main revision). Ubuntu 24.04 x86_64, Ryzen 9 9950X, GCC 13.3, Release, `BUILD_TESTING=ON`. The host CPU check stays intact. This is a native homebrew thread test, with no title or GPU run. Temporary fault injection was confined to the stack allocator's calls: return a failure before the selected `DoMapAnon` or spare-stack `DoMprotect`, then let the existing cleanup/retry code run. Six joined 80 KiB guest threads first leave five cached mappings, covering both the spare list and its unfinished collection batch. I restored the unmap observer's `GuestThreadStackHostRangeOverlaps` check for every callback. Each case passed in **3/3 fresh processes**: | Injected refusal | Observed behavior | |---|---| | First fresh mapping, using a different stack size to miss the spare list | Releases all five cached mappings, retries successfully, runs and joins the requested thread | | Both fresh mapping attempts | Releases all five, then throws `scePthreadCreate: cannot map the guest thread stack`; the caller's handle remains null | | Spare's read/write re-protection | Releases that failed spare, allocates a fresh stack, runs and joins the thread | | Spare's guard re-protection, after read/write protection succeeded | Same successful cleanup/fresh-allocation path | Every unmap callback saw **no overlapping host-only stack registration**. The five-mapping releases produced 15 callbacks, and the one-mapping releases three: guard piece, writable piece, then whole range. After clearing injection, a further guest thread also ran and joined successfully in every process; its stack was still registered read/write and retained its low-end marker. Two independent negative controls fail the temporary test: removing `ReleaseSpareStacks()` from the mapping retry, and omitting `DoMunmap` for the failed spare. Both lose the required unmap callbacks. These controls check that the failure-path assertions actually execute. Both edited files are restored byte-for-byte, the checkout is clean at the same head, and the rebuilt, unmodified `guest_pthread_stack` passes **3/3** again. This covers the joined-stack cleanup paths above; it does not simulate kernel memory pressure, detached-thread races or title behavior, and adds no production test hook or implementation change.
MarcZX10 commented 2026-10-19 16:52:05 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-10-19T16:52:05Z.


Thank you both for the independent Linux validation. The exact-head fault-injection runs cover the fresh-map and spare-stack cleanup paths, and the unmodified binary also passed 50 serial runs, five rounds of the thread tests, and the 776-test non-GPU suite. I understand these are native host tests, not title or GPU validation. I will retain that scope when describing the evidence.

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6272473386 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/7838#issuecomment-6272473386). Originally posted by [MarcZX10](https://github.com/MarcZX10) on 2026-10-19T16:52:05Z. --- Thank you both for the independent Linux validation. The exact-head fault-injection runs cover the fresh-map and spare-stack cleanup paths, and the unmodified binary also passed 50 serial runs, five rounds of the thread tests, and the 776-test non-GPU suite. I understand these are native host tests, not title or GPU validation. I will retain that scope when describing the evidence.
adriadam10 commented 2026-10-19 17:49:18 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by adriadam10 on 2026-10-19T17:49:18Z.

Review: CHANGES_REQUESTED


Thanks for the work, and for the independent Linux runs. Two things block this:

  • core/libs/prx/libkernel/Pthread/src/Thread.cpp:119 (spareStacks) has no bound. Stacks only leave it when a later DoMapAnon fails (ReleaseSpareStacks), and TakeSpareStack matches the exact mapping size, so a stack size that is not requested again stays mapped, with its touched pages resident, for the whole session. Please add a cap (entries or bytes, derived from the host, logging once when hit) and release the pages of cached stacks (e.g. madvise(MADV_DONTNEED) on the usable part) or trim on a size mismatch.
  • No before/after peak RSS on a workload that creates and joins many threads with varied stack sizes. For anything kept alive instead of unmapped, the description needs what bounds it, what frees it and those numbers.

Also, the test drops the GuestThreadStackHostRangeOverlaps / unmap-observer check that guarded the retired-stack host-only pages. Please keep a check that a stack that is really unmapped (cap hit or released) leaves no host-only pages.

<!-- greyfinch-sync:boykopovar/AnyPS5:review:5575503996 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/7838#pullrequestreview-5575503996). Originally posted by [adriadam10](https://github.com/adriadam10) on 2026-10-19T17:49:18Z. **Review:** CHANGES_REQUESTED --- Thanks for the work, and for the independent Linux runs. Two things block this: - `core/libs/prx/libkernel/Pthread/src/Thread.cpp:119` (`spareStacks`) has no bound. Stacks only leave it when a later `DoMapAnon` fails (`ReleaseSpareStacks`), and `TakeSpareStack` matches the exact mapping size, so a stack size that is not requested again stays mapped, with its touched pages resident, for the whole session. Please add a cap (entries or bytes, derived from the host, logging once when hit) and release the pages of cached stacks (e.g. `madvise(MADV_DONTNEED)` on the usable part) or trim on a size mismatch. - No before/after peak RSS on a workload that creates and joins many threads with varied stack sizes. For anything kept alive instead of unmapped, the description needs what bounds it, what frees it and those numbers. Also, the test drops the `GuestThreadStackHostRangeOverlaps` / unmap-observer check that guarded the retired-stack host-only pages. Please keep a check that a stack that is really unmapped (cap hit or released) leaves no host-only pages.
MarcZX10 commented 2026-10-19 19:16:34 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-10-19T19:16:34Z.


I agree the current cache has no bound and can retain touched pages for the process lifetime when stack sizes are not reused. The previous stress result (about 0.6 MB RSS above main) is not a before/after peak-RSS measurement on the requested varied-size create/join workload, and the fault-injection run did not exercise cache eviction. I have not implemented a cap or madvise path yet, so the resource bound and the unmap-observer assertion remain unresolved; I am not claiming this review is addressed. The existing Linux stress results only cover reuse at the exact tested stack sizes.

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6275255228 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/7838#issuecomment-6275255228). Originally posted by [MarcZX10](https://github.com/MarcZX10) on 2026-10-19T19:16:34Z. --- I agree the current cache has no bound and can retain touched pages for the process lifetime when stack sizes are not reused. The previous stress result (about 0.6 MB RSS above main) is not a before/after peak-RSS measurement on the requested varied-size create/join workload, and the fault-injection run did not exercise cache eviction. I have not implemented a cap or `madvise` path yet, so the resource bound and the unmap-observer assertion remain unresolved; I am not claiming this review is addressed. The existing Linux stress results only cover reuse at the exact tested stack sizes.
MarcZX10 commented 2026-10-19 19:23:21 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-10-19T19:23:21Z.


I pushed two commits on current main: ef7f7bd60 caps spareStacks at 1/1024 of detected physical RAM, clamped to 4–64 MiB, evicts oldest mappings over the cap, and logs only on the first eviction. Evicted stacks go through the unmap path. The cache also retains the original contents while a mapping remains cached, so the existing post-exit preservation assertions still apply. 4efaf6518 restores an unmap observer that checks GuestThreadStackHostRangeOverlaps on every callback and adds 17 joined workloads with distinct 4–20 MiB stacks that touch their stack pages, forcing eviction even at the 64 MiB cap.

The focused guest_pthread_stack_tests target builds on Linux, and git diff --check plus python3 tools/check_conventions.py --base upstream/main pass. I ran the focused CTest; it aborts at startup in the project CPU feature check because this Xeon E5-1620 v2 lacks LZCNT, BMI1/2, MOVBE, AVX2, and FMA, before the stack workload runs. I therefore do not have a before/after peak-RSS result from this machine. The added varied-size workload and eviction/unmap assertions need a runtime run on a supported Linux CPU to close that evidence gap.

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6275387741 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/7838#issuecomment-6275387741). Originally posted by [MarcZX10](https://github.com/MarcZX10) on 2026-10-19T19:23:21Z. --- I pushed two commits on current `main`: `ef7f7bd60` caps `spareStacks` at 1/1024 of detected physical RAM, clamped to 4–64 MiB, evicts oldest mappings over the cap, and logs only on the first eviction. Evicted stacks go through the unmap path. The cache also retains the original contents while a mapping remains cached, so the existing post-exit preservation assertions still apply. `4efaf6518` restores an unmap observer that checks `GuestThreadStackHostRangeOverlaps` on every callback and adds 17 joined workloads with distinct 4–20 MiB stacks that touch their stack pages, forcing eviction even at the 64 MiB cap. The focused `guest_pthread_stack_tests` target builds on Linux, and `git diff --check` plus `python3 tools/check_conventions.py --base upstream/main` pass. I ran the focused CTest; it aborts at startup in the project CPU feature check because this Xeon E5-1620 v2 lacks LZCNT, BMI1/2, MOVBE, AVX2, and FMA, before the stack workload runs. I therefore do not have a before/after peak-RSS result from this machine. The added varied-size workload and eviction/unmap assertions need a runtime run on a supported Linux CPU to close that evidence gap.
MarcZX10 commented 2026-10-19 19:26:47 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-10-19T19:26:47Z.


The normal PR workflow skips its Linux job, and the repository’s manual Linux build dispatch returned HTTP 403 (“Must have admin rights to Repository”) for this account. I will not bypass the project CPU guard locally. The latest pushed head builds here, but runtime validation and the requested before/after peak-RSS figures still need a supported Linux host. If someone with access to the project runner can run guest_pthread_stack and measure the varied-size workload on both current main and this head, that would close the remaining evidence gap.

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6275460392 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/7838#issuecomment-6275460392). Originally posted by [MarcZX10](https://github.com/MarcZX10) on 2026-10-19T19:26:47Z. --- The normal PR workflow skips its Linux job, and the repository’s manual Linux build dispatch returned HTTP 403 (“Must have admin rights to Repository”) for this account. I will not bypass the project CPU guard locally. The latest pushed head builds here, but runtime validation and the requested before/after peak-RSS figures still need a supported Linux host. If someone with access to the project runner can run `guest_pthread_stack` and measure the varied-size workload on both current main and this head, that would close the remaining evidence gap.
simonbbby commented 2026-10-19 20:25:46 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by simonbbby on 2026-10-19T20:25:46Z.


Supported-CPU runtime and RSS results for exact head 4efaf651804f65b6e41f62266aa513a121b70abd, addressing the remaining Linux evidence request.

Ubuntu 24.04, kernel 7.0.0-38, Ryzen 9 9950X, GCC 13.3, Release. The CPU feature guard is intact. The unmodified guest_pthread_stack passes, and passes 3/3 fresh executions again after the controls below are restored.

For a like-for-like memory comparison I added a temporary measurement-only mode to the PR fixture, and compiled the same fixture source against:

  • main ancestor e004d03ceb460c5b802b7905a8a88a2a3db26b46;
  • this PR head 4efaf651804f65b6e41f62266aa513a121b70abd.

It invokes the existing Worker for 17 distinct requested stack sizes, 4–20 MiB in 1 MiB steps, creating and joining one thread at a time, for three rounds (51 guest threads/process). Worker descends through the requested stack, touches its frames and checks their contents. This mode omits the PR-only post-exit retention assertions so main can run the identical workload. It retains the unmap observer and its GuestThreadStackHostRangeOverlaps assertion. Three fresh processes per tree:

Measurement main ancestor PR head
Peak RSS, KiB, each process 25924, 26460, 26076 84008, 84548, 84276
Peak RSS, MiB range 25.3–25.8 82.0–82.6
RSS after each round, KiB 6892–6980 48512–48552
Unmap callbacks after rounds 1 / 2 / 3 51 / 102 / 153 45 / 96 / 147

Peaks were read with getrusage(RUSAGE_SELF).ru_maxrss and /proc/self/status VmHWM; they agree in all six normal measurements. On the PR, round-end RSS and the high-water mark stay flat after round 1. Every observed unmap has no host-only stack overlap. The eviction message appears once per process, despite further evictions in rounds 2 and 3.

The host reports 15,839,079 physical pages × 4096 bytes, giving a cache limit of 63,356,316 bytes (60.4 MiB). That is the cached-mapping budget, not a process-RSS ceiling: live stacks and the rest of the process account for the higher transient peak.

Negative control: return size_t::max() from SpareStackLimit, leaving the rest of the PR unchanged. The same workload retains about 223.6 MiB (VmHWM 229016 KiB), records zero unmap callbacks, and fails the measurement mode's required-unmap assertion after round 3. This run used line-buffered stdout to preserve the expected abort's measurements. It confirms the real cap/eviction path is exercised.

All temporary fixture and production changes are restored byte-for-byte, the checkout is clean at the stated head, and the rebuilt stock test passes 3/3. This supplies the varied-size peak-RSS comparison and eviction/unmap evidence. It does not establish a general concurrent/live-thread RSS bound, detached-thread memory-pressure behavior, console batching semantics or NHL 26 behavior; no title was run. Logs and the identical measurement fixture are retained.

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6276562104 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/7838#issuecomment-6276562104). Originally posted by [simonbbby](https://github.com/simonbbby) on 2026-10-19T20:25:46Z. --- Supported-CPU runtime and RSS results for exact head `4efaf651804f65b6e41f62266aa513a121b70abd`, addressing the remaining Linux evidence request. Ubuntu 24.04, kernel 7.0.0-38, Ryzen 9 9950X, GCC 13.3, Release. The CPU feature guard is intact. The unmodified `guest_pthread_stack` passes, and passes **3/3 fresh executions** again after the controls below are restored. For a like-for-like memory comparison I added a temporary measurement-only mode to the PR fixture, and compiled the **same fixture source** against: - main ancestor `e004d03ceb460c5b802b7905a8a88a2a3db26b46`; - this PR head `4efaf651804f65b6e41f62266aa513a121b70abd`. It invokes the existing `Worker` for 17 distinct requested stack sizes, **4–20 MiB in 1 MiB steps**, creating and joining one thread at a time, for three rounds (51 guest threads/process). `Worker` descends through the requested stack, touches its frames and checks their contents. This mode omits the PR-only post-exit retention assertions so main can run the identical workload. It retains the unmap observer and its `GuestThreadStackHostRangeOverlaps` assertion. Three fresh processes per tree: | Measurement | main ancestor | PR head | |---|---|---| | Peak RSS, KiB, each process | 25924, 26460, 26076 | 84008, 84548, 84276 | | Peak RSS, MiB range | 25.3–25.8 | 82.0–82.6 | | RSS after each round, KiB | 6892–6980 | 48512–48552 | | Unmap callbacks after rounds 1 / 2 / 3 | 51 / 102 / 153 | 45 / 96 / 147 | Peaks were read with `getrusage(RUSAGE_SELF).ru_maxrss` and `/proc/self/status` `VmHWM`; they agree in all six normal measurements. On the PR, round-end RSS and the high-water mark stay flat after round 1. Every observed unmap has no host-only stack overlap. The eviction message appears **once per process**, despite further evictions in rounds 2 and 3. The host reports 15,839,079 physical pages × 4096 bytes, giving a cache limit of **63,356,316 bytes (60.4 MiB)**. That is the cached-mapping budget, not a process-RSS ceiling: live stacks and the rest of the process account for the higher transient peak. Negative control: return `size_t::max()` from `SpareStackLimit`, leaving the rest of the PR unchanged. The same workload retains about 223.6 MiB (`VmHWM` 229016 KiB), records zero unmap callbacks, and fails the measurement mode's required-unmap assertion after round 3. This run used line-buffered stdout to preserve the expected abort's measurements. It confirms the real cap/eviction path is exercised. All temporary fixture and production changes are restored byte-for-byte, the checkout is clean at the stated head, and the rebuilt stock test passes 3/3. This supplies the varied-size peak-RSS comparison and eviction/unmap evidence. It does not establish a general concurrent/live-thread RSS bound, detached-thread memory-pressure behavior, console batching semantics or NHL 26 behavior; no title was run. Logs and the identical measurement fixture are retained.
MarcZX10 commented 2026-10-19 20:26:33 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-10-19T20:26:33Z.


Thanks for the supported-CPU run and the controlled measurement. This fills the missing varied-size before/after evidence on exact head 4efaf651804f65b6e41f62266aa513a121b70abd. With 17 stack sizes from 4–20 MiB across three rounds, the main ancestor peaks at 25.3–25.8 MiB RSS, while this PR peaks at 82.0–82.6 MiB; after round 1 the PR remains around 48.5 MiB RSS. The cache cap on that host is 60.4 MiB, and over-cap entries are unmapped; the restored observer confirms no host-only stack overlap on every unmap. The unlimited-cap negative control retains about 223.6 MiB and triggers the expected assertion. I will make the PR description explicit that the cap bounds cached mappings, not total process RSS or concurrent live stacks, and include the measured memory cost. Could you reassess the remaining resource-bound request against this evidence and current head?

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6276577132 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/7838#issuecomment-6276577132). Originally posted by [MarcZX10](https://github.com/MarcZX10) on 2026-10-19T20:26:33Z. --- Thanks for the supported-CPU run and the controlled measurement. This fills the missing varied-size before/after evidence on exact head `4efaf651804f65b6e41f62266aa513a121b70abd`. With 17 stack sizes from 4–20 MiB across three rounds, the main ancestor peaks at 25.3–25.8 MiB RSS, while this PR peaks at 82.0–82.6 MiB; after round 1 the PR remains around 48.5 MiB RSS. The cache cap on that host is 60.4 MiB, and over-cap entries are unmapped; the restored observer confirms no host-only stack overlap on every unmap. The unlimited-cap negative control retains about 223.6 MiB and triggers the expected assertion. I will make the PR description explicit that the cap bounds cached mappings, not total process RSS or concurrent live stacks, and include the measured memory cost. Could you reassess the remaining resource-bound request against this evidence and current head?
MarcZX10 commented 2026-10-20 10:26:10 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-10-20T10:26:10Z.


I addressed the remaining cached-page concern in two commits on current head 2d0f8408fb: 6d5c63a8e4 applies MADV_DONTNEED to the usable pages before a finished Linux stack enters the cache (the guard page and virtual mapping remain), and unmaps the stack instead if discard fails; 2d0f8408fb adds a mincore assertion that the 16 MiB joined stack is nonresident after completion. Both changed files pass GCC syntax-only checks with the existing Linux Release flags, and conventions plus git diff --check pass. I could not run the current-head binary here because this Xeon fails the required CPU feature guard. The prior RSS/runtime report is still for 4efaf65180, so it does not validate these two commits. Could you review the page-discard behavior and rerun the focused test on a supported Linux host?

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6288818205 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/7838#issuecomment-6288818205). Originally posted by [MarcZX10](https://github.com/MarcZX10) on 2026-10-20T10:26:10Z. --- I addressed the remaining cached-page concern in two commits on current head `2d0f8408fb`: `6d5c63a8e4` applies `MADV_DONTNEED` to the usable pages before a finished Linux stack enters the cache (the guard page and virtual mapping remain), and unmaps the stack instead if discard fails; `2d0f8408fb` adds a `mincore` assertion that the 16 MiB joined stack is nonresident after completion. Both changed files pass GCC syntax-only checks with the existing Linux Release flags, and conventions plus `git diff --check` pass. I could not run the current-head binary here because this Xeon fails the required CPU feature guard. The prior RSS/runtime report is still for `4efaf65180`, so it does not validate these two commits. Could you review the page-discard behavior and rerun the focused test on a supported Linux host?
MarcZX10 commented 2026-10-20 10:27:13 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-10-20T10:27:13Z.


Correction: I added a third focused test commit, c608e48efb, so the current head is c608e48efb8baea481021c994d4ae5f8b588f7fc. The residency assertion now also accepts mincore returning ENOMEM when the documented madvise fallback unmapped the stack; otherwise it requires every usable page to be nonresident. Both syntax-only checks, conventions and git diff --check pass on this head. Runtime validation is still pending on a supported Linux host.

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6288835330 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/7838#issuecomment-6288835330). Originally posted by [MarcZX10](https://github.com/MarcZX10) on 2026-10-20T10:27:13Z. --- Correction: I added a third focused test commit, `c608e48efb`, so the current head is `c608e48efb8baea481021c994d4ae5f8b588f7fc`. The residency assertion now also accepts `mincore` returning `ENOMEM` when the documented `madvise` fallback unmapped the stack; otherwise it requires every usable page to be nonresident. Both syntax-only checks, conventions and `git diff --check` pass on this head. Runtime validation is still pending on a supported Linux host.
MarcZX10 commented 2026-10-20 10:29:58 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-10-20T10:29:58Z.


I corrected the mincore loop in a45b29feda: scePthreadAttrGetstack returns the usable range after the guard page, so the test now checks residency for every usable page, including index 0. GCC syntax-only checks for the test and Thread.cpp, conventions, and git diff --check pass again. The runtime assertion still needs execution on a supported Linux CPU; hosted build jobs remain skipped.

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6288880219 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/7838#issuecomment-6288880219). Originally posted by [MarcZX10](https://github.com/MarcZX10) on 2026-10-20T10:29:58Z. --- I corrected the `mincore` loop in `a45b29feda`: `scePthreadAttrGetstack` returns the usable range after the guard page, so the test now checks residency for every usable page, including index 0. GCC syntax-only checks for the test and `Thread.cpp`, conventions, and `git diff --check` pass again. The runtime assertion still needs execution on a supported Linux CPU; hosted build jobs remain skipped.
milescoviello commented 2026-10-20 10:49:13 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by milescoviello on 2026-10-20T10:49:13Z.


@MarcZX10 a run of the current head on a supported CPU: Ubuntu 24.04 (Linux 6.8), i7-13700K, GCC 13.3, Release with BUILD_TESTING=ON. Every target ctest -R '^guest_pthread' uses was built at the head a45b29feda and at its merge base e004d03ceb, and each ran 3 times:

  • Base: 27 of 27 pass in all three runs.
  • Head: 26 of 27 pass. guest_pthread_stack aborts in all three runs.

The abort is the new residency check, at Require(errno == ENOMEM). mincore fails with EINVAL, not ENOMEM, because the address it gets isn't page-aligned. With a local print added: mincore errno 22 (Invalid argument) address 0x2006b0040 size 16777216 page 4096. So the usable range scePthreadAttrGetstack reports for the 16 MiB stack starts 0x40 into a page. DiscardFinishedStackPages itself is aligned, since it starts at the mapping base plus GUEST_STACK_GUARD. Only the test's mincore range is off. Rounding lastGuestStack down to the page, and the length up by the same amount, should make the call valid. I haven't changed or rerun it that way.

AI-assisted: yes (Claude Code)

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6289187328 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/7838#issuecomment-6289187328). Originally posted by [milescoviello](https://github.com/milescoviello) on 2026-10-20T10:49:13Z. --- @MarcZX10 a run of the current head on a supported CPU: Ubuntu 24.04 (Linux 6.8), i7-13700K, GCC 13.3, Release with `BUILD_TESTING=ON`. Every target `ctest -R '^guest_pthread'` uses was built at the head `a45b29feda` and at its merge base `e004d03ceb`, and each ran 3 times: - Base: 27 of 27 pass in all three runs. - Head: 26 of 27 pass. `guest_pthread_stack` aborts in all three runs. The abort is the new residency check, at `Require(errno == ENOMEM)`. `mincore` fails with `EINVAL`, not `ENOMEM`, because the address it gets isn't page-aligned. With a local print added: `mincore errno 22 (Invalid argument) address 0x2006b0040 size 16777216 page 4096`. So the usable range `scePthreadAttrGetstack` reports for the 16 MiB stack starts 0x40 into a page. `DiscardFinishedStackPages` itself is aligned, since it starts at the mapping base plus `GUEST_STACK_GUARD`. Only the test's `mincore` range is off. Rounding `lastGuestStack` down to the page, and the length up by the same amount, should make the call valid. I haven't changed or rerun it that way. AI-assisted: yes (Claude Code)
MarcZX10 commented 2026-10-20 17:51:37 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-10-20T17:51:37Z.


I fixed the mincore test failure in commit c07bfab4948592b9102a829d3ab6f65d9c63e5d7: the queried start address is now rounded down to a page boundary and the length is expanded to cover the full usable stack. This addresses the reported EINVAL from an unaligned scePthreadAttrGetstack address. GCC syntax-only, conventions, and git diff --check pass. I could not run the runtime test on this Xeon because it fails the project CPU feature guard, so the focused guest_pthread_stack run on a supported Linux CPU is still needed.

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6297444423 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/7838#issuecomment-6297444423). Originally posted by [MarcZX10](https://github.com/MarcZX10) on 2026-10-20T17:51:37Z. --- I fixed the `mincore` test failure in commit `c07bfab4948592b9102a829d3ab6f65d9c63e5d7`: the queried start address is now rounded down to a page boundary and the length is expanded to cover the full usable stack. This addresses the reported `EINVAL` from an unaligned `scePthreadAttrGetstack` address. GCC syntax-only, conventions, and `git diff --check` pass. I could not run the runtime test on this Xeon because it fails the project CPU feature guard, so the focused `guest_pthread_stack` run on a supported Linux CPU is still needed.
milescoviello commented 2026-10-20 18:05:11 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by milescoviello on 2026-10-20T18:05:11Z.


@MarcZX10 I ran c07bfab494 (merge base e004d03ceb) on Ubuntu 24.04, i7-13700K, GCC 13.3, Release. guest_pthread_stack still aborts, 3 of 3, but no longer in the mincore check. The residency loop now runs and every page of the joined stack reads as not resident.

The abort is now in RequireRetained for the first joined probe, at the marker check (line 145). I added a print there locally:

stack=0x201838040 marker=0x20184b040 range=1 readable=1 writable=1 value=0 expected=0x77000000

So the range is still registered and readable/writable, but the marker reads 0. Since 6d5c63a8e4, a finished stack's usable pages are discarded with MADV_DONTNEED before it is cached, and an anonymous private page reads back as zeros after that. So any marker the worker writes can only read 0 after the join or detach. When I changed that one expectation to 0 locally, the next abort was at line 211, the reuse probe's marker after its own join, for the same reason. The detached checks at lines 226 onward have the same pattern.

The marker checks look like they predate the discard: the head measured in the description, 4efaf65180, comes before 6d5c63a8e4. One way to keep their meaning: after the join, expect the marker word to read 0 (that shows the pages were discarded but the mapping stayed), and keep ReusesOneOf as the reuse check, since it compares stack addresses. I'm happy to rerun whichever way you go.

AI-assisted: yes (Claude Code)

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6297705887 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/7838#issuecomment-6297705887). Originally posted by [milescoviello](https://github.com/milescoviello) on 2026-10-20T18:05:11Z. --- @MarcZX10 I ran c07bfab494 (merge base e004d03ceb) on Ubuntu 24.04, i7-13700K, GCC 13.3, Release. `guest_pthread_stack` still aborts, 3 of 3, but no longer in the `mincore` check. The residency loop now runs and every page of the joined stack reads as not resident. The abort is now in `RequireRetained` for the first joined probe, at the marker check (line 145). I added a print there locally: ``` stack=0x201838040 marker=0x20184b040 range=1 readable=1 writable=1 value=0 expected=0x77000000 ``` So the range is still registered and readable/writable, but the marker reads 0. Since 6d5c63a8e4, a finished stack's usable pages are discarded with `MADV_DONTNEED` before it is cached, and an anonymous private page reads back as zeros after that. So any marker the worker writes can only read 0 after the join or detach. When I changed that one expectation to 0 locally, the next abort was at line 211, the reuse probe's marker after its own join, for the same reason. The detached checks at lines 226 onward have the same pattern. The marker checks look like they predate the discard: the head measured in the description, 4efaf65180, comes before 6d5c63a8e4. One way to keep their meaning: after the join, expect the marker word to read 0 (that shows the pages were discarded but the mapping stayed), and keep `ReusesOneOf` as the reuse check, since it compares stack addresses. I'm happy to rerun whichever way you go. AI-assisted: yes (Claude Code)
MarcZX10 commented 2026-10-20 18:10:51 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-10-20T18:10:51Z.


Thanks for the supported-host run and the marker trace. The page-aligned mincore range passes on c07bfab494, and the remaining failure is the expected zeroing from MADV_DONTNEED. In 49b47f9711, I now assert that the worker sees its marker before exit; after join/detach, the test checks that the mapping is still registered and readable/writable while the marker page reads as zero. Reuse is still checked by comparing the stack address with the earlier probes. GCC syntax-only, conventions and git diff --check pass here, but I could not run the emulator tests on this Xeon due to the CPU feature guard. Could you rerun guest_pthread_stack on the supported Linux host to verify this exact head?

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6297815370 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/7838#issuecomment-6297815370). Originally posted by [MarcZX10](https://github.com/MarcZX10) on 2026-10-20T18:10:51Z. --- Thanks for the supported-host run and the marker trace. The page-aligned `mincore` range passes on `c07bfab494`, and the remaining failure is the expected zeroing from `MADV_DONTNEED`. In `49b47f9711`, I now assert that the worker sees its marker before exit; after join/detach, the test checks that the mapping is still registered and readable/writable while the marker page reads as zero. Reuse is still checked by comparing the stack address with the earlier probes. GCC syntax-only, conventions and `git diff --check` pass here, but I could not run the emulator tests on this Xeon due to the CPU feature guard. Could you rerun `guest_pthread_stack` on the supported Linux host to verify this exact head?
MarcZX10 commented 2026-10-20 18:11:30 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-10-20T18:11:30Z.


I rebased #7838 onto current main 8727ddb29e and force-pushed head d472eda748. The rebase was clean and retained only the intended Thread.cpp and stack-test changes. On this head, GCC syntax-only, conventions, and git diff --check pass. The latest supported-host result is still for c07bfab494 (the page-residency check passed, then marker assertions failed); commit 49b47f9711 changes those assertions, and this rebased head has not yet been run on a supported CPU. Could you rerun guest_pthread_stack on d472eda748 when convenient?

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6297828199 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/7838#issuecomment-6297828199). Originally posted by [MarcZX10](https://github.com/MarcZX10) on 2026-10-20T18:11:30Z. --- I rebased #7838 onto current `main` `8727ddb29e` and force-pushed head `d472eda748`. The rebase was clean and retained only the intended `Thread.cpp` and stack-test changes. On this head, GCC syntax-only, conventions, and `git diff --check` pass. The latest supported-host result is still for `c07bfab494` (the page-residency check passed, then marker assertions failed); commit `49b47f9711` changes those assertions, and this rebased head has not yet been run on a supported CPU. Could you rerun `guest_pthread_stack` on `d472eda748` when convenient?
milescoviello commented 2026-10-20 18:25:31 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by milescoviello on 2026-10-20T18:25:31Z.


@MarcZX10 I ran d472eda748 on the same host (i7-13700K, Ubuntu 24.04, GCC 13.3, Release). guest_pthread_stack still aborts, 3 of 3, but the joined half now passes. The abort is in RequireCachedStackDiscarded at the zero check (line 146), for the first detached probe. A local print in that function, the same on all three runs:

requested=81920  stack=0x201838040 value=0 marker=0x77000000   (joined 0..5 and the reuse probe: all read 0)
requested=114688 stack=0x2019d4040 value=0x77300000 marker=0x77300000   (detached 0: its marker is still there)

So by the time WaitForProbe has seen the detached thread's host task leave /proc/self/task, that thread's stack is still mapped, but its pages haven't been discarded yet. The description says detached stacks are reaped later, so the discard probably happens on the reap, not at exit. Either the test needs to trigger or wait for the reap before this check, or the detached path needs to discard at exit like the joined one. The joined probes all share stack 0x201838040, so joined reuse works.

AI-assisted: yes (Claude Code)

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6298102857 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/7838#issuecomment-6298102857). Originally posted by [milescoviello](https://github.com/milescoviello) on 2026-10-20T18:25:31Z. --- @MarcZX10 I ran d472eda748 on the same host (i7-13700K, Ubuntu 24.04, GCC 13.3, Release). `guest_pthread_stack` still aborts, 3 of 3, but the joined half now passes. The abort is in `RequireCachedStackDiscarded` at the zero check (line 146), for the first detached probe. A local print in that function, the same on all three runs: ``` requested=81920 stack=0x201838040 value=0 marker=0x77000000 (joined 0..5 and the reuse probe: all read 0) requested=114688 stack=0x2019d4040 value=0x77300000 marker=0x77300000 (detached 0: its marker is still there) ``` So by the time `WaitForProbe` has seen the detached thread's host task leave `/proc/self/task`, that thread's stack is still mapped, but its pages haven't been discarded yet. The description says detached stacks are reaped later, so the discard probably happens on the reap, not at exit. Either the test needs to trigger or wait for the reap before this check, or the detached path needs to discard at exit like the joined one. The joined probes all share stack 0x201838040, so joined reuse works. AI-assisted: yes (Claude Code)
MarcZX10 commented 2026-10-20 18:29:15 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-10-20T18:29:15Z.


Thanks for the supported-host trace on d472eda748. It shows the detached stack is still in retiredStacks after its host task exits; ReapRetiredStacks() runs at the next guest-thread creation. In 76a9900450, I moved the detached page-discard assertions until after the existing detachedReuse thread is created and joined, which triggers that reap. The test now checks the detached mappings after the same cleanup path the implementation uses. I rebased onto current main b85d972f42; GCC syntax-only, conventions and git diff --check pass. I haven't run the updated test on a supported host; please rerun when convenient.

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6298175192 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/7838#issuecomment-6298175192). Originally posted by [MarcZX10](https://github.com/MarcZX10) on 2026-10-20T18:29:15Z. --- Thanks for the supported-host trace on `d472eda748`. It shows the detached stack is still in `retiredStacks` after its host task exits; `ReapRetiredStacks()` runs at the next guest-thread creation. In `76a9900450`, I moved the detached page-discard assertions until after the existing `detachedReuse` thread is created and joined, which triggers that reap. The test now checks the detached mappings after the same cleanup path the implementation uses. I rebased onto current `main` `b85d972f42`; GCC syntax-only, conventions and `git diff --check` pass. I haven't run the updated test on a supported host; please rerun when convenient.
MarcZX10 commented 2026-10-20 18:31:56 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-10-20T18:31:56Z.


Validation update for exact head 76a9900450: the guest_pthread_stack_tests target builds in the Linux GCC 12.2/Ninja build. CTest starts guest_pthread_stack but this host's Xeon E5-1620 v2 aborts at the project's CPU guard before assertions (missing LZCNT, BMI1/2, MOVBE, AVX2 and FMA). I updated the description; the supported-host runtime result is still pending.

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6298237689 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/7838#issuecomment-6298237689). Originally posted by [MarcZX10](https://github.com/MarcZX10) on 2026-10-20T18:31:56Z. --- Validation update for exact head `76a9900450`: the `guest_pthread_stack_tests` target builds in the Linux GCC 12.2/Ninja build. CTest starts `guest_pthread_stack` but this host's Xeon E5-1620 v2 aborts at the project's CPU guard before assertions (missing LZCNT, BMI1/2, MOVBE, AVX2 and FMA). I updated the description; the supported-host runtime result is still pending.
MarcZX10 commented 2026-10-20 18:45:15 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-10-20T18:45:15Z.


Update against the review: current head 76a9900450 bounds the cache to 1/1024 of physical RAM, clamped to 4–64 MiB, evicts oldest mappings over the cap, and uses MADV_DONTNEED on usable pages before caching (unmapping if discard fails). The test now cycles through 4–20 MiB stack sizes to force evictions and retains the unmap observer that checks no host-only stack range remains at unmap time. GCC syntax-only, conventions and git diff --check pass on this head.

The available peak-RSS comparison is from 4efaf65180, before the MADV_DONTNEED change: 25.3–25.8 MiB on its main ancestor versus 82.0–82.6 MiB peak on that implementation, settling around 48.5 MiB with a 60.4 MiB cache cap. I am not treating that as exact-current-head evidence. The exact-head supported-CPU rerun is still pending; this Xeon stops at the project CPU guard before the test body.

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6298513268 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/7838#issuecomment-6298513268). Originally posted by [MarcZX10](https://github.com/MarcZX10) on 2026-10-20T18:45:15Z. --- Update against the review: current head `76a9900450` bounds the cache to 1/1024 of physical RAM, clamped to 4–64 MiB, evicts oldest mappings over the cap, and uses `MADV_DONTNEED` on usable pages before caching (unmapping if discard fails). The test now cycles through 4–20 MiB stack sizes to force evictions and retains the unmap observer that checks no host-only stack range remains at unmap time. GCC syntax-only, conventions and `git diff --check` pass on this head. The available peak-RSS comparison is from `4efaf65180`, before the `MADV_DONTNEED` change: 25.3–25.8 MiB on its main ancestor versus 82.0–82.6 MiB peak on that implementation, settling around 48.5 MiB with a 60.4 MiB cache cap. I am not treating that as exact-current-head evidence. The exact-head supported-CPU rerun is still pending; this Xeon stops at the project CPU guard before the test body.
milescoviello commented 2026-10-20 18:48:21 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by milescoviello on 2026-10-20T18:48:21Z.


@MarcZX10 76a9900450 passes on the same host (i7-13700K, Ubuntu 24.04, GCC 13.3, Release). guest_pthread_stack passes 5 of 5, and all 27 ^guest_pthread tests pass 3 of 3 with -j4.

AI-assisted: yes (Claude Code)

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6298572993 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/7838#issuecomment-6298572993). Originally posted by [milescoviello](https://github.com/milescoviello) on 2026-10-20T18:48:21Z. --- @MarcZX10 76a9900450 passes on the same host (i7-13700K, Ubuntu 24.04, GCC 13.3, Release). `guest_pthread_stack` passes 5 of 5, and all 27 `^guest_pthread` tests pass 3 of 3 with `-j4`. AI-assisted: yes (Claude Code)
MarcZX10 commented 2026-10-20 19:19:28 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-10-20T19:19:28Z.


@milescoviello, thanks for validating exact head 76a9900450; the 5/5 stack test and 27 pthread tests across three rounds close the supported-host runtime gap. I updated the description to distinguish that exact-head result from the older RSS measurements. The earlier peak-RSS comparison predates MADV_DONTNEED; if you have capacity, could you rerun the same varied-stack RSS fixture on 76a9900450 and its main ancestor? That would answer the remaining reviewer question about the final cache’s residency.

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6299250955 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/7838#issuecomment-6299250955). Originally posted by [MarcZX10](https://github.com/MarcZX10) on 2026-10-20T19:19:28Z. --- @milescoviello, thanks for validating exact head `76a9900450`; the 5/5 stack test and 27 pthread tests across three rounds close the supported-host runtime gap. I updated the description to distinguish that exact-head result from the older RSS measurements. The earlier peak-RSS comparison predates `MADV_DONTNEED`; if you have capacity, could you rerun the same varied-stack RSS fixture on `76a9900450` and its main ancestor? That would answer the remaining reviewer question about the final cache’s residency.
MarcZX10 commented 2026-10-20 19:20:03 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-10-20T19:20:03Z.


@adriadam10, the exact current head 76a9900450 now has supported-host coverage: guest_pthread_stack passes 5/5 and all 27 ^guest_pthread tests pass 3/3 with -j4. That run includes the cache bound, page discard, eviction path and retained unmap observer. I updated the PR description with this result. It separately labels the existing before/after RSS numbers as pre-MADV_DONTNEED; I requested an exact-head RSS rerun to fill that remaining measurement gap.

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6299264533 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/7838#issuecomment-6299264533). Originally posted by [MarcZX10](https://github.com/MarcZX10) on 2026-10-20T19:20:03Z. --- @adriadam10, the exact current head `76a9900450` now has supported-host coverage: `guest_pthread_stack` passes 5/5 and all 27 `^guest_pthread` tests pass 3/3 with `-j4`. That run includes the cache bound, page discard, eviction path and retained unmap observer. I updated the PR description with this result. It separately labels the existing before/after RSS numbers as pre-`MADV_DONTNEED`; I requested an exact-head RSS rerun to fill that remaining measurement gap.
MarcZX10 commented 2026-10-20 20:40:49 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-10-20T20:40:49Z.


The current PR head now addresses the bounded-cache and page-residency points: the cache is capped at 1/1024 physical RAM clamped to 4–64 MiB, MADV_DONTNEED drops usable pages before caching, failed discards unmap instead, eviction/release unregisters mappings, and the description reports the earlier before/after RSS measurements and their limits. It also restores an unmap observer for evicted mappings; latest commits adjust detached-thread reaping before that assertion. The supported-host exact-head test report is in the PR description. Could you recheck the current head against the earlier requested cap/residency/unmap concerns?

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6301001817 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/7838#issuecomment-6301001817). Originally posted by [MarcZX10](https://github.com/MarcZX10) on 2026-10-20T20:40:49Z. --- The current PR head now addresses the bounded-cache and page-residency points: the cache is capped at 1/1024 physical RAM clamped to 4–64 MiB, `MADV_DONTNEED` drops usable pages before caching, failed discards unmap instead, eviction/release unregisters mappings, and the description reports the earlier before/after RSS measurements and their limits. It also restores an unmap observer for evicted mappings; latest commits adjust detached-thread reaping before that assertion. The supported-host exact-head test report is in the PR description. Could you recheck the current head against the earlier requested cap/residency/unmap concerns?
MarcZX10 commented 2026-10-20 21:01:09 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-10-20T21:01:09Z.


@adriadam10, could you reassess your CHANGES_REQUESTED review against exact current head 76a990045048c71e0effdaf107239061865506fa?

The latest diff now has the requested cache cap (1/1024 physical RAM, clamped to 4–64 MiB), MADV_DONTNEED before caching with unmap-on-discard-failure, oldest-first eviction through the unmap path, and the unmap observer. The PR description reports guest_pthread_stack 5/5 and all 27 pthread tests 3/3 on a supported Linux host at this exact head. It keeps the older varied-size RSS comparison explicitly labeled as pre-MADV_DONTNEED, so that measurement is not presented as final-head evidence. The Xeon here cannot run past the CPU guard.

Please let us know whether the current implementation and exact-head runtime report resolve the cap/residency/unmap concerns, or whether you still see a specific gap (including whether exact-head RSS is still required).

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6301391079 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/7838#issuecomment-6301391079). Originally posted by [MarcZX10](https://github.com/MarcZX10) on 2026-10-20T21:01:09Z. --- @adriadam10, could you reassess your `CHANGES_REQUESTED` review against exact current head `76a990045048c71e0effdaf107239061865506fa`? The latest diff now has the requested cache cap (1/1024 physical RAM, clamped to 4–64 MiB), `MADV_DONTNEED` before caching with unmap-on-discard-failure, oldest-first eviction through the unmap path, and the unmap observer. The PR description reports `guest_pthread_stack` 5/5 and all 27 pthread tests 3/3 on a supported Linux host at this exact head. It keeps the older varied-size RSS comparison explicitly labeled as pre-`MADV_DONTNEED`, so that measurement is not presented as final-head evidence. The Xeon here cannot run past the CPU guard. Please let us know whether the current implementation and exact-head runtime report resolve the cap/residency/unmap concerns, or whether you still see a specific gap (including whether exact-head RSS is still required).
MarcZX10 commented 2026-10-20 22:39:58 +00:00 (Migrated from github.com)

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


Thanks for the blocking review. Current head 76a990045048c71e0effdaf107239061865506fa now caps the spare-stack cache at clamp(physical memory / 1024, 4 MiB, 64 MiB), discards usable pages with MADV_DONTNEED, releases mappings when the cap is exceeded, and retains the host-only-range unmap observer in the test. The latest Linux report has guest_pthread_stack passing 5/5 and the 27 ^guest_pthread tests passing 3/3 with -j4. I still don’t have a before/after peak-RSS measurement; does the explicit cache bound plus page-discard behavior and current test coverage resolve the requested memory concern, or do you still need those measurements?

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6303374954 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/7838#issuecomment-6303374954). Originally posted by [MarcZX10](https://github.com/MarcZX10) on 2026-10-20T22:39:58Z. --- Thanks for the blocking review. Current head `76a990045048c71e0effdaf107239061865506fa` now caps the spare-stack cache at `clamp(physical memory / 1024, 4 MiB, 64 MiB)`, discards usable pages with `MADV_DONTNEED`, releases mappings when the cap is exceeded, and retains the host-only-range unmap observer in the test. The latest Linux report has `guest_pthread_stack` passing 5/5 and the 27 `^guest_pthread` tests passing 3/3 with `-j4`. I still don’t have a before/after peak-RSS measurement; does the explicit cache bound plus page-discard behavior and current test coverage resolve the requested memory concern, or do you still need those measurements?
milescoviello commented 2026-10-20 23:04:33 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by milescoviello on 2026-10-20T23:04:33Z.


@MarcZX10 @adriadam10 here are before/after peak-RSS numbers for the exact head 76a9900450 against its merge base b85d972f42. The workload creates and joins many threads with varied stack sizes. It's a local test program linked like guest_pthread_stack_tests, not part of the PR; the source is below. Setup: i7-13700K, 32 GB (so the cache limit is 32 MiB), Ubuntu 24.04 (Linux 6.8), GCC 13.3, Release, 3 runs per side.

The phases run in this order:

  1. varied: 4000 threads, 8 at a time, each joined. Stack sizes cycle through 20 sizes from 16 KiB to 16 MiB, and each thread writes to every page of its usable stack.
  2. one-off: 400 threads, one at a time, with 400 different sizes (64 KiB + n × 16 KiB). No size is requested twice.
  3. detached: 1000 threads, 8 at a time, each detached, with the same 20 sizes, then a 500 ms sleep.
  4. final: 8 joined 16 KiB threads, then the last reading.
from /proc/self/status base b85d972f42 head 76a9900450
VmRSS at start 5.3 MiB 5.3 MiB
VmHWM after varied 35.5–36.0 MiB 35.6–36.4 MiB
VmRSS after varied and after one-off 5.6–5.7 MiB 5.6–5.7 MiB
VmRSS after detached + 500 ms 40.2–51.7 MiB 39.7–40.2 MiB
VmHWM over the whole run 45.5–51.7 MiB 43.0–52.8 MiB
VmRSS at the end 5.7–5.8 MiB 5.7–5.8 MiB
varied phase time 2258–2339 ms 2219–2273 ms
  • At every phase, the head's RSS is within the base's run-to-run spread.
  • After the joined phases, and at the end, RSS is back to the starting level plus about 0.4 MiB on both sides. So the cached stacks hold no resident pages, even after 400 sizes that are never requested again.
  • Each head run printed scePthread: spare stack cache reached its host-memory limit; releasing cached mappings once. No base run did.
  • The whole-run peak moves by up to about 10 MiB between runs on both sides. It comes from the detached phase, while exited threads' stacks wait to be reaped.

Not measured:

  • The cache's own virtual size. VmSize includes the guest address-space reservation (about 968 GiB), so 32 MiB doesn't show.
  • Create/join time without touching the stacks. With every page written, both sides take the same time.
  • Other hosts or memory sizes.
Workload source (GuestPthreadStackRss.cpp), built with add_test_executable and linked to libkernel libc as in libkernel/CMakeLists.txt, run as guest_pthread_stack_rss_bench 500 8 100
#include "SceTypes.hpp"
#include <chrono>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cstddef>
#include <cstdint>
#include <fstream>
#include <string>
#include <thread>
#include <vector>

extern "C" {
int APS5_VABI scePthreadCreate(Pthread* thread, const PthreadAttr* attr, PthreadEntry entry, void* arg, const char* name);
int APS5_VABI scePthreadJoin(Pthread thread, void** retval);
int APS5_VABI scePthreadAttrInit(PthreadAttr* attr);
int APS5_VABI scePthreadAttrDestroy(PthreadAttr* attr);
int APS5_VABI scePthreadAttrGet(Pthread thread, PthreadAttr* attr);
int APS5_VABI scePthreadAttrSetstacksize(PthreadAttr* attr, std::size_t stackSize);
int APS5_VABI scePthreadAttrGetstack(const PthreadAttr* attr, void** stackAddress, std::size_t* stackSize);
int APS5_VABI scePthreadDetach(Pthread thread);
Pthread APS5_VABI scePthreadSelf();
}

static void Require(bool value) { if (!value) std::abort(); }

static std::size_t touchFraction = 100;

static void* APS5_VABI Worker(void*) {
    PthreadAttr attr = nullptr;
    Require(scePthreadAttrInit(&attr) == 0);
    Require(scePthreadAttrGet(scePthreadSelf(), &attr) == 0);
    void* address = nullptr;
    std::size_t size = 0;
    Require(scePthreadAttrGetstack(&attr, &address, &size) == 0);
    Require(scePthreadAttrDestroy(&attr) == 0);
    auto* bytes = static_cast<volatile unsigned char*>(address);
    const auto here = reinterpret_cast<std::uintptr_t>(&size);
    const auto begin = reinterpret_cast<std::uintptr_t>(address);
    const auto span = (here - begin) * touchFraction / 100;
    const auto floor = here - span;
    for (auto at = here - here % 4096 - 4096; at >= floor + 8192 && at > begin; at -= 4096) bytes[at - begin] = 1;
    return nullptr;
}

static long Status(const char* key) {
    std::ifstream in("/proc/self/status");
    std::string line;
    const auto length = std::strlen(key);
    while (std::getline(in, line))
        if (line.compare(0, length, key) == 0) return std::strtol(line.c_str() + length + 1, nullptr, 10);
    return -1;
}

static void Report(const char* phase, std::chrono::steady_clock::time_point start, unsigned threads) {
    const auto ms = std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - start).count();
    std::printf("RSSBENCH %-10s threads %5u  %8.1f ms  VmRSS %7ld kB  VmHWM %7ld kB  VmSize %8ld kB\n", phase, threads, ms, Status("VmRSS:"), Status("VmHWM:"), Status("VmSize:"));
    std::fflush(stdout);
}

static Pthread Start(std::size_t stackSize) {
    PthreadAttr attr = nullptr;
    Require(scePthreadAttrInit(&attr) == 0);
    Require(scePthreadAttrSetstacksize(&attr, stackSize) == 0);
    Pthread thread = nullptr;
    Require(scePthreadCreate(&thread, &attr, Worker, nullptr, nullptr) == 0);
    Require(scePthreadAttrDestroy(&attr) == 0);
    return thread;
}

int main(int argc, char** argv) {
    const unsigned rounds = argc > 1 ? std::strtoul(argv[1], nullptr, 10) : 500;
    const unsigned batch = argc > 2 ? std::strtoul(argv[2], nullptr, 10) : 8;
    touchFraction = argc > 3 ? std::strtoul(argv[3], nullptr, 10) : 100;
    static constexpr std::size_t Sizes[] = {16384, 32768, 49152, 65536, 98304, 131072, 196608, 262144, 393216, 524288,
                                            786432, 1u << 20, 1536u << 10, 2u << 20, 3u << 20, 4u << 20, 6u << 20, 8u << 20, 12u << 20, 16u << 20};
    constexpr unsigned SizeCount = sizeof(Sizes) / sizeof(Sizes[0]);
    auto start = std::chrono::steady_clock::now();
    Report("start", start, 0);
    unsigned created = 0;
    std::vector<Pthread> threads;
    for (unsigned round = 0; round < rounds; ++round) {
        threads.clear();
        for (unsigned i = 0; i < batch; ++i) threads.push_back(Start(Sizes[(round * batch + i) * 7 % SizeCount]));
        for (auto thread : threads) Require(scePthreadJoin(thread, nullptr) == 0);
        created += batch;
    }
    Report("varied", start, created);
    start = std::chrono::steady_clock::now();
    for (unsigned i = 0; i < 400; ++i) {
        const auto thread = Start((64u << 10) + i * 16384u);
        Require(scePthreadJoin(thread, nullptr) == 0);
    }
    Report("one-off", start, 400);
    start = std::chrono::steady_clock::now();
    for (unsigned round = 0; round < rounds / 4; ++round) {
        for (unsigned i = 0; i < batch; ++i) Require(scePthreadDetach(Start(Sizes[(round * batch + i) * 3 % SizeCount])) == 0);
        std::this_thread::sleep_for(std::chrono::milliseconds(2));
    }
    std::this_thread::sleep_for(std::chrono::milliseconds(500));
    Report("detached", start, rounds / 4 * batch);
    for (unsigned i = 0; i < 8; ++i) Require(scePthreadJoin(Start(16384), nullptr) == 0);
    Report("final", start, 8);
    return 0;
}

AI-assisted: yes (Claude Code)

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6303754839 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/7838#issuecomment-6303754839). Originally posted by [milescoviello](https://github.com/milescoviello) on 2026-10-20T23:04:33Z. --- @MarcZX10 @adriadam10 here are before/after peak-RSS numbers for the exact head 76a9900450 against its merge base b85d972f42. The workload creates and joins many threads with varied stack sizes. It's a local test program linked like `guest_pthread_stack_tests`, not part of the PR; the source is below. Setup: i7-13700K, 32 GB (so the cache limit is 32 MiB), Ubuntu 24.04 (Linux 6.8), GCC 13.3, Release, 3 runs per side. The phases run in this order: 1. **varied:** 4000 threads, 8 at a time, each joined. Stack sizes cycle through 20 sizes from 16 KiB to 16 MiB, and each thread writes to every page of its usable stack. 2. **one-off:** 400 threads, one at a time, with 400 different sizes (64 KiB + n × 16 KiB). No size is requested twice. 3. **detached:** 1000 threads, 8 at a time, each detached, with the same 20 sizes, then a 500 ms sleep. 4. **final:** 8 joined 16 KiB threads, then the last reading. | from `/proc/self/status` | base b85d972f42 | head 76a9900450 | |---|---|---| | VmRSS at start | 5.3 MiB | 5.3 MiB | | VmHWM after varied | 35.5–36.0 MiB | 35.6–36.4 MiB | | VmRSS after varied and after one-off | 5.6–5.7 MiB | 5.6–5.7 MiB | | VmRSS after detached + 500 ms | 40.2–51.7 MiB | 39.7–40.2 MiB | | VmHWM over the whole run | 45.5–51.7 MiB | 43.0–52.8 MiB | | VmRSS at the end | 5.7–5.8 MiB | 5.7–5.8 MiB | | varied phase time | 2258–2339 ms | 2219–2273 ms | - At every phase, the head's RSS is within the base's run-to-run spread. - After the joined phases, and at the end, RSS is back to the starting level plus about 0.4 MiB on both sides. So the cached stacks hold no resident pages, even after 400 sizes that are never requested again. - Each head run printed `scePthread: spare stack cache reached its host-memory limit; releasing cached mappings` once. No base run did. - The whole-run peak moves by up to about 10 MiB between runs on both sides. It comes from the detached phase, while exited threads' stacks wait to be reaped. Not measured: - The cache's own virtual size. `VmSize` includes the guest address-space reservation (about 968 GiB), so 32 MiB doesn't show. - Create/join time without touching the stacks. With every page written, both sides take the same time. - Other hosts or memory sizes. <details><summary>Workload source (GuestPthreadStackRss.cpp), built with <code>add_test_executable</code> and linked to <code>libkernel libc</code> as in <code>libkernel/CMakeLists.txt</code>, run as <code>guest_pthread_stack_rss_bench 500 8 100</code></summary> ```cpp #include "SceTypes.hpp" #include <chrono> #include <cstdio> #include <cstdlib> #include <cstring> #include <cstddef> #include <cstdint> #include <fstream> #include <string> #include <thread> #include <vector> extern "C" { int APS5_VABI scePthreadCreate(Pthread* thread, const PthreadAttr* attr, PthreadEntry entry, void* arg, const char* name); int APS5_VABI scePthreadJoin(Pthread thread, void** retval); int APS5_VABI scePthreadAttrInit(PthreadAttr* attr); int APS5_VABI scePthreadAttrDestroy(PthreadAttr* attr); int APS5_VABI scePthreadAttrGet(Pthread thread, PthreadAttr* attr); int APS5_VABI scePthreadAttrSetstacksize(PthreadAttr* attr, std::size_t stackSize); int APS5_VABI scePthreadAttrGetstack(const PthreadAttr* attr, void** stackAddress, std::size_t* stackSize); int APS5_VABI scePthreadDetach(Pthread thread); Pthread APS5_VABI scePthreadSelf(); } static void Require(bool value) { if (!value) std::abort(); } static std::size_t touchFraction = 100; static void* APS5_VABI Worker(void*) { PthreadAttr attr = nullptr; Require(scePthreadAttrInit(&attr) == 0); Require(scePthreadAttrGet(scePthreadSelf(), &attr) == 0); void* address = nullptr; std::size_t size = 0; Require(scePthreadAttrGetstack(&attr, &address, &size) == 0); Require(scePthreadAttrDestroy(&attr) == 0); auto* bytes = static_cast<volatile unsigned char*>(address); const auto here = reinterpret_cast<std::uintptr_t>(&size); const auto begin = reinterpret_cast<std::uintptr_t>(address); const auto span = (here - begin) * touchFraction / 100; const auto floor = here - span; for (auto at = here - here % 4096 - 4096; at >= floor + 8192 && at > begin; at -= 4096) bytes[at - begin] = 1; return nullptr; } static long Status(const char* key) { std::ifstream in("/proc/self/status"); std::string line; const auto length = std::strlen(key); while (std::getline(in, line)) if (line.compare(0, length, key) == 0) return std::strtol(line.c_str() + length + 1, nullptr, 10); return -1; } static void Report(const char* phase, std::chrono::steady_clock::time_point start, unsigned threads) { const auto ms = std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - start).count(); std::printf("RSSBENCH %-10s threads %5u %8.1f ms VmRSS %7ld kB VmHWM %7ld kB VmSize %8ld kB\n", phase, threads, ms, Status("VmRSS:"), Status("VmHWM:"), Status("VmSize:")); std::fflush(stdout); } static Pthread Start(std::size_t stackSize) { PthreadAttr attr = nullptr; Require(scePthreadAttrInit(&attr) == 0); Require(scePthreadAttrSetstacksize(&attr, stackSize) == 0); Pthread thread = nullptr; Require(scePthreadCreate(&thread, &attr, Worker, nullptr, nullptr) == 0); Require(scePthreadAttrDestroy(&attr) == 0); return thread; } int main(int argc, char** argv) { const unsigned rounds = argc > 1 ? std::strtoul(argv[1], nullptr, 10) : 500; const unsigned batch = argc > 2 ? std::strtoul(argv[2], nullptr, 10) : 8; touchFraction = argc > 3 ? std::strtoul(argv[3], nullptr, 10) : 100; static constexpr std::size_t Sizes[] = {16384, 32768, 49152, 65536, 98304, 131072, 196608, 262144, 393216, 524288, 786432, 1u << 20, 1536u << 10, 2u << 20, 3u << 20, 4u << 20, 6u << 20, 8u << 20, 12u << 20, 16u << 20}; constexpr unsigned SizeCount = sizeof(Sizes) / sizeof(Sizes[0]); auto start = std::chrono::steady_clock::now(); Report("start", start, 0); unsigned created = 0; std::vector<Pthread> threads; for (unsigned round = 0; round < rounds; ++round) { threads.clear(); for (unsigned i = 0; i < batch; ++i) threads.push_back(Start(Sizes[(round * batch + i) * 7 % SizeCount])); for (auto thread : threads) Require(scePthreadJoin(thread, nullptr) == 0); created += batch; } Report("varied", start, created); start = std::chrono::steady_clock::now(); for (unsigned i = 0; i < 400; ++i) { const auto thread = Start((64u << 10) + i * 16384u); Require(scePthreadJoin(thread, nullptr) == 0); } Report("one-off", start, 400); start = std::chrono::steady_clock::now(); for (unsigned round = 0; round < rounds / 4; ++round) { for (unsigned i = 0; i < batch; ++i) Require(scePthreadDetach(Start(Sizes[(round * batch + i) * 3 % SizeCount])) == 0); std::this_thread::sleep_for(std::chrono::milliseconds(2)); } std::this_thread::sleep_for(std::chrono::milliseconds(500)); Report("detached", start, rounds / 4 * batch); for (unsigned i = 0; i < 8; ++i) Require(scePthreadJoin(Start(16384), nullptr) == 0); Report("final", start, 8); return 0; } ``` </details> AI-assisted: yes (Claude Code)
MarcZX10 commented 2026-10-20 23:13:14 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-10-20T23:13:14Z.


Thanks, this closes the measurement gap I raised. The exact-head RSS data shows the bounded cache returns resident memory to baseline after joined workloads, handles 400 one-off sizes without retaining resident pages, and keeps the varied joined workload time within the base spread. The detached-phase peak is present on both sides and tracks unreaped thread stacks, so it does not point to cache growth. I consider the memory concern addressed on this host; the unmeasured virtual cache size and other hosts are useful limits to keep in the report.

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6303879846 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/7838#issuecomment-6303879846). Originally posted by [MarcZX10](https://github.com/MarcZX10) on 2026-10-20T23:13:14Z. --- Thanks, this closes the measurement gap I raised. The exact-head RSS data shows the bounded cache returns resident memory to baseline after joined workloads, handles 400 one-off sizes without retaining resident pages, and keeps the varied joined workload time within the base spread. The detached-phase peak is present on both sides and tracks unreaped thread stacks, so it does not point to cache growth. I consider the memory concern addressed on this host; the unmeasured virtual cache size and other hosts are useful limits to keep in the report.
MarcZX10 commented 2026-10-21 00:14:05 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-10-21T00:14:05Z.

Review: COMMENTED


Thanks for adding the exact-head RSS comparison. The bounded cache plus MADV_DONTNEED returns resident memory to baseline after joined workloads and handles the 400 one-off sizes without retained resident pages; the detached-thread peak appears on both base and PR head. That closes the memory concern I raised on this host. The measurements remain specific to the reported Linux machine, and hosted runtime jobs are skipped here.

<!-- greyfinch-sync:boykopovar/AnyPS5:review:5593389300 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/7838#pullrequestreview-5593389300). Originally posted by [MarcZX10](https://github.com/MarcZX10) on 2026-10-21T00:14:05Z. **Review:** COMMENTED --- Thanks for adding the exact-head RSS comparison. The bounded cache plus `MADV_DONTNEED` returns resident memory to baseline after joined workloads and handles the 400 one-off sizes without retained resident pages; the detached-thread peak appears on both base and PR head. That closes the memory concern I raised on this host. The measurements remain specific to the reported Linux machine, and hosted runtime jobs are skipped here.
MarcZX10 commented 2026-10-21 01:43:44 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-10-21T01:43:44Z.


The exact-head RSS report above addresses the requested workload: joined varied-size and 400 one-off-size stacks return RSS to baseline on the capped cache head, and the measured peak is within the base run-to-run range. The detached-thread peak is also present on base and is attributed to unreaped stacks. The retained unmap-observer check is still in the test. Could you recheck the memory and unmap-test points against head 76a9900450 and update the review if these resolve them? I understand the hosted runtime jobs are skipped, and this report is specific to the stated Linux host.

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6305934864 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/7838#issuecomment-6305934864). Originally posted by [MarcZX10](https://github.com/MarcZX10) on 2026-10-21T01:43:44Z. --- The exact-head RSS report above addresses the requested workload: joined varied-size and 400 one-off-size stacks return RSS to baseline on the capped cache head, and the measured peak is within the base run-to-run range. The detached-thread peak is also present on base and is attributed to unreaped stacks. The retained unmap-observer check is still in the test. Could you recheck the memory and unmap-test points against head 76a990045048c71e0effdaf107239061865506fa and update the review if these resolve them? I understand the hosted runtime jobs are skipped, and this report is specific to the stated Linux host.
jotitadev commented 2026-10-22 00:19:00 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by jotitadev on 2026-10-22T00:19:00Z.

Review: COMMENTED


Re-validated on Linux at the new head 76a990045 (I reviewed 916bdb06a earlier; the force-push adds the spare-stack cache's host-memory cap and the discard of a finished stack's pages, with new guest_pthread_stack cases for both).

Machine: Linux x86-64, i7-8700 (AVX2), Ubuntu 26.04, GCC 15.2, Release, BUILD_TESTING=ON. Base: main a6dcea9279, this PR merged with --no-commit on top (only Pthread/src/Thread.cpp and tests/GuestPthreadStack.cpp change).

  • ctest -R '^guest_pthread_stack$' passes with the PR (the reuse and cached-page-discard checks: a joined/detached stack is reused, and RequireCachedStackDiscarded sees the marker cleared and the pages non-resident via mincore).
  • Reverting only Thread.cpp to main and keeping the PR's test, the test aborts (SIGABRT, exit 134): main maps a fresh stack per thread and releases it on exit, so there is no retained cache for the new checks to find.

So the added cache-cap and page-discard code builds and runs on Linux, and the new test fails without it. CI does not run this suite on real hardware and your host can't (no AVX2), so this is a first run of the updated test on Linux x86-64.

Written with AI assistance (Claude Code). I ran the builds and tests above on my machine.

<!-- greyfinch-sync:boykopovar/AnyPS5:review:5607799121 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/7838#pullrequestreview-5607799121). Originally posted by [jotitadev](https://github.com/jotitadev) on 2026-10-22T00:19:00Z. **Review:** COMMENTED --- Re-validated on Linux at the new head `76a990045` (I reviewed `916bdb06a` earlier; the force-push adds the spare-stack cache's host-memory cap and the discard of a finished stack's pages, with new `guest_pthread_stack` cases for both). Machine: Linux x86-64, i7-8700 (AVX2), Ubuntu 26.04, GCC 15.2, Release, `BUILD_TESTING=ON`. Base: `main` `a6dcea9279`, this PR merged with `--no-commit` on top (only `Pthread/src/Thread.cpp` and `tests/GuestPthreadStack.cpp` change). - `ctest -R '^guest_pthread_stack$'` passes with the PR (the reuse and cached-page-discard checks: a joined/detached stack is reused, and `RequireCachedStackDiscarded` sees the marker cleared and the pages non-resident via `mincore`). - Reverting only `Thread.cpp` to `main` and keeping the PR's test, the test aborts (`SIGABRT`, exit 134): `main` maps a fresh stack per thread and releases it on exit, so there is no retained cache for the new checks to find. So the added cache-cap and page-discard code builds and runs on Linux, and the new test fails without it. CI does not run this suite on real hardware and your host can't (no AVX2), so this is a first run of the updated test on Linux x86-64. Written with AI assistance (Claude Code). I ran the builds and tests above on my machine.
milescoviello commented 2026-10-22 00:38:14 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by milescoviello on 2026-10-22T00:38:14Z.


@jotitadev thanks for the re-run at 76a990045. The revert check (PR test with main's Thread.cpp aborting) is the part I couldn't show from the PR alone.

One correction: my host does have AVX2 (i7-13700K), so the suite runs here as well. The before/after RSS numbers above are from that machine. An independent Linux run at the exact head is still useful.

AI-assisted: yes (Claude Code)

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6329799922 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/7838#issuecomment-6329799922). Originally posted by [milescoviello](https://github.com/milescoviello) on 2026-10-22T00:38:14Z. --- @jotitadev thanks for the re-run at `76a990045`. The revert check (PR test with `main`'s `Thread.cpp` aborting) is the part I couldn't show from the PR alone. One correction: my host does have AVX2 (i7-13700K), so the suite runs here as well. The before/after RSS numbers above are from that machine. An independent Linux run at the exact head is still useful. 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!7838
No description provided.