fix(libc): optionally reclaim and lazily commit small heap spans #12849
Loading…
Reference in a new issue
No description provided.
Delete branch "upstream-pr/12849"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
Imported from boykopovar/AnyPS5. Originally posted by Bram910 on 2026-10-29T12:36:52Z.
What
On main, a small size class commits a full 1 MiB span on its first allocation and never releases its spans after free. Add the opt-in presence flag
APS5_RECLAIM_SMALL_HEAPto track occupancy and free lists per span, release completely empty excess spans, and retain one warm span per class. Each span reserves 1 MiB but starts with 64 KiB committed; commitment doubles as the bump pointer crosses the committed prefix.With the flag unset, the small-block allocation/free retention path, allocation headers and exported API stay unchanged.
ArenaHeap::Get()now has process lifetime even when the flag is unset: its metadata and large-block-cache containers are no longer destroyed at exit.APS5_RECLAIM_SMALL_HEAPis a presence flag; even0enables it.Safety integration: #11468 has merged and is included through current main
4f41f4c375. Its allocation metadata rejects a second free before span occupancy changes. The newdouble-freefixture leaves another allocation live, rejects a second free, checks accounting and the surviving payload, then frees it; it runs with reclamation both unset and enabled. The former missing-prerequisite warning has been removed from the environment reference and debt entry.On Linux and macOS,
arenaAllocate(SpanBytes, ...)already claims the entire span in the arena's used-range bookkeeping. The initial arena mapping andGuestArenaResetsupply fresh anonymousPROT_NONEpages; lazy growth only needsGuestArenaSetProtection/mprotectto make the next prefix writable. It does not need another used-range claim or a replacement mapping. In particular,MarkUsedForCommitaccepts the original span start but rejects an interior subrange of that existing reservation, so usingGuestArenaCommitfor subsequent growth would conflict with the span's claim. Successfully reset pages are demand-zero when made accessible again. The Windows path continues to useGuestArenaCommit. Reclamation resets the mapping, invalidates guest-allocation caches and releases the arena reservation. Failed growth rolls back the new portion without touching live objects; a cleanup failure quarantines the span. Known gaps and the flag are documented.Draft: a complete, repeated current-main/current-PR title comparison remains outstanding. The historical compatibility-build gameplay pair below is unfavorable and has dropped detailed trace events. Contributor macOS support-branch validation is attributed below. No GTA memory reduction or FPS improvement is claimed. More frequent commit/decommit can hurt throughput or cause stutter; the flag stays off by default.
Tested
Windows 11 Pro 10.0.26200, Ryzen 9 7950X, WinLibs GCC 15.2 UCRT, Release. Rebased onto
5454cd2e455994d992aca39335ce60507eeda1eb. Windows heap suite: 35/35 passed after rebase (log below). Clean original-main baseline: 13/13 existing heap tests passed.Ubuntu 22.04 under WSL, GCC 11.4,
-fsanitize=undefined -fno-sanitize-recover=all: 22/22 focused allocator cases pass, with 20/20 previous-commit controls and no UBSan diagnostic. This directly compiles the actual GuestHeap, GuestArena, GuestAllocations and GuestWriteWatch sources with the fixture; it is not a full Linux libc build. The allocator, fixture and libc CMake sources are byte-identical before and after rebase. Main has not changed GuestHeap, GuestArena, GuestAllocations or GuestWriteWatch between the measured baseline and the rebase target.The fixtures exercise default retention, live objects across spans, randomized reuse, alignment/realignment, zero-size realloc, threads, small/large thresholds, initial and growing commit rollback, invalidation-failure quarantine, allocation leases and disabled write watching. Main fails the reclamation assertion, and the previous allocator fails the sparse-commitment assertion, with candidate passing both.
Synthetic measurements used identical fixture/launcher binaries across each pair and fresh processes in alternating order (baseline/candidate/candidate/baseline/baseline/candidate). All exited normally under a 1 GiB job cap. Every live payload byte was checked. These measure native allocator workloads, not a title.
Commitment is distinct from resident RAM: the sparse result mostly avoids backing commitment for previously untouched pages. The short dense runs show a timing cost and do not establish title frame-time behavior.
Measurement pins: main
ba5b5330b37724bca4b99f30faab504653635a04; previous allocator8368fd23f2dd882023edba86cad340eab9174d36; final geometric-growth candidatef2ab45695767b8c086ca3d06e83ae49725728a8dbefore the source-equivalent rebase. Their rebased equivalents in this PR are5d22a65fa7(first reclamation) andbe5c729ccc(geometric growth). The earlier main/first-reclamation comparison measured 307.375 to 159.297 MiB median peak job commitment. That earlier six-run batch is separate from the later sparse/dense batch; their totals are not added together.Reproduction:
Duplicate search and integration: checked open allocator PRs #11468, #11850, #11870 and #12239. Each merges into the current main, then merges cleanly with this branch in
git merge-treepreviews; no dependency or duplicate implementation was found. The standardtools/pr_overlap.py --branch fix/libc-reclaim-empty-small-spanswas attempted but could not execute becauseghis absent. These direct checks do not replace the complete automated overlap scan.Review follow-up (2026-11-03)
Integrated current main
4f41f4c375, including #11468, with a clean merge. Windows 10.0.26200.9457, Ryzen 9 7950X, WinLibs GCC 15.2 Release: 39/39 focused application/guest heap tests pass after integration, including reclamation enabled/unset double-free and churn cases.check_conventions.py --base origin/mainandgit diff --checkpass.Requested churn measurement: 256 allocations of 4096 payload bytes (1 MiB live payload), write and check every payload byte, free all blocks, repeat. Four warm-up cycles, then 128 timed cycles. Same executable and allocator source with the presence flag unset versus
=1; six fresh-process samples per mode, ABBA order repeated three times,APS5_HEAP_CACHE_MIB=0. This compares the two paths of this branch, rather than claiming a new measurement of an unmodified main executable.Reclamation is 35.3% slower in this small repeated workload. Its one warm span does not eliminate the cost when rounded blocks occupy more than one span. The result reinforces keeping the flag opt-in; it establishes no title frame-time benefit. The previous dense/sparse measurements below remain historical measurements at their explicitly named revisions.
The process-lifetime heap is deliberate for both flag states: exit handlers can allocate after a function-local static heap would have been destroyed. imellag's macOS validation reports base 46/47 versus this PR 69/69 on their named macOS support branch, and
guest_heap_lifetimepassing 3/3 with this PR versus a destroyed-mutex error on base. Those are contributor results on a support branch, not a new local macOS run. The LeakSanitizer results below supersede the earlier untested leak-check status. Heap metadata and retained large-cache containers intentionally remain reachable until process exit.No title exhausting commitment has been demonstrated by this PR. The attempted fresh instrumented GTA diagnostic stopped on its existing low-memory guard before reaching the scene. The older compatibility-build gameplay pair is now audited and disclosed below; it is not a current-main/current-PR performance validation. Original saves and runtime were restored and hash-verified. No repeatable title RAM reduction or FPS improvement is claimed.
Readiness audit: leak check and existing gameplay evidence (2026-11-03)
Decision: retain draft and keep the flag off by default. The existing gameplay pair and the churn measurement do not support recommending reclamation. No new title run was performed for this audit: the available physical memory was about 11.5 GiB against the existing 28 GiB capture admission requirement, and the user chose to use the recorded gameplay evidence for now.
LeakSanitizer
Current head
aad9fecb1312d8a2235465c8466e8c07b41f274c, Ubuntu under WSL, GCC 11.4.0,-std=c++20 -O1 -g -fsanitize=leak. Directly compiled the actualGuestHeap.cpp,GuestArena.cpp,GuestAllocations.cpp,GuestWriteWatch.cppand allocator fixture; this is not a full Linux libc or title build.GuestHeapLifetime.cpp: an exit handler allocates, verifies and frees on a worker thread after the ordinary static-finalization point.LSAN_OPTIONS=exitcode=23was used. A separate deliberate 12,345-byte host allocation leak is detected and exits 23, confirming the checker is active.Historical GTA V opening-room pair
Recorded 2026-10-29, GTA V PPSA04263 01.010.002, stationary prologue opening room at the “Go to the guard” objective. Ryzen 9 7950X, RTX 3080, NVIDIA 610.47, Windows 10.0.26200, guest resolution 3840×2160. Other user workloads remained running.
Control
9b2dc9f49a3ed3f7d513f246032de6d4fdb96c34; candidatef7254105b8df483d53eeb8488112f4e145c84608. This is a compatibility integration, not clean upstream main, and predates the current PR head. Rechecked Git provenance: the two arms differ only in this PR's five files, and the historical candidate'sGuestHeap.cppis byte-identical to published revisionbe5c729ccc.Re-ran the saved-data analysis: GPU/title/version/resolution match, initial cache and save manifests match, and the recorded environment differs only by
APS5_RECLAIM_SMALL_HEAP=1. Both measured runs exited normally with code 0, with no job-cap event or low-memory stop. Logs were not redirected. Original runtime and saves were restored and hash-verified after those runs.In this pair, p50 frame time is 74.3% higher, while median private commit is only 37.219 MiB lower and working set 16.260 MiB lower. This is an unfavorable observation, not a repeatable regression estimate or a demonstrated memory benefit.
Limitations: candidate ran before control; only one pair exists. Both detailed event buffers overflowed (
trace_dropped=true), with the queue-worker buffer filling after 8.282 s for candidate and 7.872 s for control. The available frame summaries cover the named 300:20 window, but detailed timelines are incomplete. The 76 memory samples per arm cover 300–320 s after process resume, while trace time starts at first present. The pair therefore does not supply the complete reverse-order current-main/current-PR comparison needed to qualify readiness.Original recorded frame summaries (both explicitly report dropped trace events)
Private diagnostic command dumps, proprietary binaries, shader caches and saves are not included in this description.
Checklist
main; no other open PR implements the same functionsNotImplemented_nid_no_patch); silent stubs are listed under Silent stubs in their library's technical debt file.mdfiles or images added to the repository (attach them to this PR)Raw protected measurements: final geometric-growth candidate vs previous allocator
Linux focused UBSan cases (22/22)
Previous allocator Linux UBSan controls (20/20)
Sparse negative control on previous allocator
Rebased Windows heap CTest log (35/35)
Imported from boykopovar/AnyPS5. Originally posted by CnRJay on 2026-11-01T19:51:04Z.
Review: COMMENTED
Correction (2026-11-01): the title-ID/log demand below is not a CONTRIBUTING requirement;
Unblocks: noneis allowed. The technical points below are unaffected.Unblocks: none, and the body says outright that the measurements "measure native allocator workloads, not a title". Please name a title that exhausts commitment onmainwith a log line that shows it, otherwise there is nothing to show the flag is needed.tools/trace_digest.pysummaries ofmainand the flag on, same machine and scene, would show it. The 300 MiB to 150.5 MiB result is for a synthetic two-phase fixture.APS5_RECLAIM_SMALL_HEAP=0enables it.ArenaHeap::Get()now has process lifetime "even when the flag is unset", so its metadata and large-block-cache containers are no longer destroyed at exit. That is a behaviour change outside the flag; is it needed for the opt-in path, and what was the leak-check result?GuestArenaReset, which drops and re-faults pages. After a free, a title that allocates the same class a moment later pays a page-fault storm; the retained warm span (one per class) bounds it only for one span. Please include a churn test (alloc/free a 1 MiB working set repeatedly) with timing.Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-11-20T06:55:08Z.
Review: CHANGES_REQUESTED
Reviewed — comments
Changes are required before merge: resolve the rollback and release failure paths so failed cleanup cannot leave span metadata inconsistent.
What I ran
Reviewed head
aad9fecb1312d8a2235465c8466e8c07b41f274cand its prepared diff. No commands or tests were run.Files read:
core/libs/prx/libc/CMakeLists.txt,core/libs/prx/libc/src/GuestHeap.cpp,core/libs/tests/GuestHeapSmallSpans.cpp,docs/dev/ENVIRONMENT.md, anddocs/dev/debt/libc.md. Also readcore/libs/prx/libc/src/GuestArena.cppandcore/libs/prx/libc/src/GuestAllocations.cppfor context. All five changed files were included in the manifest;files.jsonwas unavailable.Results
Findings
Blocking
core/libs/prx/libc/src/GuestHeap.cpp:205: if resetting a failed growth range succeeds but invalidation throws,rollbackSmallquarantines the span without decrementingspan.committedor heap system accounting. A later free of its last live allocation can then runfreeSmall's empty-span path and retain the quarantined span assizeClass.empty; subsequent allocations can reuse its span metadata despitequarantinedbecauseallocateSmalldoes not filter it. This contradicts the stated guarantee that a cleanup failure quarantines the span. Keep quarantined spans out of both allocation and empty-span retention, and make successful reset accounting reflect committed bytes removed.core/libs/prx/libc/src/GuestHeap.cpp:261: on the second empty span, the code unlinks it before reset/invalidation/release, but exceptions from those calls do not mark it quarantined or restore a safe state. A reset or invalidation failure leaves a span with live count zero, still present in the map and no longer available; a release failure occurs after accounting was shrunk and may leave the reservation registered. Handle each cleanup failure consistently and ensure the span cannot be reallocated or retained as the warm empty span.Non-blocking
None.
Not verified
No tests were run. The author reports Windows and Linux allocator test results and contributor macOS validation in the PR description; those results were not independently verified. Physical-console behavior and title performance remain unverified, as the description itself notes. The complete contents of the 1000-line PR description were not read; relevant goal, reported test results, limitations, and gameplay evidence were read. No changed file was excluded according to the manifest.
To get this to a good state
Fix both cleanup paths so a failed reset, invalidation, or release cannot leave a span reusable or accounting inconsistent. Then rerun the allocator test suite, including the quarantine and growth rollback cases, on the new head.
Imported from boykopovar/AnyPS5. Originally posted by ligmaSec on 2026-12-03T13:25:12Z.
Review: COMMENTED
Built the focused checks against the existing Linux runtime.
GuestHeapSmallSpanspassed in the default, reclaim, live, and reuse modes with the configuration used by the registered tests. A trial merge against integration main reports conflicts inGuestHeap.cppand the environment guide.AI-assisted: yes.
View command line instructions
Checkout
From your project repository, check out a new branch and test the changes.Merge
Merge the changes and update on Forgejo.Warning: The "Autodetect manual merge" setting is not enabled for this repository, you will have to mark this pull request as manually merged afterwards.