diff --git a/Cargo.lock b/Cargo.lock index 72b6784..8d8f101 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -275,7 +275,7 @@ checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" [[package]] name = "rusty_alloc" -version = "2.6.0" +version = "2.7.0" dependencies = [ "libc", "loom", @@ -286,14 +286,14 @@ dependencies = [ [[package]] name = "rusty_alloc-api" -version = "2.6.0" +version = "2.7.0" dependencies = [ "rusty_alloc", ] [[package]] name = "rusty_alloc-bench" -version = "2.6.0" +version = "2.7.0" dependencies = [ "libloading", "rusty_alloc", @@ -302,14 +302,14 @@ dependencies = [ [[package]] name = "rusty_alloc-ffi" -version = "2.6.0" +version = "2.7.0" dependencies = [ "rusty_alloc", ] [[package]] name = "rusty_alloc-override" -version = "2.6.0" +version = "2.7.0" dependencies = [ "rusty_alloc", "rusty_alloc-ffi", @@ -317,7 +317,7 @@ dependencies = [ [[package]] name = "rusty_alloc-wasm" -version = "2.6.0" +version = "2.7.0" dependencies = [ "rusty_alloc", ] diff --git a/Cargo.toml b/Cargo.toml index 543f259..aecb2bc 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -132,7 +132,7 @@ members = [ # different files that never got the section. Fixed here, in both, and # verified by extracting the packaged `.crate` before publishing rather than # checking the live page afterwards. -version = "2.6.0" +version = "2.7.0" edition = "2024" # MSRV. Declared for the first time in 1.0.1 because this release genuinely # needs it: `asm!` label blocks (`asm_goto`, stable 1.87) carry the free path's diff --git a/README.md b/README.md index 170f296..f7dc323 100644 --- a/README.md +++ b/README.md @@ -34,7 +34,7 @@ toolchain, no emscripten, no per-platform allocator to qualify. ```toml [dependencies] -rusty_alloc-api = "2.5" +rusty_alloc-api = "2.7" ``` ```rust @@ -50,11 +50,11 @@ are before you ship. | platform | replaces | result | trade-off | |---|---|---|---| -| **Linux servers & CLIs** | mimalloc | allocator's own instructions **0.52× / 0.81× / 0.83×** on lua / perl / sqlite; whole program 0.96–1.00× | lead is widest in the allocator and narrowest across a whole program, because most instructions in a real program are not the allocator | -| **Linux** | jemalloc | whole program **0.84× / 0.89× / 0.98×** | — | +| **Linux servers & CLIs** | mimalloc | allocator's own instructions **0.44× / 0.68× / 0.71×** on lua / perl / sqlite; whole program 0.96–1.00× | lead is widest in the allocator and narrowest across a whole program, because most instructions in a real program are not the allocator | +| **Linux** | jemalloc | whole program **0.83× / 0.89× / 0.98×** | — | | **Linux** | glibc `malloc` | whole program **0.81× / 0.81× / 0.99×** | — | -| **Rust applications** | the default allocator path | **up to 27 % fewer whole-program instructions** vs rusty_alloc 2.2.0 via a dedicated `GlobalAlloc` fast path | short-lived-thread workloads: only 0.8 % | -| **Windows & macOS** | system heap | same codebase and fast paths, full test suites on each release | freed memory stays committed by default, as in mimalloc: one consumer read 461 MB retained where the Windows heap fell back to 4 MB; set `RUSTY_ALLOC_PURGE_DELAY` to return it | +| **Rust applications** | the default allocator path | dedicated `GlobalAlloc` and `Allocator` fast paths; `Vec::new_in(RustyAlloc)` runs **1 % below** the same work through `#[global_allocator]` | — | +| **Windows** | system heap | OpenTTD builds in **0.95×** the Windows heap's time, ninja on par; peak commit **1.07–1.29×** the Windows heap's | commits somewhat more than the Windows heap: freed memory is kept for 10 ms (`purge_delay`) so a loop that frees and reallocates never refaults | | **Browser (wasm32)** | `dlmalloc` | churn workload **4.9–7.3× faster**; adds **+2,435 bytes gzipped** to a minimal module | a 2 KB tight alloc/free loop runs **0.55–0.83×** as fast as dlmalloc; small tight loops within noise | | **Microcontrollers (ESP32-S3)** | `esp-alloc` | **2.1–3.9× faster** on silicon, flat capacity under churn | needs a **64 KiB** RAM floor vs 8 KiB; held 21 size classes at once vs 24; **357 NULLs** in 50,000 hostile churn allocations vs 0; refuses 64 KiB-aligned requests | @@ -65,111 +65,109 @@ paths, where upstream mimalloc accepts it silently in release builds. - **Permissive MIT licence.** No GPL, no LGPL, no C anywhere in the dependency tree. -- **In production** across the Remade With Rust and Mata Network portfolio, with - 27,892 active installs. SpaceDB and rusty_zstd validate every release against - their full test suites, and the Silesia corpus compresses byte-identically - on the allocator. -- **Hardened**: 14 of 15 v1.0.0 security gates met, Miri-clean, a loom-verified - cross-thread protocol, every `unsafe` block documented and ratcheted, and - opt-in `secure` mode with encrypted free lists for hostile input. Details in - [Security](#security). -- **Stable API**: frozen since 2.0 and following semver, with every release - checked by `cargo-semver-checks`. +- **In production** across the Remade With Rust and Mata Network portfolio, + with 130,396 active installs. +- **Hardened**: a loom-verified cross-thread protocol, every `unsafe` block + documented and ratcheted, no panic reachable from an allocation on x86-64 + Linux release builds, and opt-in `secure` mode with encrypted free lists for + hostile input. Details in [Security](#security). +- **Stable API**: frozen since 2.0 and following semver. - **Deterministic evidence**: performance claims come from exact instruction counts, not a noisy stopwatch. Every comparison names its harness in `bench/`. -> **Current release: `2.2.1`.** The API is stable and follows semver. -> Upgrading from 1.x with `default-features = false`? Add -> `features = ["std"]`, since that flag now selects the bare-metal profile. The +> **Current release: `2.7.0`.** The API is stable and follows semver. The > release history is in `CHANGELOG.md`. ## Performance (deterministic instruction counts) -Instructions retired under callgrind, x86-64 Linux, `LD_PRELOAD`. perl and -sqlite repeat to the instruction with the hash seed pinned; **lua does not — -its seed is not pinnable from the environment and it moves ~0.26% run to run**, -so read lua as indicative and the other two as verdicts. Real programs, -WHOLE-PROGRAM instructions: +Instructions retired under callgrind, x86-64 Linux, `LD_PRELOAD`, Rust 1.100. +perl and sqlite repeat to the instruction with the hash seed pinned; lua's seed +cannot be pinned from the environment and moves about 0.26 % run to run, so +read lua as indicative and the other two as exact. Real programs, +whole-program instructions: | workload | vs mimalloc | vs jemalloc | vs glibc | |---|---:|---:|---:| -| lua | **0.962** | **0.835** | 0.813 | +| lua | **0.957** | **0.829** | 0.809 | | perl | **0.988** | **0.889** | 0.810 | | sqlite | **0.995** | **0.976** | 0.988 | -Those are whole-program ratios, and they understate the allocator by design, -because in a real program most instructions are not the allocator. The same -runs, decomposed: +Whole-program ratios understate the allocator by design, because in a real +program most instructions are not the allocator. The same runs, decomposed: -| workload | allocator share | **allocator-only ra/mi** | whole program | floor if our allocator cost ZERO | +| workload | allocator share | **allocator-only ra/mi** | whole program | floor if our allocator cost zero | |---|---:|---:|---:|---:| -| lua | 3.3% | **0.44** | 0.962 | 0.93 | -| perl | 2.7% | **0.68** | 0.988 | 0.96 | -| sqlite | 1.2% | **0.70** | 0.995 | 0.98 | - -Allocator-only Ir is summed by OBJECT from the raw callgrind file -(`bench/icount-arms.sh`), so code inlined from any source file counts. Measured -2026-11-12 (2.5.0) against the mimalloc v2.4.5 oracle build and jemalloc -5.3.0. At 2.4.0 the allocator-only column read 0.52 / 0.81 / 0.83. - -**What moved since 2.2.0** — five rounds of exact-instruction work, every -change gated on the counts and on the full suites (`docs/LEDGER.md`, -CURIOSITY rounds one to four; `docs/opps.md`, vein census 4, for 2.5.0). -Per-op, `bench/opscan.sh` (lower is better): - -| op | 2.2.0 (`c9631f4`) | 2.4.0 | 2.5.0 | Δ since 2.2.0 | -|---|---:|---:|---:|---:| -| cross-thread free (`xthread`) | 113.71 | 74.81 | **65.83** | −42 % | -| huge (2 MiB) alloc + free | 689.68 | 144.00 | **144.00** | −79 % | -| `big` (4 KiB) alloc + free | 121.00 | 94.00 | **89.00** | −26 % | -| `mixed` sizes | 110.93 | 93.56 | **85.80** | −23 % | -| `calloc` | 107.57 | 93.01 | **83.01** | −23 % | -| `posix_memalign` | 97.88 | 83.01 | **79.13** | −19 % | -| `realloc` (grow) | 259.86 | 227.97 | **203.45** | −22 % | -| `small` (32 B) alloc + free | 54.39 | 52.25 | **47.07** | −13 % | - -Against mimalloc v2.4.5 on the same scan, every one of the 16 operations is -below it: 0.003× on the 2 MiB pair, 0.39× on the 256-byte pair, and 0.86× at -the narrowest (`liveset`, 65,536 live objects with a random victim replaced -each step). - -Process start-up also got cheaper: reading the allocator's options used to -walk the environment 76 times; on Linux it now walks it once, about 25,000 -instructions saved on every process launch. - -### Rust programs (`GlobalAlloc`) - -Rust deliverables reach the allocator through `GlobalAlloc`, which the C -instruments above never exercise. Four deterministic Rust workloads -(`bench/rust-globalalloc.sh`, whole-program Ir per 20,000 steps, identical -checksums between arms): - -| workload | 2.4.0 | 2.5.0 | Δ | +| lua | 3.3 % | **0.44** | 0.957 | 0.92 | +| perl | 2.7 % | **0.68** | 0.988 | 0.96 | +| sqlite | 1.2 % | **0.71** | 0.995 | 0.98 | + +Allocator-only instructions are summed by object from the raw callgrind file +(`bench/icount-arms.sh`), so code inlined from any source file counts. +Measured 2026-12-02 (2.7.0) against the mimalloc v2.4.5 oracle build and +jemalloc 5.3.0. + +Per operation, `bench/opscan.sh` (instructions per operation, lower is +better): + +| op | 2.2.0 | 2.6.0 | **2.7.0** | Δ since 2.2.0 | vs mimalloc | +|---|---:|---:|---:|---:|---:| +| cross-thread free (`xthread`) | 113.71 | 65.83 | **65.83** | −42 % | 0.50× | +| huge (2 MiB) alloc + free | 689.68 | 145.00 | **138.00** | −80 % | 0.003× | +| `big` (4 KiB) alloc + free | 121.00 | 89.00 | **89.00** | −26 % | 0.40× | +| `mixed` sizes | 110.93 | 85.80 | **85.81** | −23 % | 0.54× | +| `calloc` | 107.57 | 83.01 | **83.00** | −23 % | 0.52× | +| `posix_memalign` | 97.88 | 79.63 | **79.50** | −19 % | 0.42× | +| `realloc` (grow) | 259.86 | 203.92 | **190.79** | −27 % | 0.38× | +| `small` (32 B) alloc + free | 54.39 | 47.07 | **47.07** | −13 % | 0.42× | + +All 23 operations in the scan measure below mimalloc. The widest margins are +the 2 MiB pair (0.003×), blocks above 32 MiB (0.021×) and small `realloc` +(0.36×); the narrowest are the ones dominated by work any allocator must do or +by a large live set: `calloc` of 256 KiB (0.97×, the zeroing), `liveset` +(0.86×, 65,536 live objects with a random victim replaced each step) and +`shbench` (0.83×). Against 2.6.0 the one operation that measurably moved up +is the block above 32 MiB, +0.4 % (1,138 to 1,143), the cost of committing +only the part of a giant block that is reached. + +Process start-up is cheap too: reading the allocator's options walks the +environment once on Linux, about 25,000 instructions saved on every launch +compared with a walk per option. + +### Rust programs (`GlobalAlloc` and `Allocator`) + +Rust deliverables reach the allocator through `GlobalAlloc`, or through the +`Allocator` trait for a single collection, which the C instruments above never +exercise. Seven deterministic Rust workloads (`bench/rust-globalalloc.sh`, +whole-program instructions per 20,000 steps, identical checksums between +arms, both columns built by Rust 1.100 on 2026-12-02): + +| workload | 2.6.0 | **2.7.0** | Δ | |---|---:|---:|---:| -| boxed trees, buffers, `Rc` | 18,436,007 | 17,477,878 | **−5.2 %** | -| hash maps, B-trees, strings | 26,485,019 | 26,301,891 | −0.7 % | -| cache-line-aligned buffers (`realloc`) | 1,292,463 | 1,213,478 | **−6.1 %** | -| short-lived threads | 2,769,878 | 2,560,766 | **−7.5 %** | - -Both columns measured 2026-11-12 with the same script and toolchain (Rust -1.97.1, LLVM 22). The numbers in this section are that compiler's. Rust -1.100 (LLVM 23) compiles every allocation and free fast path to the same -instructions, and the allocator's total on the C programs above moves by -+0.003 % to +0.024 %; the Rust workloads themselves are compiled differently -by it (`docs/opps.md`, "Toolchain"), so compare columns from one compiler -only. Against -2.2.0 (`c9631f4`, measured 2026-09-25) the boxed-trees workload has gone from -23,357,670 to 17,477,878 (−25 %) and the hash-maps one from 28,220,088 to -26,301,891 (−7 %). - -What changed: the `GlobalAlloc` methods are `#[inline]` (as the `mimalloc` -crate's are), so rustc's `__rust_alloc` shims carry the fast path instead of -jumping to it; `dealloc` is the free fast path with its null test folded -away; layouts aligned to 16 bytes — every hashbrown table — are served from -the ordinary size classes, which are already 16-aligned, instead of the -aligned path; and `realloc` at any alignment keeps a block in place when it -fits instead of always copying. +| boxed trees, buffers, `Rc` | 17,468,164 | **17,467,850** | 0.0 % | +| hash maps, B-trees, strings | 27,078,126 | **27,078,257** | 0.0 % | +| cache-line-aligned buffers (`realloc`) | 1,216,516 | **1,215,600** | −0.1 % | +| short-lived threads | 2,617,563 | **2,411,815** | **−7.9 %** | +| `Vec` growth, `#[global_allocator]` | 50,667,363 | **50,365,884** | −0.6 % | +| `Vec` growth, `Vec::new_in(RustyAlloc)` | 50,709,569 | **49,856,136** | **−1.7 %** | +| `Vec` growth, in a first-class `Heap` | 50,486,172 | **49,687,570** | **−1.6 %** | + +Both `Allocator` trait routes are now cheaper than the global one. Where the build +is proven unable to panic on an allocation (x86-64 Linux, release, +`opt-level` 2 or 3, default features), its methods run without the +abort-on-unwind guard the trait's contract otherwise calls for: the panic +sites are counted in the machine code under fat LTO and under Cargo's default +release profile, and held at zero. A short-lived thread makes no system +calls of its own beyond its segment: its random-number generator seeds on +first use, and a segment handed back records how much of it is committed. + +The `GlobalAlloc` methods are `#[inline]` (as the `mimalloc` crate's are), so +rustc's `__rust_alloc` shims carry the fast path instead of jumping to it; +`dealloc` is the free fast path with its null test folded away; layouts +aligned to 16 bytes, every hashbrown table among them, are served from the +ordinary size classes, which are already 16-aligned; and `realloc` keeps a +block in place when it fits, and grows a large block in place into the free +space after it. **One more instruction, if the allocator is linked into an executable.** On x86-64 Linux, add `--cfg ra_tls_local_exec` to `RUSTFLAGS` for a binary that @@ -182,10 +180,9 @@ RUSTFLAGS="--cfg ra_tls_local_exec" cargo build --release Every allocation finds its thread's heap through a thread-local slot. A library has to reach it in two instructions, because the slot's offset is only known when the program is loaded. In an executable the linker knows it, -and the load takes it as its own displacement: one instruction. Measured on -the workloads above, same checksums: boxed trees **−220,144** whole-program -(−1.24 %), hash maps −29,141, aligned buffers −3,684; `__rust_alloc` 16 → 15 -instructions per call. +and the load takes it as its own displacement: one instruction. On the boxed +trees workload that is 1.24 % of the whole program, and `__rust_alloc` goes +from 16 to 15 instructions per call. It is a `--cfg` and not a default because the same code cannot be linked into a shared library: set it on a `cdylib` (the `LD_PRELOAD` override, a plugin) @@ -193,17 +190,30 @@ and the link fails with `relocation R_X86_64_TPOFF32 ... cannot be used with -shared`. That is the whole failure mode. It is a link error, never a wrong program. -**Checked on real consumers, not just counted.** On 2026-09-25 SpaceDB (whole -workspace, 314 tests) and rusty_zstd (194 tests plus C-zstd cross tests) ran -on this allocator on Windows and Linux, and the Silesia corpus went through -rusty_zstd's CLI: every file at levels 1/3/9/19 and 4 threads compressed -**byte-identically** to the same CLI on 2.2.0 and round-tripped through C zstd -1.5.7 both ways (`tools/corpus/`, `docs/LEDGER.md` DOWNSTREAM CORPUS). +### Windows: memory committed + +Peak commit charge on real Windows builds (medians of interleaved runs, Rust +1.100), against the Windows heap and the previous release: + +| program, threads | Windows heap | 2.6.0 | **2.7.0** | +|---|---:|---:|---:| +| ninja, 1 | 17.6 MiB | 34.0 | **21.9** | +| ninja, 6 | 33.4 MiB | 90.6 | **43.0** | +| OpenTTD, 6 | 361 MiB | 493 | **405** | +| Godot editor, 6 | 1,024 MiB | 1,435 | **1,097** | + +Medium pages and a size class's first small page commit as they fill, large +blocks commit to their last OS page, a segment commits 256 KiB ahead of its +carve cursor, and a heap gives back free spans it has seen unused for a whole +`purge_delay`. None of it costs speed: OpenTTD's build runs in 0.95× the +Windows heap's time, and loops that free and reallocate fault exactly as many +pages as before. + +### The `free` fast path -**Where this came from: `free`.** It is the function a real program spends its -allocator time in, so it is the one worth counting instruction by instruction. -Ours is now **17 instructions on the fast path against mimalloc's 25**, down -from 27 at 2.2.0 and 21 at 2.4.0: +`free` is the function a real program spends its allocator time in, so it is +the one worth counting instruction by instruction. Ours is **17 instructions +on the fast path against mimalloc's 25**: | stage | rusty_alloc | mimalloc | |---|---:|---:| @@ -217,10 +227,10 @@ from 27 at 2.2.0 and 21 at 2.4.0: | CET landing pad + return | 1 | 2 | | **total** | **17** | **25** | -The flags test is gone in 2.5.0: each page carries one owner word that holds -its thread's id only while the page is plain, so the same load and compare -that asks "is this my page" also asks "is it plain". The page is found -through a per-slice table of page pointers in the segment header. +Each page carries one owner word that holds its thread's id only while the +page is plain, so the same load and compare that asks "is this my page" also +asks "is it plain". The page is found through a per-slice table of page +pointers in the segment header. ## Embedded: bare metal, measured on silicon @@ -370,13 +380,9 @@ username. `RUSTFLAGS="--remap-path-prefix=$PWD=."` fixes it on stable; Cargo's ## Security -Audited against the `use-protection-please` 41-gate hardening standard — -**14 of 15 v1.0.0 gates met**. The one open gate, H-27, is the 30-day -continuous-fuzz soak: the nightly mechanism is live and the corpus is committed -as a floor; the soak completes 2026-09-19 and ships under a time-bound owner -waiver. The residual-risk register (R-001..R-005) is owner-accepted; both -release waivers (H-05 release overflow-checks, H-27 soak) are time-bounded. The -gate-by-gate table is at the bottom of this README. +Audited against the `use-protection-please` 41-gate hardening standard, with +nightly continuous fuzzing and an owner-accepted residual-risk register +(R-001..R-005). The gate-by-gate table is at the bottom of this README. Default build: @@ -384,12 +390,11 @@ Default build: owner and cross-thread paths both. - **Memory-safe core:** `unsafe` isolated with a stated invariant per block, `undocumented_unsafe_blocks` and `unsafe_op_in_unsafe_fn` denied - workspace-wide, Miri-clean over the whole target, a loom-verified cross-thread - protocol. -- **Mitigations verified for efficacy, not just presence:** `tests/corruption.rs` - poisons a real free list and requires SIGABRT (detected-and-refused), not - SIGSEGV (followed the poisoned link) — a mitigation nobody has watched fire is - a claim, not a defence. + workspace-wide, a loom-verified cross-thread protocol, and no panic + reachable from an allocation on x86-64 Linux release builds, counted in the + machine code. +- **Mitigations proven to fire:** a poisoned free list must end in an abort + (detected and refused), never a fault from following the poisoned link. Opt-in for hostile input: **`secure`** (encrypted free-list links + a same-segment link bound; flat ~15 instr/alloc) and **`blockmap`** (a per-page @@ -420,11 +425,10 @@ abandonment and adoption, first-class heaps, arenas, huge allocations, aligned allocation with interior-pointer recovery, and the full realloc family. **Safety** — double-free detection on both the owner and cross-thread paths; -Miri-clean; `debug_checks` for full invariant validation; `secure` for encrypted +`debug_checks` for full invariant validation; `secure` for encrypted free-list links with a same-segment link bound (flat ~15 instr/alloc); `blockmap` for a per-page block-liveness map that closes the read-primitive residual R-005 -(off by default on cost). Mitigations are tested for efficacy — the corruption -suite asserts the allocator *aborts* on a poisoned free list. +(off by default on cost). **Portability** — x86-64 and aarch64, Linux, macOS and Windows, plus `wasm32-unknown-unknown` via `memory.grow`. @@ -473,7 +477,7 @@ in the `options` module docs, and a test holds it to the source. ```toml [dependencies] -rusty_alloc-api = "2.5" +rusty_alloc-api = "2.7" ``` | crate | docs | what | diff --git a/bench/issue63/adj.py b/bench/issue63/adj.py new file mode 100644 index 0000000..ee52600 --- /dev/null +++ b/bench/issue63/adj.py @@ -0,0 +1,29 @@ +"""For each large span, at the moment it is freed: was the slice after it the cursor or free? (An upper bound on growth in place.)""" +import sys, collections +ev = [tuple(map(int, l.split())) for l in open(sys.argv[1])] +SEG = 512 +live = {} # slice -> span start +spans = {} +cursor = collections.defaultdict(int) +res = collections.Counter(); mib = collections.Counter() +for k, a, n in ev: + if k in (0, 1): + sl = n & 0xFFFFF + spans[a] = sl + for s in range(a, a + sl): live[s] = a + cursor[a // SEG] = max(cursor[a // SEG], a + sl) + elif k == 2 and a in spans: + sl = spans.pop(a) + for s in range(a, a + sl): live.pop(s, None) + if sl >= 2 and sl != 8 or sl > 8: + nxt = a + sl + if nxt % SEG == 0: w = "segment end" + elif nxt >= cursor[a // SEG]: w = "cursor follows" + elif nxt not in live: + run = 0 + while nxt + run not in live and nxt + run < cursor[a // SEG]: run += 1 + w = "free span follows, at least as long" if run >= sl else "free span follows, shorter" + else: w = "live span follows" + res[w] += 1; mib[w] += sl / 16 +tot = sum(mib.values()) +for w, c in res.most_common(): print(f" {w:38} {c:5} spans {mib[w]:8.1f} MiB {100 * mib[w] / tot:5.1f} %") diff --git a/bench/issue63/allocator-trace-and-step.patch b/bench/issue63/allocator-trace-and-step.patch new file mode 100644 index 0000000..03f2494 --- /dev/null +++ b/bench/issue63/allocator-trace-and-step.patch @@ -0,0 +1,96 @@ +diff --git a/crates/rusty_alloc/src/page.rs b/crates/rusty_alloc/src/page.rs +index 7d921bf..c24b24d 100644 +--- a/crates/rusty_alloc/src/page.rs ++++ b/crates/rusty_alloc/src/page.rs +@@ -1584,6 +1584,7 @@ pub unsafe fn page_extend_inline(page: *mut Page, area: *mut u8) { + let head = link_run(page, start, bsize, take, (*page).free); + (*page).free = head; + (*page).capacity = (capacity + take) as u32; ++ crate::segment::trace_ext(page, (capacity + take) * bsize); + } + } + +diff --git a/crates/rusty_alloc/src/segment.rs b/crates/rusty_alloc/src/segment.rs +index 98b7a76..50fcc91 100644 +--- a/crates/rusty_alloc/src/segment.rs ++++ b/crates/rusty_alloc/src/segment.rs +@@ -223,7 +223,7 @@ pub const LAZY_COMMIT: bool = + /// double from the header up to this step, so a full segment costs about a + /// dozen commit calls and the committed-but-uncarved tail stays under + /// max(the carved size, 4 MiB). +-const COMMIT_STEP_MAX_SLICES: usize = (4 << 20) / SEGMENT_SLICE_SIZE; ++const COMMIT_STEP_MAX_SLICES: usize = (256 << 10) / SEGMENT_SLICE_SIZE; + + /// How many slices to commit at the creation of a segment for a heap that + /// already owns one, when it wants `slices` from it: a whole step. +@@ -1104,6 +1104,7 @@ pub unsafe fn span_alloc(seg: *mut Segment, slices: usize) -> (*mut Page, bool) + // The FRONT of a free span: its interiors already point here. + span_mark(seg, s, idx, slices, slices); + (*seg).used_pages += 1; ++ trace_ev(1, seg, idx, slices); + return (s, false); + } + s = (*s).next; +@@ -1132,6 +1133,7 @@ pub unsafe fn span_alloc(seg: *mut Segment, slices: usize) -> (*mut Page, bool) + } + (*seg).next_free_slice = (idx + slices) as u32; + (*seg).used_pages += 1; ++ trace_ev(0, seg, idx, slices); + // Never-carved slices: mark all of them. + span_mark(seg, start, idx, slices, 1); + (start, (*seg).mem_is_zero) +@@ -1162,6 +1164,7 @@ pub unsafe fn span_free(seg: *mut Segment, page: *mut Page) -> usize { + // Where the freed span sat before any merge: its interiors already + // point back to `freed_idx` (see `span_mark`). + let (freed_idx, freed_len) = (idx, len); ++ trace_ev(2, seg, idx, len); + (*seg).used_pages -= 1; + // Scrub page state so a stale slot can't masquerade as live. + (*page).block_size = 0; +@@ -1481,6 +1484,7 @@ unsafe fn commit_frontier(seg: *mut Segment, need: usize) -> bool { + return false; + }; + (*seg).commit_end = end as u32; ++ trace_ev(3, seg, have, end - have); + true + } + } +@@ -2543,3 +2547,38 @@ mod free_slot_tests { + unsafe { free(blocks[0]) }; + } + } ++ ++// TEMPORARY (issue 63 investigation): span event trace. ++static TRACE: [core::sync::atomic::AtomicU64; 1 << 18] = [const { core::sync::atomic::AtomicU64::new(0) }; 1 << 18]; ++static TRACE_N: AtomicUsize = AtomicUsize::new(0); ++#[inline] ++fn trace_ev(kind: u64, seg: *mut Segment, idx: usize, n: usize) { ++ let i = TRACE_N.fetch_add(1, Ordering::Relaxed); ++ if i < TRACE.len() { ++ let v = (kind << 60) | (((seg.addr() >> 25) as u64 & 0xfff) << 40) | ((idx as u64) << 20) | n as u64; ++ TRACE[i].store(v, Ordering::Relaxed); ++ } ++} ++/// Dump the trace: `kind seg idx n` per line. ++#[cfg(feature = "std")] ++#[unsafe(no_mangle)] ++pub extern "C" fn ra_trace_dump() { ++ use std::io::Write; ++ let n = TRACE_N.load(Ordering::Relaxed).min(TRACE.len()); ++ let mut out = std::string::String::new(); ++ for e in &TRACE[..n] { ++ let v = e.load(Ordering::Relaxed); ++ out.push_str(&std::format!("{} {} {} {} ++", v >> 60, (v >> 40) & 0xfff, (v >> 20) & 0xfffff, v & 0xfffff)); ++ } ++ if let Ok(p) = std::env::var("RA_TRACE_FILE") { ++ let _ = std::fs::File::create(p).and_then(|mut f| f.write_all(out.as_bytes())); ++ } ++} ++/// TEMPORARY: a page now has `bytes` of its area carved into blocks. ++pub fn trace_ext(page: *mut Page, bytes: usize) { ++ let seg = segment_of(page.cast()); ++ // SAFETY: `page` is a live span start of `seg`. ++ let idx = unsafe { page_index(seg, page) }; ++ trace_ev(4, seg, idx, bytes.div_ceil(4096)); ++} diff --git a/bench/issue63/cgsum.py b/bench/issue63/cgsum.py new file mode 100644 index 0000000..caf6cbb --- /dev/null +++ b/bench/issue63/cgsum.py @@ -0,0 +1,32 @@ +"""cgsum.py []: allocator self instructions by function, and call counts.""" +import re, subprocess, sys, collections +def load(path): + txt = subprocess.run(["callgrind_annotate", "--threshold=100", path], capture_output=True, text=True).stdout + by = collections.Counter(); total = 0 + for l in txt.splitlines(): + m = re.match(r"\s*([\d,]+) \(\s*[\d.]+%\)\s+(\S+?):(.+?)(?: \[.*)?$", l) + if not m: continue + ir = int(m[1].replace(",", "")); f, fn = m[2], m[3] + if "rusty_alloc" not in l and "librusty" not in l: continue + by[fn] += ir; total += ir + calls = collections.Counter(); names = {}; cur = None + for l in open(path, errors="replace"): + if l.startswith("cfn="): + m = re.match(r"cfn=\((\d+)\)(?: (.*))?", l) + if m: + if m[2]: names[m[1]] = m[2].strip() + cur = names.get(m[1]) + elif l.startswith("calls=") and cur: + calls[cur] += int(l.split("=")[1].split()[0]) + return by, total, calls +a = load(sys.argv[1]); b = load(sys.argv[2]) if len(sys.argv) > 2 else None +print(f"allocator self Ir: {a[1]:,}" + (f" -> {b[1]:,} ({b[1]-a[1]:+,})" if b else "")) +src = b or a +for fn, ir in src[0].most_common(26): + old = a[0].get(fn, 0) + c = next((v for k, v in src[2].items() if fn.split("::")[-1] in k), 0) + print(f" {ir:>12,} {'' if not b else f'{ir-old:+10,}'} calls~{c:>9,} {fn[:80]}") +if b: + for k in ("clock_gettime", "schedule_purge", "purge_tick", "purge_aged", "span_free", "span_alloc", "retire_span", "fresh_page", "mprotect", "madvise"): + ca = sum(v for n, v in a[2].items() if k in n); cb = sum(v for n, v in b[2].items() if k in n) + print(f" calls {k:16} {ca:>8,} -> {cb:>8,}") diff --git a/bench/issue63/ci-linux.sh b/bench/issue63/ci-linux.sh new file mode 100644 index 0000000..5f3d1e2 --- /dev/null +++ b/bench/issue63/ci-linux.sh @@ -0,0 +1,59 @@ +#!/usr/bin/env bash +# Local mirror of the Linux CI jobs. usage: ci-linux.sh +. /root/.cargo/env +tree=$1; tag=$2 +cd "$tree" || exit 2 +T=/root/slh/t-$tag +ok=0; bad=0 +step() { # name, target-dir suffix, env..., -- cmd + local name=$1 td=$2; shift 2 + local envs=() + while [ "$1" != "--" ]; do envs+=("$1"); shift; done; shift + if env CARGO_TARGET_DIR=$T$td "${envs[@]}" "$@" > /root/slh/last.$tag.log 2>&1; then + echo "PASS $name"; ok=$((ok+1)) + else + echo "FAIL $name"; tail -25 /root/slh/last.$tag.log; bad=$((bad+1)) + fi +} +step "clippy all features" "" -- cargo clippy --workspace --all-targets --all-features -- -D warnings +step "clippy default" "" -- cargo clippy --workspace --all-targets -- -D warnings +for f in secure linkcheck blockmap debug_checks; do + step "clippy --features $f" "" -- cargo clippy -p rusty_alloc --all-targets --features $f -- -D warnings +done +step "test all features" "" -- cargo test --workspace --all-features +step "test default" "" -- cargo test --workspace +step "test release api" "" -- cargo test --release -p rusty_alloc-api --features allocator-api +step "test release core lib" "" -- cargo test --release -p rusty_alloc --lib +step "test release destroy_no_adopt" "" -- cargo test --release -p rusty_alloc --test destroy_no_adopt +for g in "" "--cfg ra_small_profile"; do + step "shared light heap test [$g]" "-slh" "RUSTFLAGS=--cfg ra_shared_light_heap $g" -- cargo test -p rusty_alloc -p rusty_alloc-api + step "shared light heap clippy [$g]" "-slh" "RUSTFLAGS=--cfg ra_shared_light_heap $g" -- cargo clippy -p rusty_alloc --all-targets -- -D warnings +done +step "small profile test" "-small" "RUSTFLAGS=--cfg ra_small_profile" -- cargo test -p rusty_alloc +step "small profile clippy" "-small" "RUSTFLAGS=--cfg ra_small_profile" -- cargo clippy -p rusty_alloc --all-targets -- -D warnings +S3="RUSTFLAGS=--cfg ra_small_profile --cfg ra_single_threaded --cfg ra_aligned_region" +step "small+single+aligned fixed" "-sar" "$S3" -- cargo test -p rusty_alloc --lib prim::fixed +step "small+single+aligned region" "-sar" "$S3" -- cargo test -p rusty_alloc --test region +step "small+single+aligned clippy" "-sar" "$S3" -- cargo clippy -p rusty_alloc --all-targets -- -D warnings +S4='RUSTFLAGS=--cfg ra_small_profile --cfg ra_segment_size="256k"' +step "small 256k test" "-256" "$S4" -- cargo test -p rusty_alloc +step "small 256k clippy" "-256" "$S4" -- cargo clippy -p rusty_alloc --all-targets -- -D warnings +step "no_std clippy" "-nostd" "RUSTFLAGS=--cfg ra_single_threaded" -- cargo clippy -p rusty_alloc --no-default-features -- -D warnings +step "single-threaded fixed" "-nostd" "RUSTFLAGS=--cfg ra_single_threaded" -- cargo test -p rusty_alloc --lib prim::fixed +for target in riscv32imac-unknown-none-elf riscv32imafc-unknown-none-elf; do + for g in "" "--cfg ra_small_profile"; do + step "bare metal $target [$g]" "-rv" "RUSTFLAGS=--cfg ra_single_threaded $g" -- cargo build -p rusty_alloc --no-default-features --target $target + done +done +step "api riscv" "-rv" "RUSTFLAGS=--cfg ra_small_profile --cfg ra_single_threaded" -- cargo build -p rusty_alloc-api --no-default-features --features allocator-api --target riscv32imac-unknown-none-elf +step "check windows target" "-win" -- cargo check --workspace --target x86_64-pc-windows-msvc +step "check wasm" "-wasm" -- cargo check -p rusty_alloc --target wasm32-unknown-unknown +step "build wasm release" "-wasm" -- cargo build -p rusty_alloc-wasm --target wasm32-unknown-unknown --release +step "msrv 1.88" "-msrv" -- cargo +1.88.0 check --locked -p rusty_alloc -p rusty_alloc-api +step "msrv 1.88 wasm" "-msrv" -- cargo +1.88.0 check --locked -p rusty_alloc --target wasm32-unknown-unknown +step "unsafe census" "" -- bash tools/unsafe-census.sh +step "no-unwind scan" "" -- bash tools/no-unwind-scan.sh +( cd "$tree" && mkdir -p target && rm -f target/wasm32-unknown-unknown 2>/dev/null; ln -sfn $T-wasm/wasm32-unknown-unknown target/wasm32-unknown-unknown ) +step "wasm size" "" -- env -u CARGO_TARGET_DIR bash tools/wasm-size.sh +step "gate selftest" "" -- bash tools/gate-selftest.sh +echo "LOCAL CI: $ok passed, $bad failed" diff --git a/bench/issue63/fast-decomp-probe.patch b/bench/issue63/fast-decomp-probe.patch new file mode 100644 index 0000000..d2a0d04 --- /dev/null +++ b/bench/issue63/fast-decomp-probe.patch @@ -0,0 +1,201 @@ +diff --git a/Cargo.lock b/Cargo.lock +index 1ff8ac3..aac7ee7 100644 +--- a/Cargo.lock ++++ b/Cargo.lock +@@ -75,6 +75,7 @@ dependencies = [ + "fd-pipeline", + "fd-testkit", + "regex-lite", ++ "rusty_alloc-api", + ] + + [[package]] +@@ -298,6 +299,12 @@ dependencies = [ + "itoa", + ] + ++[[package]] ++name = "portable-atomic" ++version = "1.15.0" ++source = "registry+https://github.com/rust-lang/crates.io-index" ++checksum = "05c8b63e8d9609db387f0324918f81d68fe27748f084ef092fb35954d0539a85" ++ + [[package]] + name = "rayon" + version = "1.12.0" +@@ -336,8 +343,104 @@ version = "2.1.3" + source = "registry+https://github.com/rust-lang/crates.io-index" + checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d" + ++[[package]] ++name = "rusty_alloc" ++version = "2.6.0" ++dependencies = [ ++ "libc", ++ "portable-atomic", ++ "windows-sys", ++] ++ ++[[package]] ++name = "rusty_alloc-api" ++version = "2.6.0" ++dependencies = [ ++ "rusty_alloc", ++] ++ + [[package]] + name = "stable_deref_trait" + version = "1.2.1" + source = "registry+https://github.com/rust-lang/crates.io-index" + checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" ++ ++[[package]] ++name = "windows-link" ++version = "0.2.1" ++source = "registry+https://github.com/rust-lang/crates.io-index" ++checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" ++ ++[[package]] ++name = "windows-sys" ++version = "0.60.2" ++source = "registry+https://github.com/rust-lang/crates.io-index" ++checksum = "f2f500e4d28234f72040990ec9d39e3a6b950f9f22d3dba18416c35882612bcb" ++dependencies = [ ++ "windows-targets", ++] ++ ++[[package]] ++name = "windows-targets" ++version = "0.53.5" ++source = "registry+https://github.com/rust-lang/crates.io-index" ++checksum = "4945f9f551b88e0d65f3db0bc25c33b8acea4d9e41163edf90dcd0b19f9069f3" ++dependencies = [ ++ "windows-link", ++ "windows_aarch64_gnullvm", ++ "windows_aarch64_msvc", ++ "windows_i686_gnu", ++ "windows_i686_gnullvm", ++ "windows_i686_msvc", ++ "windows_x86_64_gnu", ++ "windows_x86_64_gnullvm", ++ "windows_x86_64_msvc", ++] ++ ++[[package]] ++name = "windows_aarch64_gnullvm" ++version = "0.53.1" ++source = "registry+https://github.com/rust-lang/crates.io-index" ++checksum = "a9d8416fa8b42f5c947f8482c43e7d89e73a173cead56d044f6a56104a6d1b53" ++ ++[[package]] ++name = "windows_aarch64_msvc" ++version = "0.53.1" ++source = "registry+https://github.com/rust-lang/crates.io-index" ++checksum = "b9d782e804c2f632e395708e99a94275910eb9100b2114651e04744e9b125006" ++ ++[[package]] ++name = "windows_i686_gnu" ++version = "0.53.1" ++source = "registry+https://github.com/rust-lang/crates.io-index" ++checksum = "960e6da069d81e09becb0ca57a65220ddff016ff2d6af6a223cf372a506593a3" ++ ++[[package]] ++name = "windows_i686_gnullvm" ++version = "0.53.1" ++source = "registry+https://github.com/rust-lang/crates.io-index" ++checksum = "fa7359d10048f68ab8b09fa71c3daccfb0e9b559aed648a8f95469c27057180c" ++ ++[[package]] ++name = "windows_i686_msvc" ++version = "0.53.1" ++source = "registry+https://github.com/rust-lang/crates.io-index" ++checksum = "1e7ac75179f18232fe9c285163565a57ef8d3c89254a30685b57d83a38d326c2" ++ ++[[package]] ++name = "windows_x86_64_gnu" ++version = "0.53.1" ++source = "registry+https://github.com/rust-lang/crates.io-index" ++checksum = "9c3842cdd74a865a8066ab39c8a7a473c0778a3f29370b5fd6b4b9aa7df4a499" ++ ++[[package]] ++name = "windows_x86_64_gnullvm" ++version = "0.53.1" ++source = "registry+https://github.com/rust-lang/crates.io-index" ++checksum = "0ffa179e2d07eee8ad8f57493436566c7cc30ac536a3379fdf008f47f6bb7ae1" ++ ++[[package]] ++name = "windows_x86_64_msvc" ++version = "0.53.1" ++source = "registry+https://github.com/rust-lang/crates.io-index" ++checksum = "d6bbff5f0aada427a1e5a6da5f1f98158182f26556f345ac9e04d36d0ebed650" +diff --git a/Cargo.toml b/Cargo.toml +index d6efda4..c083c9d 100644 +--- a/Cargo.toml ++++ b/Cargo.toml +@@ -66,3 +66,7 @@ debug = "line-tables-only" + inherits = "release" + lto = "fat" + codegen-units = 1 ++ ++[patch.crates-io] ++rusty_alloc = { path = "E:/coding/rusty_alloc-i63/crates/rusty_alloc" } ++rusty_alloc-api = { path = "E:/coding/rusty_alloc-i63/crates/rusty_alloc_api" } +diff --git a/crates/fd-cli/Cargo.toml b/crates/fd-cli/Cargo.toml +index df44b54..35e4d71 100644 +--- a/crates/fd-cli/Cargo.toml ++++ b/crates/fd-cli/Cargo.toml +@@ -22,10 +22,16 @@ default = ["msvc-signatures"] + # The shipped signature files derived from Microsoft's runtime code (crates/fd-libid): build + # with `--no-default-features` to leave them out. + msvc-signatures = ["fd-pipeline/msvc-signatures"] ++# Local A/B only: the Rust global allocator is rusty_alloc instead of the ++# Windows heap. The system-allocator binary is this crate without the feature. ++rusty-alloc = ["dep:rusty_alloc-api"] ++probe = [] ++trace = [] + + [dependencies] + fd-pipeline = { workspace = true, default-features = false } + regex-lite.workspace = true ++rusty_alloc-api = { version = "2.6.0", optional = true } + + [dev-dependencies] + fd-testkit.workspace = true +diff --git a/crates/fd-cli/src/main.rs b/crates/fd-cli/src/main.rs +index 7d1e555..89b215b 100644 +--- a/crates/fd-cli/src/main.rs ++++ b/crates/fd-cli/src/main.rs +@@ -15,6 +15,19 @@ use fd_pipeline::{ + RunOptions, RunStats, SelectError, Selector, Session, Sink, State, TextOptions, Va, VerifyOptions, + }; + ++/// Local measurement build. Every Rust allocation goes through rusty_alloc. ++#[cfg(all(feature = "rusty-alloc", not(feature = "probe")))] ++#[global_allocator] ++static GLOBAL: rusty_alloc_api::RustyAlloc = rusty_alloc_api::RustyAlloc; ++#[cfg(feature = "probe")] ++mod probe; ++#[cfg(all(feature = "rusty-alloc", feature = "probe"))] ++#[global_allocator] ++static GLOBAL: probe::Probe = probe::Probe(rusty_alloc_api::RustyAlloc); ++#[cfg(all(not(feature = "rusty-alloc"), feature = "probe"))] ++#[global_allocator] ++static GLOBAL: probe::Probe = probe::Probe(std::alloc::System); ++ + /// The command ran and found problems (internal errors, verification failures). + const EXIT_FAILURES: u8 = 1; + /// Bad usage or an input that cannot be processed. +@@ -721,6 +734,13 @@ fn parse(argv: &[String]) -> Result { + } + + fn main() -> ExitCode { ++ let code = real_main(); ++ #[cfg(feature = "probe")] ++ probe::report(); ++ code ++} ++ ++fn real_main() -> ExitCode { + let argv: Vec = std::env::args().skip(1).collect(); + if argv.first().is_some_and(|a| a == "libsig") { + return match libsig::main(&argv[1..]) { diff --git a/bench/issue63/faults.py b/bench/issue63/faults.py new file mode 100644 index 0000000..7db7213 --- /dev/null +++ b/bench/issue63/faults.py @@ -0,0 +1,21 @@ +import subprocess, ctypes, sys +from ctypes import wintypes +k = ctypes.WinDLL("kernel32"); ps = ctypes.WinDLL("psapi") +class PMC(ctypes.Structure): + _fields_ = [("cb", wintypes.DWORD), ("pf", wintypes.DWORD)] + [(n, ctypes.c_size_t) for n in ("peakws", "ws", "a", "b", "c", "d", "pagefile", "peakpagefile")] +k.OpenProcess.restype = wintypes.HANDLE +ps.GetProcessMemoryInfo.argtypes = [wintypes.HANDLE, ctypes.POINTER(PMC), wintypes.DWORD] +def faults(exe, mode): + p = subprocess.Popen([exe, mode], stdout=subprocess.PIPE, text=True) + h = k.OpenProcess(0x1000 | 0x0400, False, p.pid) + p.communicate() + m = PMC(); m.cb = ctypes.sizeof(PMC) + ps.GetProcessMemoryInfo(h, ctypes.byref(m), m.cb) + return m.pf +arms = sys.argv[1].split(",") +for mode in sys.argv[2:]: + rows = {a: [] for a in arms} + for r in range(5): + for a in arms[r % len(arms):] + arms[:r % len(arms)]: + rows[a].append(faults(f"E:/coding/fd-i63/microbench/mb-{a}.exe", mode)) + print(f"{mode:11} faults min/med: " + " ".join(f"{a} {min(v):>8,}/{sorted(v)[2]:>8,}" for a, v in rows.items()), flush=True) diff --git a/bench/issue63/ir-ab.sh b/bench/issue63/ir-ab.sh new file mode 100644 index 0000000..fa3c347 --- /dev/null +++ b/bench/issue63/ir-ab.sh @@ -0,0 +1,25 @@ +#!/usr/bin/env bash +# Instructions per operation, base tree vs new tree (LD_PRELOAD override), two-point estimator. +# usage: ir-ab.sh +. /root/.cargo/env +base=$1; new=$2 +gcc -O2 -o /root/slh/i63-opscan "$new/bench/opscan.c" || exit 1 +for t in base new; do + tree=${!t} + ( cd "$tree" && CARGO_TARGET_DIR=/root/slh/t-i63-ir-$t cargo build -q --release -p rusty_alloc-override ) || exit 1 +done +ir() { # lib op iters + local out; out=$(mktemp) + LD_PRELOAD="$1" valgrind --tool=callgrind --callgrind-out-file="$out" --cache-sim=no --branch-sim=no /root/slh/i63-opscan "$2" "$3" >/dev/null 2>&1 + grep -m1 '^summary:' "$out" | awk '{print $2}'; rm -f "$out" +} +printf "%-12s %12s %12s %10s\n" op base new delta +for spec in small:200000 med:200000 big:100000 large:20000 huge:2000 calloc:200000 batch_lifo:200000 batch_fifo:200000 realloc:100000 aligned:200000 mixed:200000; do + op=${spec%:*}; n=${spec#*:} + for t in base new; do + lib=/root/slh/t-i63-ir-$t/release/librusty_alloc_override.so + a=$(ir $lib $op $n); b=$(ir $lib $op $((2*n))) + eval "v_$t=$(awk -v a=$a -v b=$b -v n=$n 'BEGIN{printf "%.2f", (b-a)/n}')" + done + printf "%-12s %12s %12s %10s\n" $op $v_base $v_new $(awk -v a=$v_base -v b=$v_new 'BEGIN{printf "%+.2f", b-a}') +done diff --git a/bench/issue63/mine-rs.sh b/bench/issue63/mine-rs.sh new file mode 100644 index 0000000..174e111 --- /dev/null +++ b/bench/issue63/mine-rs.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# The Rust GlobalAlloc / Allocator workloads (bench/rust-globalalloc), paired: +# previous tree against new tree, whole-program Ir per n steps by Ir(2n)-Ir(n), +# with the program's checksum as the work anchor. mine-rs.sh [n] +. /root/.cargo/env +prev=$1; new=$2; n=${3:-20000} +for t in "$prev" "$new"; do + ( cd "$t" && CARGO_TARGET_DIR=/root/slh/t-rs-$(basename "$t") cargo build --release -q --manifest-path bench/rust-globalalloc/Cargo.toml ) || { echo "BUILD FAILED $t"; exit 1; } +done +ir() { local o; o=$(mktemp); valgrind --tool=callgrind --callgrind-out-file="$o" --cache-sim=no --branch-sim=no "$1" "$2" >/dev/null 2>&1; grep -m1 '^summary:' "$o" | awk '{print $2}'; rm -f "$o"; } +printf "%-12s %14s %14s %12s %s\n" bin prev new delta checksum +for b in maps trees threads overaligned vec_global vec_direct vec_heap; do + for t in prev new; do + tree=${!t}; bin=/root/slh/t-rs-$(basename "$tree")/release/$b + a=$(ir "$bin" "$n"); c=$(ir "$bin" $((2 * n))) + eval "v_$t=$((c - a))"; eval "k_$t='$("$bin" "$n" | md5sum | cut -c1-8)'" + done + printf "%-12s %14d %14d %+12d %s\n" $b $v_prev $v_new $((v_new - v_prev)) "$([ "$k_prev" = "$k_new" ] && echo "same $k_new" || echo "DIFFERS $k_prev $k_new")" +done diff --git a/bench/issue63/mine.sh b/bench/issue63/mine.sh new file mode 100644 index 0000000..3bf31ba --- /dev/null +++ b/bench/issue63/mine.sh @@ -0,0 +1,63 @@ +#!/usr/bin/env bash +# Paired instruction counts, previous tree against new tree, in ONE invocation. +# mine.sh [what...] +# what: opscan op names, and/or the programs perl sqlite lua python thr (default: all) +# Prints Ir/op (two-point estimator) for ops, allocator-object self Ir for +# programs with an output hash as the work anchor, and Ir per thread for `thr`. +. /root/.cargo/env +export PERL_HASH_SEED=0 PERL_PERTURB_KEYS=0 +prev=$1; new=$2; shift 2 +W=/root/slh/mine; mkdir -p $W +lib() { echo /root/slh/t-mine-$(basename "$1")/release/librusty_alloc_override.so; } +for t in "$prev" "$new"; do + ( cd "$t" && CARGO_TARGET_DIR=/root/slh/t-mine-$(basename "$t") cargo build -q --release -p rusty_alloc-override ) || { echo "BUILD FAILED: $t"; exit 1; } +done +gcc -O2 -o $W/opscan "$new/bench/opscan.c" -lpthread || exit 1 +cat > $W/thr.c <<'EOF' +#include +#include +#include +static void *work(void *a) { void *p[16]; for (int i = 0; i < 16; i++) { p[i] = malloc(100 + 8 * i); ((char *)p[i])[0] = 1; } for (int i = 0; i < 16; i++) free(p[i]); return a; } +int main(int c, char **v) { int n = atoi(v[1]); for (int i = 0; i < n; i++) { pthread_t t; pthread_create(&t, 0, work, 0); pthread_join(t, 0); } printf("%d\n", n); return 0; } +EOF +gcc -O2 -o $W/thr $W/thr.c -lpthread || exit 1 +ir() { # lib cmd... -> whole-program Ir + local e; e=$(mktemp) + LD_PRELOAD="$1" valgrind --tool=callgrind --callgrind-out-file=/dev/null --cache-sim=no --branch-sim=no "${@:2}" >/dev/null 2>"$e" + grep -oP 'refs:\s+\K[0-9,]+' "$e" | tr -d ','; rm -f "$e" +} +alloc_ir() { # lib cmd... -> " " + local cg o; cg=$(mktemp); o=$(mktemp) + LD_PRELOAD="$1" valgrind --tool=callgrind --callgrind-out-file="$cg" --cache-sim=no --branch-sim=no "${@:2}" >"$o" 2>/dev/null + local a; a=$(awk -v want="$(basename "$1")" ' + function reg(kind, spec, id, rest) { if (spec ~ /^\([0-9]+\)/) { id = spec; sub(/^\(/, "", id); sub(/\).*$/, "", id); rest = spec; sub(/^\([0-9]+\)[ ]?/, "", rest); if (rest != "") N[kind "/" id] = rest; return N[kind "/" id] } return spec } + /^ob=/ { ob = reg("ob", substr($0,4)); next } /^cob=/ { reg("ob", substr($0,5)); next } /^calls=/ { skip = 1; next } + /^[0-9+*-]/ { if (skip) { skip = 0; next } if (index(ob, want) > 0) a += $2; next } END { print a + 0 }' "$cg") + echo "$a $(md5sum < "$o" | cut -c1-8)"; rm -f "$cg" "$o" +} +declare -A N=( [small]=200000 [small_touch]=200000 [med]=200000 [big]=100000 [large]=20000 [huge]=2000 [calloc]=200000 [calloc_big]=20000 [batch_lifo]=200000 [batch_fifo]=200000 [calloc_batch]=200000 [new_batch]=200000 [realloc]=100000 [realloc_small]=200000 [aligned]=200000 [aligned_alloc]=200000 [usable]=400000 [mixed]=200000 [xthread]=100000 ) +ALL="small med big large huge calloc calloc_batch batch_lifo realloc realloc_small aligned aligned_alloc mixed xthread thr perl sqlite lua python" +what="${*:-$ALL}" +printf "%-14s %14s %14s %12s %s\n" what prev new delta anchor +for w in $what; do + case $w in + perl) cmd=(perl -e 'my %h; for my $i (1..150000) { $h{"key$i"} = [ $i, "v$i" ]; } my $s=0; while (my ($k,$v)=each %h) { $s += $v->[0] } print "$s\n";') ;; + sqlite) cmd=(sqlite3 :memory: "CREATE TABLE t(a INTEGER, b TEXT); WITH RECURSIVE c(x) AS (SELECT 1 UNION ALL SELECT x+1 FROM c WHERE x<60000) INSERT INTO t SELECT x, hex(x*7919) FROM c; SELECT count(*), sum(a) FROM t;") ;; + lua) cmd=(lua5.4 -e "local t={} for i=1,120000 do t[#t+1]=tostring(i)..'x' end local m={} for i=1,60000 do m['k'..i]={i,i*2,tostring(i)} end local s=0 for k,v in pairs(m) do s=s+v[2] end print(#t,s)") ;; + python) cmd=(python3 -c "d={} +for i in range(60000): d['k%d'%i]=[i,str(i)] +print(len(d), sum(v[0] for v in d.values()))") ;; + *) cmd=() ;; + esac + if [ ${#cmd[@]} -gt 0 ]; then + read -r a ha <<<"$(alloc_ir "$(lib "$prev")" "${cmd[@]}")"; read -r b hb <<<"$(alloc_ir "$(lib "$new")" "${cmd[@]}")" + printf "%-14s %14d %14d %+12d %s %s\n" $w $a $b $((b-a)) $ha $([ "$ha" = "$hb" ] && echo same || echo "OUTPUT DIFFERS $hb") + elif [ $w = thr ]; then + for t in prev new; do tree=${!t}; l=$(lib "$tree"); x=$(ir "$l" $W/thr 200); y=$(ir "$l" $W/thr 400); eval "v_$t=$(awk -v a=$x -v b=$y 'BEGIN{printf "%.2f", (b-a)/200}')"; done + printf "%-14s %14s %14s %12s per thread\n" thr $v_prev $v_new $(awk -v a=$v_prev -v b=$v_new 'BEGIN{printf "%+.2f", b-a}') + else + n=${N[$w]:-100000} + for t in prev new; do tree=${!t}; l=$(lib "$tree"); x=$(ir "$l" $W/opscan $w $n); y=$(ir "$l" $W/opscan $w $((2*n))); eval "v_$t=$(awk -v a=$x -v b=$y -v n=$n 'BEGIN{printf "%.2f", (b-a)/n}')"; done + printf "%-14s %14s %14s %12s per op\n" $w $v_prev $v_new $(awk -v a=$v_prev -v b=$v_new 'BEGIN{printf "%+.2f", b-a}') + fi +done diff --git a/bench/issue63/multi.py b/bench/issue63/multi.py new file mode 100644 index 0000000..5520e9a --- /dev/null +++ b/bench/issue63/multi.py @@ -0,0 +1,16 @@ +import sys, statistics +from pathlib import Path +sys.path.insert(0, r"E:\coding\fast-decomp-corpus") +import ab +case, jobs, rounds = sys.argv[1], int(sys.argv[2]), int(sys.argv[3]) +arms = sys.argv[4:] +binary = {c[0]: c[1] for c in ab.CASES}[case] +rows = {a: [] for a in arms} +for r in range(rounds): + for a in arms[r % len(arms):] + arms[:r % len(arms)]: + exe = ab.BINS[a] if a in ab.BINS else Path(f"E:/coding/fd-i63/bin/{a}.exe") + d = ab.run_once(exe, binary, jobs, Path(__file__).parent / "out" / f"m-{a}.json") + rows[a].append((d["_peak_commit"] / 2**20, d["_peak_ws"] / 2**20, d["wall_seconds"]["total"])) +for a in arms: + c = sorted(x[0] for x in rows[a]); w = sorted(x[1] for x in rows[a]); t = sorted(x[2] for x in rows[a]) + print(f"{case} j{jobs} {a:10} commit med {statistics.median(c):7.1f} [{c[0]:.0f}..{c[-1]:.0f}] ws med {statistics.median(w):7.1f} time med {statistics.median(t):.3f} min {t[0]:.3f}", flush=True) diff --git a/bench/issue63/poison.py b/bench/issue63/poison.py new file mode 100644 index 0000000..547ccc8 --- /dev/null +++ b/bench/issue63/poison.py @@ -0,0 +1,120 @@ +"""Poison run: each mutation must make at least one test fail. + +usage: poison.py [name regex] + +Each entry is (name, file, text to find exactly once, replacement, cargo test +arguments). A mutation the suite stays green under is a rule nothing guards. +""" +import re +import subprocess +import sys + +root = sys.argv[1] +SEG, PAGE, HEAP, ALLOC = (root + "/crates/rusty_alloc/src/" + f for f in ("segment.rs", "page.rs", "heap.rs", "alloc.rs")) +LIB = ["--lib", "commit_footprint_tests"] +HEAPS = ["--test", "heaps"] +M = [ + ("reuse commits nothing", SEG, + " if os::commit(area, first).is_err() {\n crate::stats::commit_failed();\n return (ptr::null_mut(), false);\n }\n", + "", LIB), + ("remainder forgets it is purged", SEG, + " (*rest).purged = was_purged;", " (*rest).purged = false;", LIB), + ("partly span is not a candidate for a scheduled purge", SEG, + " if (!(*s).purged || (*s).partly) && len >= PURGE_MIN_SLICES {\n // Milliseconds this span must still wait; none when forced.", + " if !(*s).purged && len >= PURGE_MIN_SLICES {\n // Milliseconds this span must still wait; none when forced.", LIB), + ("partly span is not a candidate for the heap's look", SEG, + " if (!(*s).purged || (*s).partly) && len >= PURGE_MIN_SLICES {\n let area = page_area(seg, page_index(seg, s));", + " if !(*s).purged && len >= PURGE_MIN_SLICES {\n let area = page_area(seg, page_index(seg, s));", LIB), + ("merge is not flagged partly", SEG, + " (*head).purged = true;\n (*head).partly = true;\n (*seg).purged_any = true;", + " (*head).purged = true;\n (*seg).purged_any = true;", LIB), + ("frontier commits from the old frontier", SEG, + " let from = have.max(idx);", " let from = have;", LIB), + ("a short page is freed as backed", SEG, + " let freed_short = PAGE_LAZY_COMMIT && (*page).lazy_end != 0;", + " let freed_short = false;", LIB), + ("short reuse claims the whole span", SEG, + " (*s).lazy_end = if !(was_purged && lazy) {", " (*s).lazy_end = if true {", LIB), + ("page commit commits nothing", SEG, + " if os::commit(base, (want - have) * LAZY_UNIT).is_err() {\n crate::stats::commit_failed();\n return false;\n }\n", + "", LIB), + ("a small page's first unit is not committed", SEG, + " if os::commit(page_area(seg, idx), LAZY_UNIT).is_err() {\n crate::stats::commit_failed();\n return (ptr::null_mut(), false);\n }\n", + "", LIB), + ("a small page takes the whole slice as one unit", SEG, + " lazy_end = 1;\n", " lazy_end = 0;\n", LIB), + ("a large block's pages are not committed", SEG, + "if end > from && os::commit(seg.cast::().add(from), end - from).is_err() {", "if false {", LIB), + ("extend does not commit", PAGE, + " if end > (*page).lazy_end as usize * crate::segment::LAZY_UNIT\n && !crate::segment::page_commit_to(page, end)\n {\n return;\n }\n", + "", LIB), + ("extend carves a full batch on a short page", PAGE, + " let take = take.min(chunk.max(1));\n", "", LIB), + ("realloc never grows a large block in place", ALLOC, + "&& crate::segment::span_grow(seg, pg, newsize)", "&& false", LIB), + ("any thread may grow a large block", ALLOC, + "&& (*seg).thread_id.load(Ordering::Relaxed) == init::thread_id()\n && crate::segment::span_grow", "&& crate::segment::span_grow", LIB), + ("growth into the cursor commits nothing", SEG, + "if want > from && LAZY_COMMIT && os::commit(area.add(from), want - from).is_err() {", "if false {", LIB), + ("growth into the cursor leaves the cursor behind", SEG, + " (*seg).next_free_slice = (idx + need) as u32;\n", "", LIB), + ("growth into a free span commits nothing", SEG, + "if to > from && os::commit(area.add(from), to - from).is_err() {", "if false {", LIB), + ("growth takes a live neighbour", SEG, + "if next > (*seg).next_free_slice as usize || (*f).block_size != 0 {", "if next > (*seg).next_free_slice as usize {", LIB), + ("growth takes a free span that is too short", SEG, + "if old + flen < need {", "if false {", LIB), + ("the remainder after growth forgets it is purged", SEG, + "(*rest).purged = f_purged;", "(*rest).purged = false;", LIB), + ("growth inside the last slice commits nothing", SEG, + "} else if want > have && os::commit(area.add(have), want - have).is_err() {", "} else if false {", LIB), + ("the heap purges at first sight", HEAP, + "segment::purge_aged(s, now, since)", "segment::purge_aged(s, now, 0)", LIB), + ("a span freed just after the last look is purged", SEG, + "if now.wrapping_sub((*s).capacity) > min_age_ms", "if now.wrapping_sub((*s).capacity) + 3 > min_age_ms", LIB), + ("the heap never ticks", HEAP, + " if self.purge_next != 0 {\n self.purge_tick();\n }\n", "", LIB), + ("retire does not record the deadline", HEAP, + " if due != 0 && (self.purge_next == 0 || due < self.purge_next) {\n self.purge_next = due;\n }\n", + "", LIB), + ("a short large block reports its whole span", HEAP, + " (*p).block_size = if segment::PAGE_LAZY_COMMIT && (*p).lazy_end != 0 {", + " (*p).block_size = if false {", LIB), + ("the large cache hands out a short span for a longer block", HEAP, + " && (!segment::PAGE_LAZY_COMMIT || (*c).block_size >= size)\n", "", LIB), + ("every small page of a class is lazy", HEAP, + " let first = self.bins_seen & bit == 0;", " let first = true;", LIB), + ("two slices are not a purge candidate", SEG, + "const PURGE_MIN_SLICES: usize = if crate::types::MEDIUM_PAGE_SLICES > 2 {\n 2\n", + "const PURGE_MIN_SLICES: usize = if crate::types::MEDIUM_PAGE_SLICES > 2 {\n 3\n", LIB), + ("a trimmed huge block's chunks go back as committed", SEG, + " {\n (*seg).purged_any = true;\n (*seg).huge_trim = used;", + " {\n (*seg).huge_trim = used;", HEAPS), + ("a huge block's tail is restored from the wrong place", SEG, + "(seg.cast::().add(trim), (*seg).total_size - trim)", "(seg.cast::().add(trim), 4096)", HEAPS), + ("a huge block is visited from the reservation's end", HEAP, + " let block = (*pg).area;", " let block = seg.cast::().add((*seg).total_size - bsize);", HEAPS), +] +only = sys.argv[2] if len(sys.argv) > 2 else "" +bad = 0 +for name, path, old, new, args in M: + if only and not re.search(only, name): + continue + src = open(path, newline="", encoding="utf-8").read() + assert src.count(old) == 1, (name, src.count(old)) + open(path, "w", newline="", encoding="utf-8").write(src.replace(old, new)) + try: + r = subprocess.run(["cargo", "test", "-q", "-p", "rusty_alloc", *args], cwd=root, capture_output=True, text=True) + finally: + open(path, "w", newline="", encoding="utf-8").write(src) + out = r.stdout + r.stderr + code = r.returncode + if re.search(r"^error(\[|:)", out, re.M) and "could not compile" in out: + how, code = "DID NOT COMPILE", 0 + else: + failed = sorted(set(re.findall(r"---- (\S+) stdout ----", out))) + how = ", ".join(f.split("::")[-1] for f in failed) if failed else "crash" + verdict = "caught" if code != 0 else "MISSED" + bad += code == 0 + print(f"{verdict:7} {name}: {how}", flush=True) +print("missed:", bad) diff --git a/bench/issue63/probe.py b/bench/issue63/probe.py new file mode 100644 index 0000000..ca9d442 --- /dev/null +++ b/bench/issue63/probe.py @@ -0,0 +1,16 @@ +"""probe.py [KEY=VAL ...] -> peak working set / commit, parity, stderr tail""" +import os, sys +from pathlib import Path +sys.path.insert(0, r"E:\coding\fast-decomp-corpus") +import ab +case, jobs, arm = sys.argv[1], int(sys.argv[2]), sys.argv[3] +for kv in sys.argv[4:]: + k, v = kv.split("=", 1); os.environ[k] = v +binary = {c[0]: c[1] for c in ab.CASES}[case] +exe = Path(arm) if arm.endswith(".exe") else ab.BINS[arm] +out = Path(__file__).parent / "out" / f"{case}-{jobs}-{Path(arm).stem}.json" +d = ab.run_once(exe, binary, jobs, out) +tag = " ".join(sys.argv[4:]) or "-" +print(f"{case} j{jobs} {Path(arm).stem:22} [{tag}] ws {d['_peak_ws']/2**20:8.1f} MiB commit {d['_peak_commit']/2**20:8.1f} MiB total {d['wall_seconds']['total']:.3f}s cpu/wall {d['_cpu_over_wall']:.2f} out_bytes {d['output_bytes']}") +if os.environ.get("SHOWERR"): + print(out.with_suffix(".err").read_text(errors="replace")) diff --git a/bench/issue63/probe.rs b/bench/issue63/probe.rs new file mode 100644 index 0000000..912a20c --- /dev/null +++ b/bench/issue63/probe.rs @@ -0,0 +1,304 @@ +//! Measurement only. One wrapper both allocator arms sit under: it counts what the program +//! REQUESTS (live bytes, peak, sizes), and walks the address space at the peak and at exit to +//! see what the process COMMITTED. Nothing here calls either allocator's internals. + +#![allow(unsafe_code, clippy::all, clippy::pedantic)] +use std::alloc::{GlobalAlloc, Layout}; +use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering::Relaxed}; + +pub struct Probe(pub A); + +static LIVE: AtomicUsize = AtomicUsize::new(0); +static PEAK: AtomicUsize = AtomicUsize::new(0); +static LIVE_N: AtomicUsize = AtomicUsize::new(0); +static CALLS: AtomicUsize = AtomicUsize::new(0); +static REALLOCS: AtomicUsize = AtomicUsize::new(0); +/// Live bytes and live count by log2(size) bucket, and the same at the peak. +static BY_LOG: [AtomicUsize; 48] = [const { AtomicUsize::new(0) }; 48]; +static N_BY_LOG: [AtomicUsize; 48] = [const { AtomicUsize::new(0) }; 48]; +static PEAK_BY_LOG: [AtomicUsize; 48] = [const { AtomicUsize::new(0) }; 48]; +static PEAK_N_BY_LOG: [AtomicUsize; 48] = [const { AtomicUsize::new(0) }; 48]; +/// Next live level at which the address space is walked again. +static NEXT_SNAP: AtomicUsize = AtomicUsize::new(1 << 20); +static SNAPPING: AtomicBool = AtomicBool::new(false); +static SNAP: [AtomicUsize; 8] = [const { AtomicUsize::new(0) }; 8]; + +#[inline] +fn bucket(size: usize) -> usize { + (usize::BITS - size.max(1).leading_zeros()) as usize - 1 +} + +#[inline] +fn add(size: usize) { + CALLS.fetch_add(1, Relaxed); + LIVE_N.fetch_add(1, Relaxed); + BY_LOG[bucket(size)].fetch_add(size, Relaxed); + N_BY_LOG[bucket(size)].fetch_add(1, Relaxed); + let live = LIVE.fetch_add(size, Relaxed) + size; + if live > PEAK.load(Relaxed) { + PEAK.fetch_max(live, Relaxed); + if live >= NEXT_SNAP.load(Relaxed) && !SNAPPING.swap(true, Relaxed) { + // 3 % steps: the walk is a few hundred system calls. + NEXT_SNAP.store(live + live / 32 + (256 << 10), Relaxed); + snapshot(live); + SNAPPING.store(false, Relaxed); + } + } +} + +#[inline] +fn sub(size: usize) { + LIVE.fetch_sub(size, Relaxed); + LIVE_N.fetch_sub(1, Relaxed); + BY_LOG[bucket(size)].fetch_sub(size, Relaxed); + N_BY_LOG[bucket(size)].fetch_sub(1, Relaxed); +} + +unsafe impl GlobalAlloc for Probe { + unsafe fn alloc(&self, l: Layout) -> *mut u8 { + let p = unsafe { self.0.alloc(l) }; + if !p.is_null() { + add(l.size()); + } + p + } + unsafe fn alloc_zeroed(&self, l: Layout) -> *mut u8 { + let p = unsafe { self.0.alloc_zeroed(l) }; + if !p.is_null() { + add(l.size()); + } + p + } + unsafe fn dealloc(&self, p: *mut u8, l: Layout) { + sub(l.size()); + unsafe { self.0.dealloc(p, l) } + } + unsafe fn realloc(&self, p: *mut u8, l: Layout, new: usize) -> *mut u8 { + let q = unsafe { self.0.realloc(p, l, new) }; + if !q.is_null() { + REALLOCS.fetch_add(1, Relaxed); + sub(l.size()); + add(new); + } + q + } +} + +#[repr(C)] +struct Mbi { + base: usize, + alloc_base: usize, + alloc_protect: u32, + partition: u16, + region_size: usize, + state: u32, + protect: u32, + kind: u32, +} + +#[repr(C)] +#[derive(Default)] +struct Pmc { + cb: u32, + faults: u32, + peak_ws: usize, + ws: usize, + a: usize, + b: usize, + c: usize, + d: usize, + pagefile: usize, + peak_pagefile: usize, +} + +#[link(name = "kernel32")] +unsafe extern "system" { + fn VirtualQuery(addr: usize, mbi: *mut Mbi, len: usize) -> usize; + fn GetCurrentProcess() -> isize; + fn K32GetProcessMemoryInfo(h: isize, pmc: *mut Pmc, cb: u32) -> i32; +} + +const MEM_COMMIT: u32 = 0x1000; +const MEM_RESERVE: u32 = 0x2000; +const MEM_PRIVATE: u32 = 0x20000; + +/// One reservation (an `AllocationBase`): bytes reserved, bytes committed, committed runs. +#[derive(Clone, Copy, Default)] +struct Resv { + base: usize, + size: usize, + committed: usize, + runs: usize, +} + +struct Walk { + priv_commit: usize, + priv_reserve: usize, + other_commit: usize, + /// Committed private bytes in reservations of at least 1 MiB / under 1 MiB. + big_commit: usize, + small_commit: usize, + n_resv: usize, + top: [Resv; 24], +} + +/// Walk the whole user address space. No allocation: fixed storage only. +fn walk() -> Walk { + let mut w = Walk { + priv_commit: 0, + priv_reserve: 0, + other_commit: 0, + big_commit: 0, + small_commit: 0, + n_resv: 0, + top: [Resv::default(); 24], + }; + let mut cur = Resv::default(); + let flush = |w: &mut Walk, r: Resv| { + if r.size == 0 { + return; + } + w.n_resv += 1; + if r.size >= 1 << 20 { + w.big_commit += r.committed; + } else { + w.small_commit += r.committed; + } + // Keep the 24 largest by committed bytes. + let mut min = 0; + for i in 0..w.top.len() { + if w.top[i].committed < w.top[min].committed { + min = i; + } + } + if r.committed > w.top[min].committed { + w.top[min] = r; + } + }; + let mut addr = 0x10000usize; + let mut mbi = Mbi { + base: 0, + alloc_base: 0, + alloc_protect: 0, + partition: 0, + region_size: 0, + state: 0, + protect: 0, + kind: 0, + }; + // SAFETY: VirtualQuery writes one MEMORY_BASIC_INFORMATION into `mbi`. + while unsafe { VirtualQuery(addr, &mut mbi, size_of::()) } != 0 { + if mbi.state & (MEM_COMMIT | MEM_RESERVE) != 0 { + if mbi.kind == MEM_PRIVATE { + if mbi.alloc_base != cur.base { + flush(&mut w, cur); + cur = Resv { base: mbi.alloc_base, ..Resv::default() }; + } + cur.size += mbi.region_size; + if mbi.state == MEM_COMMIT { + cur.committed += mbi.region_size; + cur.runs += 1; + w.priv_commit += mbi.region_size; + } else { + w.priv_reserve += mbi.region_size; + } + } else if mbi.state == MEM_COMMIT { + w.other_commit += mbi.region_size; + } + } + let next = mbi.base.wrapping_add(mbi.region_size); + if next <= addr { + break; + } + addr = next; + } + flush(&mut w, cur); + w +} + +fn snapshot(live: usize) { + let w = walk(); + SNAP[0].store(live, Relaxed); + SNAP[1].store(w.priv_commit, Relaxed); + SNAP[2].store(w.priv_reserve, Relaxed); + SNAP[3].store(w.big_commit, Relaxed); + SNAP[4].store(w.small_commit, Relaxed); + SNAP[5].store(w.n_resv, Relaxed); + SNAP[6].store(LIVE_N.load(Relaxed), Relaxed); + for i in 0..48 { + PEAK_BY_LOG[i].store(BY_LOG[i].load(Relaxed), Relaxed); + PEAK_N_BY_LOG[i].store(N_BY_LOG[i].load(Relaxed), Relaxed); + } +} + +fn mib(x: usize) -> f64 { + x as f64 / (1 << 20) as f64 +} + +pub fn report() { + if std::env::var_os("FD_PROBE").is_none() { + return; + } + #[cfg(feature = "trace")] + { + unsafe extern "C" { + fn ra_trace_dump(); + } + unsafe { ra_trace_dump() }; + } + let w = walk(); + let mut pmc = Pmc::default(); + pmc.cb = size_of::() as u32; + // SAFETY: fills `pmc`, whose `cb` says how large it is. + unsafe { K32GetProcessMemoryInfo(GetCurrentProcess(), &mut pmc, pmc.cb) }; + eprintln!("[probe] calls {} reallocs {}", CALLS.load(Relaxed), REALLOCS.load(Relaxed)); + eprintln!( + "[probe] peak requested {:.2} MiB at exit: live {:.2} MiB in {} blocks", + mib(PEAK.load(Relaxed)), + mib(LIVE.load(Relaxed)), + LIVE_N.load(Relaxed) + ); + eprintln!( + "[probe] process: peak commit {:.2} MiB peak working set {:.2} MiB", + mib(pmc.peak_pagefile), + mib(pmc.peak_ws) + ); + eprintln!( + "[probe] last walk near peak: requested {:.2} MiB in {} blocks | private commit {:.2} MiB (reservations >=1 MiB: {:.2}, smaller: {:.2}) | private reserved-only {:.2} MiB | {} reservations", + mib(SNAP[0].load(Relaxed)), + SNAP[6].load(Relaxed), + mib(SNAP[1].load(Relaxed)), + mib(SNAP[3].load(Relaxed)), + mib(SNAP[4].load(Relaxed)), + mib(SNAP[2].load(Relaxed)), + SNAP[5].load(Relaxed) + ); + eprintln!( + "[probe] walk at exit: private commit {:.2} MiB (>=1 MiB: {:.2}, smaller: {:.2}) | reserved-only {:.2} MiB | image+mapped commit {:.2} MiB | {} reservations", + mib(w.priv_commit), + mib(w.big_commit), + mib(w.small_commit), + mib(w.priv_reserve), + mib(w.other_commit), + w.n_resv + ); + eprintln!("[probe] requested at the peak walk, by size (log2 bucket: blocks, MiB):"); + for i in 0..48 { + let n = PEAK_N_BY_LOG[i].load(Relaxed); + if n != 0 { + eprintln!("[probe] 2^{i:<2} {n:>9} {:>10.3}", mib(PEAK_BY_LOG[i].load(Relaxed))); + } + } + let mut top = w.top; + top.sort_by(|a, b| b.committed.cmp(&a.committed)); + eprintln!("[probe] reservations at exit by committed bytes (base, reserved MiB, committed MiB, runs):"); + for r in top.iter().filter(|r| r.committed != 0).take(16) { + eprintln!( + "[probe] {:#014x} {:>9.2} {:>9.2} {:>5}", + r.base, + mib(r.size), + mib(r.committed), + r.runs + ); + } +} diff --git a/bench/issue63/route3-big-blocks-in-chunks.patch b/bench/issue63/route3-big-blocks-in-chunks.patch new file mode 100644 index 0000000..d0c4cd4 --- /dev/null +++ b/bench/issue63/route3-big-blocks-in-chunks.patch @@ -0,0 +1,530 @@ +--- a/crates/rusty_alloc/src/arena.rs 2026-12-02 12:55:16.000000000 -0700 ++++ b/crates/rusty_alloc/src/arena.rs 2026-12-02 13:30:46.000000000 -0700 +@@ -85,6 +85,12 @@ + /// Wrapping milliseconds at which the earliest pending chunk falls due; 0 + /// when none is pending. + purge_due_ms: AtomicU32, ++ /// For a free chunk whose `committed` bit is clear: how many OS pages ++ /// from its base are committed all the same. A big block's chunk comes ++ /// back with the pages its block reached still committed ++ /// ([`chunk_release_part`]), and the next tenant commits only what it ++ /// needs past them ([`chunk_claim_part`]). 0 when nothing is known to be. ++ part: [AtomicU32; MAX_CHUNKS], + } + + /// Milliseconds of `prim::clock_now`, wrapping in `u32`, never 0 (0 marks +@@ -449,10 +455,146 @@ + /// chunk-is-zero, chunk-is-committed-in-full); the caller commits whatever it + /// touches unless the last is true. + pub fn chunk_claim(restrict_id: i32) -> Option<(*mut u8, bool, bool)> { ++ chunk_alloc_ex(restrict_id, false).map(|(p, zero, got)| (p, zero, got == SEGMENT_SIZE)) ++} ++ ++/// [`chunk_claim`] returning HOW MUCH of the chunk is committed, from its ++/// base: all of it, nothing, or the part its last tenant left ++/// ([`chunk_release_part`]). The caller commits what it touches past that. ++pub fn chunk_claim_part(restrict_id: i32) -> Option<(*mut u8, bool, usize)> { + chunk_alloc_ex(restrict_id, false) + } + +-fn chunk_alloc_ex(restrict_id: i32, commit: bool) -> Option<(*mut u8, bool, bool)> { ++/// Claim one chunk for a big block that will reach `want` bytes into it, ++/// choosing by what the free chunks have committed. For a block that is ++/// `growing` (a `realloc` that could not grow in place): the one with the ++/// most, since the block is on its way up. Otherwise: the one with the least ++/// that still covers `want`; failing that, one with nothing committed, ++/// before one with too little, because topping up a smaller chunk takes it ++/// from the block of that size that is about to come back for it, and every ++/// chunk in a mixed loop ratchets up to the largest size. Returns ++/// (chunk, chunk-is-zero, bytes committed from its base, stale), where ++/// `stale` says the chunk had been free for a whole `purge_delay` (or was ++/// never marked pending): what it has beyond `want` is then not part of a ++/// loop that is about to take it back. ++/// ++/// First fit by address (as [`chunk_claim`]) hands a 2 MiB block the chunk a ++/// 12 MiB one just left and the 12 MiB block a chunk with 2 MiB committed: ++/// six threads allocating 2, 6 and 12 MiB in a loop committed 164 MiB for ++/// 120 live. Chosen by fit, each takes back a chunk of its own size. ++#[allow(clippy::needless_range_loop)] // indexed scan over a fixed atomic table ++pub fn chunk_claim_fit( ++ restrict_id: i32, ++ want: usize, ++ growing: bool, ++) -> Option<(*mut u8, bool, usize, bool)> { ++ // Higher is better: (class, key). ++ let rank = |have: u32, want: u32| -> (u8, u32) { ++ if growing { ++ (0, have) ++ } else if have >= want { ++ (2, u32::MAX - have) ++ } else if have == 0 { ++ (1, 0) ++ } else { ++ (0, have) ++ } ++ }; ++ if crate::FIXED_REGION || (restrict_id < 0 && crate::options::is_enabled(27)) { ++ return None; ++ } ++ let want_pages = want.div_ceil(4096) as u32; ++ let whole = (SEGMENT_SIZE / 4096) as u32; ++ for _ in 0..4 { ++ // (arena, chunk, pages committed); `fits` when that covers `want`. ++ let mut best: Option<(*mut Arena, usize, u32)> = None; ++ let n = ARENA_COUNT.load(Ordering::Acquire).min(MAX_ARENAS); ++ 'scan: for id in 0..n { ++ if restrict_id >= 0 && id != restrict_id as usize { ++ continue; ++ } ++ let a = ARENAS[id].load(Ordering::Acquire); ++ if a.is_null() { ++ continue; ++ } ++ // SAFETY: arena descriptors are live for the process. ++ unsafe { ++ if restrict_id < 0 && (*a).exclusive { ++ continue; ++ } ++ let chunks = (*a).chunks_live.load(Ordering::Acquire); ++ for j in 0..chunks { ++ let (w, m) = (j / WORD_BITS, (1 as BitWord) << (j % WORD_BITS)); ++ if (*a).used[w].load(Ordering::Acquire) & m != 0 { ++ continue; ++ } ++ let have = if (*a).committed[w].load(Ordering::Acquire) & m != 0 { ++ whole ++ } else { ++ (*a).part[j].load(Ordering::Acquire) ++ }; ++ let better = match best { ++ None => true, ++ Some((_, _, b)) => rank(have, want_pages) > rank(b, want_pages), ++ }; ++ if better { ++ best = Some((a, j, have)); ++ if !growing && have == want_pages { ++ break 'scan; ++ } ++ } ++ } ++ } ++ } ++ let Some((a, j, _)) = best else { ++ break; ++ }; ++ let (w, m) = (j / WORD_BITS, (1 as BitWord) << (j % WORD_BITS)); ++ // SAFETY: live descriptor; chunk `j` is inside it. The claim is the ++ // `used` bit: whoever sets it owns the chunk's record. ++ unsafe { ++ if (*a).used[w].fetch_or(m, Ordering::AcqRel) & m != 0 { ++ continue; // taken since the scan: look again ++ } ++ let have = if (*a).committed[w].load(Ordering::Acquire) & m != 0 { ++ SEGMENT_SIZE ++ } else { ++ (*a).part[j].load(Ordering::Acquire) as usize * 4096 ++ }; ++ (*a).part[j].store(0, Ordering::Release); ++ let pending = (*a).purge_pending[w].load(Ordering::Acquire) & m != 0; ++ let stale = !pending ++ || now_ms().wrapping_sub((*a).freed_ms[j].load(Ordering::Relaxed)) >= delay_ms(); ++ let was_dirty = (*a).dirty[w].fetch_or(m, Ordering::AcqRel) & m != 0; ++ return Some(((*a).base.add(j * SEGMENT_SIZE), !was_dirty, have, stale)); ++ } ++ } ++ // Nothing free (or four lost races): the ordinary claim, which reserves ++ // another arena when it must. ++ chunk_alloc_ex(restrict_id, false).map(|(p, zero, got)| (p, zero, got, true)) ++} ++ ++/// Return one chunk whose first `bytes` bytes are committed and whose rest ++/// is not (`bytes` a multiple of the OS page size, at most the chunk). ++/// `pending` as in [`chunk_release`]. True when the address was an arena's. ++pub fn chunk_release_part(p: *mut u8, bytes: usize, pending: bool) -> bool { ++ let Some((a, off, chunks)) = find_arena(p.addr()) else { ++ return false; ++ }; ++ if !off.is_multiple_of(SEGMENT_SIZE) || off / SEGMENT_SIZE >= chunks { ++ return false; ++ } ++ let j = off / SEGMENT_SIZE; ++ // SAFETY: live descriptor; chunk `j` is inside it and still claimed by ++ // the caller, so nothing else reads its record until `chunk_release` ++ // publishes it. ++ unsafe { ++ (*a).part[j].store((bytes.min(SEGMENT_SIZE) / 4096) as u32, Ordering::Release); ++ } ++ chunk_release(p, 1, Some(bytes >= SEGMENT_SIZE), pending) ++} ++ ++fn chunk_alloc_ex(restrict_id: i32, commit: bool) -> Option<(*mut u8, bool, usize)> { + // No arenas on a one-region target: every segment comes straight from the + // region. Folding this here is what removes the registry scan from the + // segment-allocation path on a chip. +@@ -485,7 +627,7 @@ + fn chunk_alloc_inner( + restrict_id: i32, + commit: bool, +-) -> Result, CommitRefused> { ++) -> Result, CommitRefused> { + let n = ARENA_COUNT.load(Ordering::Acquire).min(MAX_ARENAS); + for id in 0..n { + if restrict_id >= 0 && id != restrict_id as usize { +@@ -534,14 +676,19 @@ + let idx = w * WORD_BITS + bit; + // Before the dirty bit: a refused commit leaves the chunk + // untouched, and still zero. ++ // How much of it is committed: all, or the part its last ++ // tenant recorded (which a full commit supersedes). + let committed = if commit { + if !commit_claimed(a, idx, 1) { + return Err(CommitRefused); + } +- true ++ SEGMENT_SIZE ++ } else if (*a).committed[w].load(Ordering::Acquire) & (1 << bit) != 0 { ++ SEGMENT_SIZE + } else { +- (*a).committed[w].load(Ordering::Acquire) & (1 << bit) != 0 ++ (*a).part[idx].load(Ordering::Acquire) as usize * 4096 + }; ++ (*a).part[idx].store(0, Ordering::Release); + let was_dirty = + (*a).dirty[w].fetch_or(1 << bit, Ordering::AcqRel) & (1 << bit) != 0; + let p = (*a).base.add(idx * SEGMENT_SIZE); +@@ -901,6 +1048,7 @@ + if os::purge(p, SEGMENT_SIZE, decommits).is_ok() { + if decommits { + (*a).committed[w].fetch_and(!m, Ordering::AcqRel); ++ (*a).part[j].store(0, Ordering::Release); + } + purged += 1; + } +--- a/crates/rusty_alloc/src/segment.rs 2026-12-02 12:55:16.000000000 -0700 ++++ b/crates/rusty_alloc/src/segment.rs 2026-12-02 13:30:48.000000000 -0700 +@@ -641,21 +641,31 @@ + pub fn segment_alloc_for(arena_id: i32, first: usize) -> Result<*mut Segment, PrimError> { + let mut init = (HEADER_SLICES + first).min(SLICES_PER_SEGMENT); + let claim = if LAZY_COMMIT { +- crate::arena::chunk_claim(arena_id) ++ crate::arena::chunk_claim_part(arena_id) + } else { +- crate::arena::chunk_alloc(arena_id).map(|(p, zero)| (p, zero, true)) ++ crate::arena::chunk_alloc(arena_id).map(|(p, zero)| (p, zero, SEGMENT_SIZE)) + }; +- let (ptr_, size, mem_zero, committed) = match claim { +- Some((p, zero, committed)) => (p, SEGMENT_SIZE, zero, committed), ++ // `had`: the whole slices already committed from the base, which a chunk ++ // that held a big block brings with it. ++ let (ptr_, size, mem_zero, had) = match claim { ++ Some((p, zero, got)) => (p, SEGMENT_SIZE, zero, got / SEGMENT_SLICE_SIZE), + None => { + if arena_id >= 0 { + return Err(0); // exclusive-arena heap and its arena is full + } + let (p, sz, zero) = reserve_backing(SEGMENT_SIZE, !LAZY_COMMIT)?; +- (p, sz, zero, !LAZY_COMMIT) ++ ( ++ p, ++ sz, ++ zero, ++ if LAZY_COMMIT { 0 } else { SLICES_PER_SEGMENT }, ++ ) + } + }; +- if !committed { ++ let committed = had == SLICES_PER_SEGMENT; ++ if had >= init { ++ init = had; ++ } else { + // The header is written next, so it is committed first. On refusal + // the memory goes back untouched: its chunk keeps a clear + // `committed` bit, a fresh reservation is released whole. +@@ -1185,6 +1195,65 @@ + crate::types::MEDIUM_PAGE_SLICES + }; + ++/// The smallest block that gets a segment of its own, as a huge block does: ++/// 1 MiB, where chunks commit on demand. ++/// ++/// A block of this size carved from its thread's segment leaves, when it is ++/// freed, a span only that thread can take back, and until the purge delay ++/// runs out it is committed memory no other thread can use. Measured at the ++/// moment of OpenTTD's peak commit on fast-decomp (issue 63, six threads): ++/// 123 MiB of 403 was such spans, in the five heaps that were not the one ++/// committing a fresh 8 MiB block. A block in its own chunk goes back to the ++/// arena, which every thread allocates from: the next big block, on any ++/// thread, takes that chunk with its pages still committed and resident. It ++/// also grows where it is, up to the chunk ([`huge_grow`]), and leaves no ++/// hole in a segment of pages. ++/// ++/// The price is address space: a 32 MiB chunk a block, of which only the ++/// block's pages are committed. ++pub const BIG_BLOCK_MIN: usize = if LAZY_COMMIT { ++ 1 << 20 ++} else { ++ crate::types::LARGE_OBJ_SIZE_MAX + 1 ++}; ++ ++/// Grow a live block that has a segment of its own to hold `bytes` bytes, ++/// if its reservation has the room: commit what the block now reaches. ++/// Returns whether it did; on false nothing has changed. ++/// ++/// # Safety ++/// `page` is the live block's page (slot 1) of the Huge segment `seg`, the ++/// block is not an aligned or guarded placement, and the caller is the ++/// thread that owns `seg`; `bytes` is more than the block's size. ++#[cold] ++pub unsafe fn huge_grow(seg: *mut Segment, page: *mut Page, bytes: usize) -> bool { ++ // SAFETY: caller contract; the range committed lies inside the ++ // segment's reservation. ++ unsafe { ++ let total = (*seg).total_size; ++ let start = (*page).area.addr() - seg.addr(); ++ let size = crate::prim::align_up(bytes, SEGMENT_SLICE_SIZE); ++ if size < bytes || size > total - start { ++ return false; ++ } ++ let reach = os::page_align_up(start + size); ++ let have = match (*seg).huge_trim { ++ 0 => total, ++ t => t, ++ }; ++ if reach > have { ++ if os::commit(seg.cast::().add(have), reach - have).is_err() { ++ crate::stats::commit_failed(); ++ return false; ++ } ++ (*seg).huge_trim = if reach >= total { 0 } else { reach }; ++ } ++ (*page).block_size = size; ++ (*page).free_is_zero = false; ++ true ++ } ++} ++ + /// What [`Page::lazy_end`] holds on a short LARGE span: only that it is + /// short. Its committed extent is its `block_size`. + const LAZY_LARGE: u8 = u8::MAX; +@@ -1935,6 +2004,20 @@ + offset: usize, + arena_id: i32, + ) -> Result<(*mut Segment, *mut u8), PrimError> { ++ huge_alloc_for(size, align, offset, arena_id, false) ++} ++ ++/// [`huge_alloc`] for a caller that knows whether the block is `growing`: a ++/// `realloc` moving a block that could not grow where it was. Such a block ++/// takes the chunk with the most committed and keeps it all; any other takes ++/// the chunk that fits and keeps at most its own size again beyond its reach. ++pub fn huge_alloc_for( ++ size: usize, ++ align: usize, ++ offset: usize, ++ arena_id: i32, ++ growing: bool, ++) -> Result<(*mut Segment, *mut u8), PrimError> { + // A garbage alignment is EINVAL, not a `debug_assert!`: this is a safe + // `pub fn`, and the mask arithmetic below is only sound for a power of + // two. Cold path (dedicated segment), so the two compares are free. +@@ -1999,7 +2082,50 @@ + } else { + chunk_bytes + }; +- let (bptr, total, mem_zero, committed) = ++ // One chunk, where chunks commit on demand: take the free chunk whose ++ // committed part suits this block (`arena::chunk_claim_fit`), and commit ++ // what the block reaches past that. What the chunk has BEYOND the reach, ++ // where that is a megabyte or more: ++ // - goes back if the chunk had been free for the whole purge delay: ++ // nothing is about to reuse it; ++ // - is kept by a growing block: a buffer freed and grown again (1 MiB, ++ // 2, 4 ... each round of a loop) takes its chunk back as it left it; ++ // - is kept by any other block up to the block's own size again, and ++ // goes back past that, so a block never holds more than twice itself. ++ let one = if chunks == 1 && LAZY_COMMIT { ++ let reach = os::page_align_up(reach.max(header)); ++ crate::arena::chunk_claim_fit(arena_id, reach, growing) ++ } else { ++ None ++ }; ++ let (bptr, total, mem_zero, committed) = if let Some((p, zero, had, stale)) = one { ++ let reach = os::page_align_up(reach.max(header)); ++ let mut got = had; ++ if reach > had { ++ // SAFETY: `p` is the base of a chunk this call has claimed. ++ if unsafe { os::commit(p.add(had), reach - had) }.is_err() { ++ crate::stats::commit_failed(); ++ let _ = crate::arena::chunk_release_part(p, had, false); ++ return Err(0); ++ } ++ got = reach; ++ } else { ++ let keep = if stale { ++ reach ++ } else if growing { ++ had ++ } else { ++ os::page_align_up(2 * reach).min(had) ++ }; ++ if had - keep >= 1 << 20 ++ // SAFETY: as above; the range is inside the chunk, past the block. ++ && unsafe { os::decommit(p.add(keep), had - keep) }.is_ok() ++ { ++ got = keep; ++ } ++ } ++ (p, chunk_bytes, zero, got) ++ } else { + match crate::arena::chunk_alloc_n_part(arena_id, chunks, reach) { + Some((p, zero, got)) => (p, chunk_bytes, zero, got), + None => { +@@ -2009,7 +2135,8 @@ + let (p, sz, zero) = reserve_backing(want, true)?; + (p, sz, zero, sz) + } +- }; ++ } ++ }; + let seg: *mut Segment = bptr.cast(); + // SAFETY: header scalars fully written below; a recycled chunk's owner + // table and the two slots a huge segment uses (0, and 1 for its page) are +@@ -2085,13 +2212,14 @@ + // `purged_any` and `huge_trim` make `huge_free` commit that tail + // again, and only it, before the chunks are recycled. A refused + // decommit changes nothing: the tail stays committed. +- if PAGE_LAZY_COMMIT { ++ if LAZY_COMMIT { + let used = os::page_align_up(block.addr() - seg.addr() + (*page).block_size); + debug_assert!(used <= committed, "a huge block reaches past its commit"); + if committed < b.size { + (*seg).purged_any = true; + (*seg).huge_trim = committed; +- } else if used < b.size ++ } else if PAGE_LAZY_COMMIT ++ && used < b.size + && os::decommit(seg.cast::().add(used), b.size - used).is_ok() + { + (*seg).purged_any = true; +@@ -2182,6 +2310,27 @@ + // Part of the run was never committed, so the arena has it marked + // uncommitted; the restore below commits it, and the release says so. + let was_short = (*seg).huge_trim != 0; ++ // A block in one chunk that never committed all of it: the chunk ++ // goes back as it is, the pages the block reached still committed ++ // and the rest not, for the next big block to take over. Nothing is ++ // committed to give memory back. (A guarded block needs the full ++ // restore below to lift its protection.) ++ if was_short ++ && !(*seg).guarded ++ && (*seg).total_size == SEGMENT_SIZE ++ && crate::arena::owns(seg.cast()) ++ { ++ let mut left = (*seg).huge_trim; ++ if delay == 0 ++ && crate::options::is_enabled(5) ++ && os::decommit(seg.cast::(), left).is_ok() ++ { ++ left = 0; ++ } ++ if crate::arena::chunk_release_part(seg.cast(), left, crate::OS_PAGES && delay > 0) { ++ return Ok(()); ++ } ++ } + if chunked && delay == 0 && crate::arena::owns(seg.cast()) { + let base = seg.cast::().add(HEADER_SLICES * SEGMENT_SLICE_SIZE); + let bytes = (*seg).total_size - HEADER_SLICES * SEGMENT_SLICE_SIZE; +--- a/crates/rusty_alloc/src/heap.rs 2026-12-02 12:55:16.000000000 -0700 ++++ b/crates/rusty_alloc/src/heap.rs 2026-12-02 13:30:48.000000000 -0700 +@@ -259,6 +259,10 @@ + /// When [`Heap::purge_tick`] last looked at this heap's free spans, in + /// milliseconds of `prim::clock_now`, wrapping. + pub purge_seen_ms: u32, ++ /// The next big block this heap allocates is one `realloc` is moving ++ /// because it could not grow in place (`segment::huge_alloc_for`). Set ++ /// by `realloc`, taken by `Heap::huge_alloc`. ++ pub grow_hint: bool, + /// One bit per bin: this heap has carved a page for it + /// (`fresh_page`; maintained only under `PAGE_LAZY_COMMIT`). + pub bins_seen: u128, +@@ -337,6 +341,7 @@ + no_reclaim: false, + purge_next: 0, + purge_seen_ms: 0, ++ grow_hint: false, + bins_seen: 0, + } + } +@@ -772,7 +777,9 @@ + unsafe { self.collect_inner(false, false) }; + } + if size > MEDIUM_OBJ_SIZE_MAX { +- let r = if size <= LARGE_OBJ_SIZE_MAX { ++ // A block of a megabyte and more gets a segment of its own ++ // where chunks commit on demand (`segment::BIG_BLOCK_MIN`). ++ let r = if size < segment::BIG_BLOCK_MIN { + self.large_alloc(size) + } else { + self.huge_alloc(size, 8, 0) +@@ -1219,6 +1226,10 @@ + if self.purge_next != 0 { + self.purge_tick(); + } ++ // EXPERIMENT v4: chunks returned to the arena and past their delay. ++ if crate::OS_PAGES && crate::options::get(15) > 0 { ++ self.stats.purges += crate::arena::purge_due(false) as u64; ++ } + let mut seg = self.segments; + while !seg.is_null() { + let was_empty = (*seg).used_pages == 0; +@@ -1422,7 +1433,12 @@ + /// an arm taken on requests above 32 MiB (callgrind, per instruction). + #[inline(never)] + fn huge_alloc(&mut self, size: usize, align: usize, offset: usize) -> (*mut u8, bool) { +- match segment::huge_alloc(size, align, offset, self.arena_id) { ++ let growing = core::mem::take(&mut self.grow_hint); ++ let r = segment::huge_alloc_for(size, align, offset, self.arena_id, growing); ++ if crate::OS_PAGES && crate::options::get(15) > 0 { ++ self.stats.purges += crate::arena::purge_due(false) as u64; ++ } ++ match r { + Ok((seg, block)) => { + // SAFETY: fresh segment we own; page slot 1 is its block's + // metadata. DELAYED + xheap route remote frees through our +--- a/crates/rusty_alloc/src/alloc.rs 2026-12-02 12:55:16.000000000 -0700 ++++ b/crates/rusty_alloc/src/alloc.rs 2026-12-02 13:30:50.000000000 -0700 +@@ -2523,12 +2523,28 @@ + unsafe fn large_grows_in_place(seg: *mut Segment, pg: *mut Page, newsize: usize) -> bool { + // SAFETY: caller contract. + unsafe { +- let flags = (*pg).flags.load(Ordering::Relaxed); +- flags & (pflags::HAS_ALIGNED | pflags::SINGLE_BLOCK | pflags::HUGE_SEGMENT) +- == pflags::SINGLE_BLOCK +- && newsize <= crate::types::LARGE_OBJ_SIZE_MAX +- && (*seg).thread_id.load(Ordering::Relaxed) == init::thread_id() +- && crate::segment::span_grow(seg, pg, newsize) ++ let flags = (*pg).flags.load(Ordering::Relaxed) ++ & (pflags::HAS_ALIGNED | pflags::SINGLE_BLOCK | pflags::HUGE_SEGMENT); ++ if (*seg).thread_id.load(Ordering::Relaxed) != init::thread_id() { ++ return false; ++ } ++ let grew = if flags == pflags::SINGLE_BLOCK | pflags::HUGE_SEGMENT { ++ // A block with a segment of its own grows inside its reservation. ++ crate::segment::huge_grow(seg, pg, newsize) ++ } else { ++ flags == pflags::SINGLE_BLOCK ++ && newsize < crate::segment::BIG_BLOCK_MIN ++ && crate::segment::span_grow(seg, pg, newsize) ++ }; ++ // A single-block span that has to move to grow is a buffer on its ++ // way up: tell the big-block allocation that follows. ++ if !grew && flags & pflags::SINGLE_BLOCK != 0 && newsize >= crate::segment::BIG_BLOCK_MIN { ++ let h = my_heap(); ++ if !h.is_null() { ++ (*h).grow_hint = true; ++ } ++ } ++ grew + } + } + diff --git a/bench/issue63/timing.py b/bench/issue63/timing.py new file mode 100644 index 0000000..c4907c9 --- /dev/null +++ b/bench/issue63/timing.py @@ -0,0 +1,25 @@ +"""timing.py FIXEXE: interleaved rounds of system / 2.6.0 / fix / system-b on the issue's cases.""" +import sys, statistics +from pathlib import Path +sys.path.insert(0, r"E:\coding\fast-decomp-corpus") +import ab +arms = {"system": ab.BINS["system"], "2.6.0": ab.BINS["rusty"], "fix": Path(sys.argv[1]), "system-b": ab.BINS["system"]} +names = list(arms) +cases = [("ninja", 1, 7), ("ninja", 6, 7), ("openttd", 6, 5)] +binary = {c[0]: c[1] for c in ab.CASES} +out = Path(__file__).parent / "out" +for case, jobs, rounds in cases: + rows = {a: [] for a in names} + for a in names: + ab.run_once(arms[a], binary[case], jobs, out / f"t-warm-{a}.json") + for r in range(rounds): + order = names[r % 4:] + names[:r % 4] + for a in order: + d = ab.run_once(arms[a], binary[case], jobs, out / f"t-{case}-{jobs}-{r}-{a}.json") + rows[a].append((d["wall_seconds"]["total"], d["_cpu_over_wall"], d["_peak_commit"] / 2**20, d["_peak_ws"] / 2**20)) + print(f"== {case} j{jobs}, {rounds} rounds") + base = [x[0] for x in rows["system"]] + for a in names: + t = [x[0] for x in rows[a]] + ratios = [x / b for x, b in zip(t, base)] + print(f" {a:9} median {statistics.median(t):7.3f}s min {min(t):7.3f}s paired ratio {statistics.median(ratios):.3f} faster {sum(1 for q in ratios if q < 1)}/{rounds} cpu/wall {statistics.median(x[1] for x in rows[a]):.2f} commit {statistics.median(x[2] for x in rows[a]):7.1f} ws {statistics.median(x[3] for x in rows[a]):7.1f} MiB", flush=True) diff --git a/bench/issue63/tr2.py b/bench/issue63/tr2.py new file mode 100644 index 0000000..590decc --- /dev/null +++ b/bench/issue63/tr2.py @@ -0,0 +1,37 @@ +import sys, collections +ev = [tuple(map(int, l.split())) for l in open(sys.argv[1])] +print("events", len(ev), "(cap 262144)", dict(collections.Counter(k for k, *_ in ev))) +span = {} # (seg, idx) -> [slices, ext_4k] +commit = collections.defaultdict(int); front = collections.defaultdict(int) +peak = (0,) +def totals(): + sl = sum(v[0] for v in span.values()); ex = sum(min(v[1], v[0] * 16) for v in span.values()) + return sl, ex +cur_sl = 0 +for j, (k, s, i, n) in enumerate(ev): + if k in (0, 1): + span[(s, i)] = [n, 0]; cur_sl += n + if k == 0: front[s] = i + n + elif k == 2: + v = span.pop((s, i), None) + if v: cur_sl -= v[0] + elif k == 3: commit[s] = i + n + elif k == 4: + if (s, i) in span: span[(s, i)][1] = n + if cur_sl > peak[0]: + peak = (cur_sl, j, {k2: list(v) for k2, v in span.items()}, dict(front), dict(commit)) +mb = lambda sl: sl * 65536 / 2**20 +sl, j, sp, fr, cm = peak +by = collections.defaultdict(lambda: [0, 0, 0]) +for (s, i), (n, e) in sp.items(): + cls = "small page (1 slice)" if n == 1 else "medium page (8 slices)" if n == 8 else "large span" + # a large span is one block: its trace 'ext' is the block size + b = by[cls]; b[0] += 1; b[1] += n * 16; b[2] += min(e, n * 16) +print(f"at span peak (event {j}): {len(sp)} spans, {mb(sl):.2f} MiB carved; segments {len(fr)}; frontier {mb(sum(fr.values())):.2f} MiB; committed {mb(sum(cm.values())):.2f} MiB") +print(f"{'kind':24} {'spans':>6} {'carved MiB':>11} {'in blocks MiB':>14} {'unused MiB':>11}") +T = [0, 0, 0] +for cls, (c, a, e) in sorted(by.items()): + print(f"{cls:24} {c:6} {a/256:11.2f} {e/256:14.2f} {(a-e)/256:11.2f}") + T[0] += c; T[1] += a; T[2] += e +print(f"{'total':24} {T[0]:6} {T[1]/256:11.2f} {T[2]/256:14.2f} {(T[1]-T[2])/256:11.2f}") +print(f"header slices: {len(fr)} x 64 KiB; committed beyond frontier {mb(sum(cm.values()) - sum(fr.values())):.2f} MiB; free spans under frontier {mb(sum(fr.values()) - sl) - len(fr)*0.0625:.2f} MiB") diff --git a/bench/issue63/tr3.py b/bench/issue63/tr3.py new file mode 100644 index 0000000..84d4ffd --- /dev/null +++ b/bench/issue63/tr3.py @@ -0,0 +1,134 @@ +"""Decompose a trace from trace_on.py at the moment of peak commit. + +usage: tr3.py [probe stderr file] +""" +import collections +import re +import sys + +ev = [tuple(map(int, l.split())) for l in open(sys.argv[1])] +PPS = 16 # 4 KiB pages per 64 KiB slice +SEG = 512 # slices per segment +MIB = 256 # pages per MiB + +committed = set() +spans = {} # global slice -> [slices, kind, ext pages] +carved = set() # slices ever carved and not yet released with their segment +huge = {} # segment page index -> block pages +peak = (0, None) + + +def snapshot(i): + return (len(committed), i, set(committed), {k: list(v) for k, v in spans.items()}, set(carved), dict(huge)) + + +count = collections.Counter() +for i, (k, a, n) in enumerate(ev): + count[k] += 1 + if k in (0, 1): + slices, flag = n & 0xFFFFF, n >> 20 + kind = "small" if slices == 1 else "medium" if (slices == 8 and flag == 1) else "large" + spans[a] = [slices, kind, 0] + carved.update(range(a, a + slices)) + elif k == 2: + spans.pop(a, None) + elif k == 4: + if a in spans: + spans[a][2] = n + elif k == 5: + committed.update(range(a, a + n)) + if len(committed) > peak[0]: + peak = snapshot(i) + elif k == 6: + committed.difference_update(range(a, a + n)) + # a whole chunk given back: its slices are no longer carved + if n >= SEG * PPS - PPS: + base = (a // PPS) // SEG * SEG + carved.difference_update(range(base, base + SEG)) + huge.pop(base * PPS, None) + elif k == 7: + huge[a] = n + +n_commit, at, com, sp, carv, hg = peak +print(f"events {len(ev)} {dict(count)}; peak commit {n_commit / MIB:.2f} MiB at event {at}") +rows = collections.OrderedDict() + + +def add(name, pages, spans_n=0, carved_pages=0): + r = rows.setdefault(name, [0, 0, 0]) + r[0] += spans_n + r[1] += pages + r[2] += carved_pages + + +seen = set() +for gs, (slices, kind, ext) in sp.items(): + pages = set(range(gs * PPS, (gs + slices) * PPS)) + c = len(pages & com) + seen |= pages + if kind == "large": + add("large blocks", c, 1, c) + else: + add(f"{kind} pages", c, 1, min(ext, c)) +live_slices = set() +for gs, (slices, _, _) in sp.items(): + live_slices.update(range(gs, gs + slices)) +free_pages = set() +for s in carv - live_slices: + free_pages.update(range(s * PPS, (s + 1) * PPS)) +add("free spans, still committed", len(free_pages & com)) +seen |= free_pages +segs = {s // SEG * SEG for s in carv} +hdr = set() +for b in segs: + hdr.update(range(b * PPS, (b + 1) * PPS)) +add("segment headers", len(hdr & com)) +seen |= hdr +hpages = set() +for base, blk in hg.items(): + # the block and its header slice + hpages.update(range(base, base + PPS + blk)) +add("huge blocks", len(hpages & com - seen), len(hg), len(hpages & com - seen)) +seen |= hpages +ahead = set() +for b in segs: + ahead.update(range(b * PPS, (b + SEG) * PPS)) +add("ahead of the cursor", len((ahead - seen) & com)) +seen |= ahead +add("elsewhere (idle chunks, huge tails)", len(com - seen)) + +print(f"{'line':38} {'spans':>6} {'committed':>10} {'in blocks':>10} {'not':>8}") +tot = [0, 0] +for name, (n, pages, cv) in rows.items(): + has = name.endswith("pages") or name.endswith("blocks") + print(f"{name:38} {n or '':>6} {pages / MIB:10.2f} " + (f"{cv / MIB:10.2f} {(pages - cv) / MIB:8.2f}" if has else "")) + tot[0] += pages +print(f"{'sum':38} {'':>6} {tot[0] / MIB:10.2f} (segments {len(segs)}, huge {len(hg)})") + +if len(sys.argv) > 2: + txt = open(sys.argv[2], errors="replace").read() + b = collections.Counter() + for m in re.finditer(r"2\^(\d+)\s+(\d+)\s+([\d.]+)", txt): + e, n, mib = int(m[1]), int(m[2]), float(m[3]) + cls = "small (to 8 KiB)" if e < 13 else "medium (to 64 KiB)" if e < 16 else "large (to 32 MiB)" if e < 25 else "huge" + b[cls] += mib + m = re.search(r"last walk near peak: requested ([\d.]+) MiB", txt) + print("requested at the probe's last peak walk:", m[1] if m else "?", "MiB:", ", ".join(f"{k} {v:.2f}" for k, v in b.items())) + +# Free spans still committed at the peak: contiguous runs, and what was being committed. +fs = sorted(s for s in (carv - live_slices) if (s * PPS) in com) +runs = [] +for s in fs: + if runs and s == runs[-1][0] + runs[-1][1] and s // SEG == runs[-1][0] // SEG: + runs[-1][1] += 1 + else: + runs.append([s, 1]) +h = collections.Counter() +for _, n in runs: + b = "1 slice" if n == 1 else "2-7" if n < 8 else "8-63 (0.5-4 MiB)" if n < 64 else "64-255 (4-16 MiB)" if n < 256 else "256+" + h[b] += n +print("free committed runs by length (MiB):", ", ".join(f"{k}: {v / 16:.1f}" for k, v in sorted(h.items())), f"| {len(runs)} runs") +k, a, n = ev[at] +print(f"the commit that set the peak: {n / MIB:.2f} MiB; largest free committed run {max((r[1] for r in runs), default=0) / 16:.1f} MiB") +big = [(i, n) for i, (k, a, n) in enumerate(ev[:at + 1]) if k == 5 and n >= 4 * MIB] +print("commits of 4 MiB and more before the peak:", len(big), "totalling", f"{sum(n for _, n in big) / MIB:.0f} MiB") diff --git a/bench/issue63/trace_on.py b/bench/issue63/trace_on.py new file mode 100644 index 0000000..f813147 --- /dev/null +++ b/bench/issue63/trace_on.py @@ -0,0 +1,122 @@ +"""TEMPORARY instrumentation, never to land: an event trace of spans, page +extends and OS commits, dumped at exit. Backs the files up first; restore with +`trace_on.py off`. + +Events are (kind, a, n): + 0 bump a = global slice (addr >> 16), n = slices | lazy kind << 20 + 1 reuse the same + 2 free a = global slice, n = slices + 4 extend a = global slice of the page, n = carved bytes / 4096 (ceil) + 5 commit a = addr >> 12, n = pages + 6 uncommit a = addr >> 12, n = pages + 7 huge a = addr >> 12 of the segment, n = block bytes / 4096 +""" +import shutil +import sys + +root = sys.argv[1] +src = root + "/crates/rusty_alloc/src/" +bak = root + "/bench/issue63/.bak/" +FILES = ["segment.rs", "page.rs", "os.rs"] +if len(sys.argv) > 2 and sys.argv[2] == "off": + for f in FILES: + shutil.copyfile(bak + f, src + f) + print("restored") + sys.exit(0) +import os + +os.makedirs(bak, exist_ok=True) +for f in FILES: + shutil.copyfile(src + f, bak + f) + + +def edit(p, pairs): + s = open(p, newline="", encoding="utf-8").read() + for old, new in pairs: + assert s.count(old) == 1, (p, old[:70], s.count(old)) + s = s.replace(old, new) + open(p, "w", newline="", encoding="utf-8").write(s) + + +edit(src + "segment.rs", [ +(""" span_mark(seg, s, idx, slices, slices); + (*s).purged = false;""", +""" span_mark(seg, s, idx, slices, slices); + crate::os::trace_ev(1, (seg.addr() >> 16) + idx, slices | (usize::from(lazy) + usize::from(large)) << 20); + (*s).purged = false;"""), +(""" span_mark(seg, start, idx, slices, 1); + (*start).lazy_end = lazy_end;""", +""" span_mark(seg, start, idx, slices, 1); + crate::os::trace_ev(0, (seg.addr() >> 16) + idx, slices | (usize::from(lazy) + usize::from(large)) << 20); + (*start).lazy_end = lazy_end;"""), +(""" let (freed_idx, freed_len) = (idx, len);""", +""" let (freed_idx, freed_len) = (idx, len); + crate::os::trace_ev(2, (seg.addr() >> 16) + idx, len);"""), +(""" Ok((seg, block))""", +""" crate::os::trace_ev(7, seg.addr() >> 12, (*page).block_size >> 12); + Ok((seg, block))"""), +]) +edit(src + "page.rs", [ +(""" (*page).capacity = (capacity + take) as u32;""", +""" (*page).capacity = (capacity + take) as u32; + crate::os::trace_ev(4, area.addr() >> 16, ((capacity + take) * bsize).div_ceil(4096));"""), +]) +edit(src + "os.rs", [ +(""" let r = unsafe { prim::commit(ptr, page_align_up(size)) };""", +""" let r = unsafe { prim::commit(ptr, page_align_up(size)) }; + if r.is_ok() { + trace_ev(5, ptr.addr() >> 12, page_align_up(size) >> 12); + }"""), +("""pub unsafe fn decommit(ptr: *mut u8, size: usize) -> Result { + // SAFETY: forwarded contract. + unsafe { prim::decommit(ptr, page_align_up(size)) } +}""", +"""pub unsafe fn decommit(ptr: *mut u8, size: usize) -> Result { + // SAFETY: forwarded contract. + let r = unsafe { prim::decommit(ptr, page_align_up(size)) }; + if r.is_ok() { + trace_ev(6, ptr.addr() >> 12, page_align_up(size) >> 12); + } + r +} + +const TRACE_CAP: usize = 1 << 20; +static TRACE: [core::sync::atomic::AtomicU64; 2 * TRACE_CAP] = + [const { core::sync::atomic::AtomicU64::new(0) }; 2 * TRACE_CAP]; +static TRACE_N: core::sync::atomic::AtomicUsize = core::sync::atomic::AtomicUsize::new(0); + +/// TEMPORARY: record one event. +#[allow(missing_docs)] +#[inline] +pub fn trace_ev(kind: u64, a: usize, n: usize) { + use core::sync::atomic::Ordering::Relaxed; + let i = TRACE_N.fetch_add(1, Relaxed); + if i < TRACE_CAP { + TRACE[2 * i + 1].store(n as u64, Relaxed); + TRACE[2 * i].store((kind << 56) | a as u64 | (1 << 63), Relaxed); + } +} + +/// TEMPORARY: write the trace to `RA_TRACE_FILE`. +#[allow(missing_docs)] +#[unsafe(no_mangle)] +pub extern "C" fn ra_trace_dump() { + use core::sync::atomic::Ordering::Relaxed; + use std::io::Write; + let n = TRACE_N.load(Relaxed).min(TRACE_CAP); + let mut out = std::string::String::new(); + for i in 0..n { + let v = TRACE[2 * i].load(Relaxed); + if v >> 63 == 0 { + continue; + } + let v = v & !(1 << 63); + out.push_str(&std::format!("{} {} {}\\n", v >> 56, v & ((1 << 56) - 1), TRACE[2 * i + 1].load(Relaxed))); + } + if let Ok(p) = std::env::var("RA_TRACE_FILE") { + let _ = std::fs::File::create(p).and_then(|mut f| f.write_all(out.as_bytes())); + } + std::eprintln!("[trace] {} events (cap {})", TRACE_N.load(Relaxed), TRACE_CAP); +}"""), +]) +print("trace on") diff --git a/bench/opscan.c b/bench/opscan.c index f0ec6f0..b074909 100644 --- a/bench/opscan.c +++ b/bench/opscan.c @@ -372,6 +372,10 @@ int main(int argc, char **argv) { else if (!strcmp(op, "calloc")) op_calloc(256, n); /* A medium zeroed block: above the direct table, so every call misses. */ else if (!strcmp(op, "calloc_big")) op_calloc(4096, n); + /* A large zeroed block (a span of its own): every reuse of a span that + * was purged in between needs no zeroing. Run under + * RUSTY_ALLOC_PURGE_DELAY=0 to purge at every free. */ + else if (!strcmp(op, "calloc_large")) op_calloc(256 * 1024, n); else if (!strcmp(op, "batch_lifo")) op_batch(64, n, 1); else if (!strcmp(op, "batch_fifo")) op_batch(64, n, 0); else if (!strcmp(op, "calloc_batch")) op_calloc_batch(64, n); diff --git a/bench/rust-globalalloc/Cargo.lock b/bench/rust-globalalloc/Cargo.lock index 3681580..1d552a9 100644 --- a/bench/rust-globalalloc/Cargo.lock +++ b/bench/rust-globalalloc/Cargo.lock @@ -23,7 +23,7 @@ dependencies = [ [[package]] name = "rusty_alloc" -version = "2.6.0" +version = "2.7.0" dependencies = [ "libc", "portable-atomic", @@ -32,7 +32,7 @@ dependencies = [ [[package]] name = "rusty_alloc-api" -version = "2.6.0" +version = "2.7.0" dependencies = [ "rusty_alloc", ] diff --git a/crates/rusty_alloc/CHANGELOG.md b/crates/rusty_alloc/CHANGELOG.md index 59a28b4..caa48a4 100644 --- a/crates/rusty_alloc/CHANGELOG.md +++ b/crates/rusty_alloc/CHANGELOG.md @@ -7,6 +7,166 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +## [2.7.0](https://github.com/Remade-With-Rust/rusty_alloc/compare/rusty_alloc-v2.6.0...rusty_alloc-v2.7.0) - 2026-12-02 + +### Semver note (read before upgrading) + +`heap::Heap` gained five public fields (`purge_next`, `purge_seen_ms`, +`bins_seen`, `queues_live`, `exiting`), `page::Page` two (`partly`, +`lazy_end`; it keeps its size) and `segment::Segment` one (`huge_trim`). +Every field of these is public, so code that builds one with a struct +literal must add them, and `cargo-semver-checks` reports it as breaking. It +ships as a minor release, as 2.2.4 and 2.6.0 did for the same class: these +are allocator state that callers obtain from the allocator (`Heap::new()`), +never construct field by field. If you build `Heap { .. }` yourself, start +from `Heap::new()` instead. + +### Changed + +- **Windows: a process commits far less memory for the same work** (issue 63). + Measured on fast-decomp, Rust 1.100, against 2.6.0 and the Windows heap, + peak commit charge (medians of interleaved runs): + + | program, threads | Windows heap | 2.6.0 | now | + |---|---:|---:|---:| + | ninja, 1 | 17.6 MiB | 34.0 | 21.9 | + | ninja, 6 | 33.4 MiB | 90.6 | 43.0 | + | OpenTTD, 6 | 361 MiB | 493 | 405 | + | Godot editor, 6 | 1,024 MiB | 1,435 | 1,097 | + + Run time against the Windows heap: OpenTTD's paired ratio is 0.950, where + 2.6.0 measured 0.966 in the same rounds; ninja's differences are inside + the noise of the runs. Six loops that free memory and take it back fault + exactly as many pages as under 2.6.0 (`bench/issue63/faults.py`). A + process of 64 threads that each touch every size class once committed + 518 MiB and now commits 134 (the Windows heap: 66). What changed, each its + own cause (`docs/plans/windows-commit-footprint.md` has the byte-exact + account). The first five are Windows only: elsewhere untouched memory is + not charged. + - **A medium page commits as it fills.** Its 512 KiB span was committed + when carved and then filled four blocks at a time, so a size class + holding one 40 KiB block charged 512 KiB. It now commits a 64 KiB slice + at a time as its blocks are carved, and carves one slice of blocks a + trip until the page is whole (`segment::PAGE_LAZY_COMMIT`). + - **The first small page of a size class commits 16 KiB, then 32, then + all 64.** A heap's first page for a class is the one that may hold three + blocks for the life of its thread. Later pages of the class commit whole. + - **A large block commits to its last OS page, not its last 64 KiB slice,** + and its usable size is what was committed. + - **A block above 32 MiB commits what it reaches, not whole 32 MiB + chunks.** A 33 MiB block committed 64 MiB. + - **A segment commits 256 KiB ahead of its carve cursor, not 4 MiB.** Every + thread's segment carried up to 4 MiB nothing had asked for. + - **Taking part of a purged free span commits the part taken.** The whole + free span was re-committed first: one slice taken from a purged 6 MiB + span committed 6 MiB. All platforms. +- **A heap gives back free spans it has seen unused for a whole + `purge_delay`.** Under the default delay (10 ms) a freed span was given + back only when the SAME segment freed another large span, or by the + collect that runs every 10,000 slow-path allocations. A heap that freed + its large spans and moved on kept them resident. Now, when a heap carves a + span, it looks at its free spans at most once a delay, and purges those + that were already free at its last look. A loop that frees, pauses past + the delay and takes the same memory back (a frame, a request) purges + nothing, as before: a first cut that purged everything due at the first + carve after a pause made such a loop's allocations 2.2 times slower, and + `a_loop_that_pauses_and_reuses_purges_nothing` holds the line. All + platforms; this is resident memory, not only commit: OpenTTD's peak + working set went from 437 to 412 MiB and Godot's from 1,416 to 1,136 MiB. +- **A large block grows in place.** `realloc` to a larger size moved every + large block: a fresh span, a copy of the whole block, and the old span left + free in the wrong size for the next growth. It now extends the block's + span into the bump cursor or into a free span that follows it, when one + does and the calling thread owns the segment (`segment::span_grow`). A + buffer grown by doubling from the cursor never moves: that shape ran + 0.97 s and runs 0.87. All platforms. +- **The wasm module is 807 bytes larger gzipped** (21,432 to 22,239), most of + it the growth in place above. +- **Free spans of two slices (128 KiB) and up are purged**, where it took + eight (512 KiB). Measured with the delay in force, medians: OpenTTD 403 MiB + at eight, 392 at two; Godot 1,165 at eight, 1,143 at two; same run time. + One slice stays exempt: it is every small page a class retires and takes + back. +- New public fields on `Heap`, `Page` and `Segment`: see the semver note above. + +- **A short-lived thread costs 14 % fewer allocator instructions** (1,416 a + thread on a probe that starts, allocates 16 blocks in, and joins 200 + threads), and **no system calls of its own** beyond its segment: a new + heap's CSPRNG seeds itself at its first draw (most heaps never draw), so + the `open`, `read` and `close` of `/dev/urandom` at every thread's first + allocation are gone; a dying thread's freed spans are no longer scheduled + for a delayed purge (its segment is freed or abandoned next, either way + purged), which was four clock reads and a `madvise` a thread; a chunk a + segment hands back records how much of it is committed, so the next + thread to take it commits none of that again (three `mprotect` a thread); + and a collect sweeps only the bin queues that may hold a page. +- **`realloc` copies up to 128 bytes in line** (was 64), on the global handle + and in a first-class heap: opscan's realloc -6.4 % instructions, `Vec` + growth -14.1 and -10.4 instructions a step. All platforms where the + realloc leaf exists (x86-64 Linux). +- **`calloc` of memory that was decommitted zeroes nothing.** A free span + purged by a decommit reads as zero once committed again (Linux + `MADV_DONTNEED`, the Darwin remap, Windows `MEM_DECOMMIT`), and taking it + now says so, as fresh memory does: a 256 KiB `calloc` of a purged span + skipped a 256 KiB `memset`. The spans a loop reuses inside the purge delay + are not purged, and are zeroed as before. +- **No panic is reachable from an allocation, and `Allocator` methods run + without their guard** on x86-64 Linux release builds. The panic sites an + `Allocator` method can reach went from 28 to 0 + (`tools/no-unwind-baseline.txt`), counted in the machine code under fat + LTO and, new, under Cargo's default release profile (no LTO, 16 codegen + units), which found two sites fat LTO's inlining had hidden. Each site was + an index the optimiser could not prove in range: the bin formula and the + arena's live chunk count now carry visible bounds, table walks go by + pointer, a bin or subprocess id out of range aborts (as a corrupted free + list does) instead of panicking, and the CSPRNG's `/dev/urandom` read and + the diagnostic writer no longer go through std paths that can panic. With + nothing left to guard, `rusty_alloc_api`'s `Allocator` impls drop the + guard that turned an unwind into an abort where the scan proves the build + (`rusty_alloc::NO_UNWIND_PROVEN`: x86-64 Linux, no debug assertions, + `opt-level` 2 or 3, default features): `Vec::new_in(RustyAlloc)` −27.6 + instructions a step (−1.09 %), now about 1 % below the same work through + `#[global_allocator]`, and −28.5 inside a `Heap` (−1.13 %). The guard + stays everywhere else, including `opt-level` `s`, `z` and 1, where a few + table indexes keep their bounds checks. Every other instrument is + unchanged to the instruction (opscan, perl, sqlite, lua, python, the Rust + workloads), with identical output. +- **`rusty_alloc` has a build script.** It reads `OPT_LEVEL` and sets one + `cfg`; no dependencies, files or network. It exists only for the line + above: no `cfg` names the optimisation level. +- **Diagnostics go to fd 2 directly on unix**, not through + `std::io::stderr()`, whose lock carries panics. Same bytes, unbuffered as + before. + +### Fixed + +- **A resident span that merged with a purged neighbour was never purged.** + The merged span was flagged purged, so that reuse would re-commit it, and + the purge pass skips flagged spans: the resident part stayed resident + until the span was reused. Such a span is now flagged `partly` and stays + a purge candidate. At exit of the OpenTTD run above the process held + 314 MiB committed with 1.4 MiB live; it now holds 86. +- **An abandoned segment's free spans were not purged by default.** The + purge before a dying thread's segment is orphaned read option 30 + (`guarded_min`, off unless guarded sampling is set) instead of + `abandoned_page_purge`, from 0.3.0 on. A dying thread's spans were purged + by its teardown collect instead; a segment abandoned with spans freed some + other way kept their pages resident until another thread adopted it. It is + unconditional now, as `options` documents. +- **`Heap::visit_blocks` reported a huge block at the wrong address.** The + block's start was derived from the end of its reservation, which was right + while a huge block's size was the whole reservation and has been wrong + since 2.2 made it the size asked for: a 33 MiB block in its 64 MiB of + chunks was reported 31 MiB above where it is. +- **An `options::set` racing the first option read could be lost.** The + thread that reads an option first parses the environment and writes the + whole option table; another thread that called `set` while that pass was + running had its value overwritten with the default. The pass now fills + only options nobody has set, so an explicit `set` always wins, with the + environment still taking precedence over the built-in defaults. Seen as a + one-in-five failure of `tests/heaps.rs` on Windows; `get` and `set` are + unchanged. + ## [2.6.0](https://github.com/Remade-With-Rust/rusty_alloc/compare/rusty_alloc-v2.5.0...rusty_alloc-v2.6.0) - 2026-11-13 ### Fixed diff --git a/crates/rusty_alloc/README.md b/crates/rusty_alloc/README.md index bc8167e..42e5a46 100644 --- a/crates/rusty_alloc/README.md +++ b/crates/rusty_alloc/README.md @@ -11,14 +11,14 @@ cross-thread frees), rebuilt from the design rather than transliterated from the C. No C anywhere in the product; the C mimalloc is a development-only differential oracle and is never a dependency. -**Status: `1.0.0` — the API is frozen; changes follow semver from here.** +**Current release: `2.7.0`.** The API is stable and follows semver. -> **Upgrade from 0.3.x or earlier — mandatory.** 0.4.0 fixed three -> platform-independent use-after-frees on the abandon → adopt → reuse path. -> **Treat 0.3.2 and earlier as unsound on every target.** +> **Upgrade from 2.5.0 or earlier.** 2.6.0 fixed two soundness bugs: a +> destroyable heap could unmap a dead thread's live blocks, and `Heap::alloc` +> could return misaligned blocks on 32-bit targets. -Tested on x86-64/aarch64 Linux, aarch64/x86-64 macOS and x86-64 Windows; -executed on `wasm32-unknown-unknown` (Node VM self-test, no emscripten). +Runs on x86-64 and aarch64 Linux, macOS and Windows, on +`wasm32-unknown-unknown` (no emscripten), and on bare-metal microcontrollers. ## What it is @@ -33,58 +33,43 @@ executed on `wasm32-unknown-unknown` (Node VM self-test, no emscripten). ## Performance (instruction counts, not seconds) Measured deterministically via callgrind instructions retired, x86-64 Linux, -`LD_PRELOAD`. Side-by-side against the field (ratio = our instructions ÷ -theirs; **lower is better**): +`LD_PRELOAD`, Rust 1.100, 2026-12-02 (2.7.0). Ratio = our instructions ÷ +theirs; **lower is better**: | workload | vs mimalloc | vs jemalloc | vs glibc | |---|---:|---:|---:| -| lua | **0.962** | **0.835** | 0.813 | +| lua | **0.957** | **0.829** | 0.809 | | perl | **0.988** | **0.889** | 0.810 | | sqlite | **0.995** | **0.976** | 0.988 | -Whole programs come in at or under mimalloc (0.5–4 %), **2–17 % under -jemalloc** (jemalloc 5.3.0) and up to 19 % under glibc. Counting only the -allocator's own instructions, rusty_alloc executes **0.44× (lua), 0.68× -(perl) and 0.70× (sqlite)** of mimalloc's. Measured 2026-11-12 (2.5.0). - -The per-operation scan (small/med/big/large/huge, calloc, realloc, aligned, -usable, batch, mixed and cross-thread ops) measures **below mimalloc on all 14 -operations**. Per-op ratios vs mimalloc: med **0.39**, big/large **0.40**, -realloc **0.41**, small and aligned **0.42**, small_touch **0.45**, xthread -**0.50**, calloc **0.52**, mixed **0.54**, usable **0.74**, batch lifo/fifo -**0.80**, huge **0.003**. - -Five of those hold ONE BLOCK LIVE at a time, so the page empties on every free -and what they measure is page retire-and-recarve rather than steady-state -service. On workloads with a real working set — the honest number for a -program — it is `liveset` **0.86** (65,536 live objects, random victim replaced -each step), `shbench` **0.85** (bulk batches released in waves) and `xthread` -**0.50** (every free performed by a non-owning thread). Wall-clock time is deliberately not claimed: the measurement box -cannot resolve it above its own noise floor, and instructions are not seconds. - -Batch is the narrowest margin, and it is the one with a story. It sat at -**1.008** after a ThreadSanitizer fix made a page-flags byte atomic, which -costs exactly one instruction because LLVM will not fold an atomic load into a -test's memory operand. That trade was kept — upstream reads the same byte -non-atomically and has the race — and the instruction was won back elsewhere on -the same path rather than by undoing it. - -`free`'s fast path is **17 instructions against mimalloc's 25**, down from 27 -at 2.2.0 and 21 at 2.4.0. The `used--` codegen floor `docs/opps.md` recorded -is closed: it took five instructions from safe Rust because LLVM will not emit -a memory-destination read-modify-write when the value must also drive a -branch, and it is two now, written directly. Resolving a pointer to its page -went from nine instructions to four: the segment header keeps a per-slice -table of page pointers. And the flags test, the one row where upstream used -to be cheaper, is gone: each page carries an owner word that holds its -thread's id only while the page is plain, so one load and one compare answer -both "is this my page" and "is it plain". The word is read atomically, so -the sanitizer that found the old flags race still sees every access. - -Correctness on real software: jq, sqlite3, python3, git, xz, zstd, lua and -perl produce **byte-identical output** under rusty_alloc, mimalloc and glibc; -the full mimalloc-bench corpus (19 configurations, including the 8–16-thread -storms) runs clean; Miri is clean over the whole target. +Whole programs come in under mimalloc (0.5–4 %), **2–17 % under jemalloc** +(5.3.0) and up to 19 % under glibc. Counting only the allocator's own +instructions, rusty_alloc executes **0.44× (lua), 0.68× (perl) and 0.71× +(sqlite)** of mimalloc's (v2.4.5). + +The per-operation scan measures **below mimalloc on all 23 operations**: +huge (2 MiB) **0.003×**, blocks above 32 MiB **0.021×**, small `realloc` +**0.36×**, `realloc` **0.38×**, med **0.39×**, `aligned_alloc` **0.39×**, +big and large **0.40×**, small and `posix_memalign` **0.42×**, small_touch +**0.45×**, xthread **0.50×**, calloc **0.52×**, mixed **0.54×**, new_batch +**0.70×**, usable **0.74×**, batch lifo/fifo **0.80×**, calloc_batch +**0.82×**. On workloads with a real working set it is `liveset` **0.86×** +(65,536 live objects, a random victim replaced each step), `shbench` +**0.83×** (bulk batches released in waves) and `xthread` **0.50×** (every +free performed by a non-owning thread). The narrowest is a 256 KiB `calloc`, +**0.97×**, where zeroing the memory is most of the work. + +`free`'s fast path is **17 instructions against mimalloc's 25**. Resolving a +pointer to its page takes four instructions through a per-slice table of page +pointers in the segment header, and each page carries an owner word that +holds its thread's id only while the page is plain, so one load and one +compare answer both "is this my page" and "is it plain". + +**Windows commit charge** on real builds is within **1.07–1.29×** of the +Windows heap (ninja, OpenTTD, Godot editor; 2.6.0 measured 1.4–2.7×), with +OpenTTD's build running in 0.95× the Windows heap's time. Medium pages and a +size class's first small page commit as they fill, and a heap gives back +free spans it has seen unused for a whole `purge_delay`. ## Embedded: 2.2-4.0x faster than `esp-alloc` on an ESP32-S3 @@ -169,8 +154,9 @@ This crate is the allocator core. For the ergonomic Rust surface (`GlobalAlloc`, first-class `Heap`, the `Allocator` trait), use [`rusty_alloc-api`](https://crates.io/crates/rusty_alloc-api). -Long-lived services should set `purge_delay >= 0` — the configuration with -flat, measured RSS. The shipped default leaves purging opt-in. +Freed memory is returned to the OS once it has been unused for `purge_delay` +(10 ms by default); a loop that frees and reallocates within that window +never refaults. Set `RUSTY_ALLOC_PURGE_DELAY` to tune it. ## Security diff --git a/crates/rusty_alloc/UNSAFE.md b/crates/rusty_alloc/UNSAFE.md index cf73d4a..9983a7b 100644 --- a/crates/rusty_alloc/UNSAFE.md +++ b/crates/rusty_alloc/UNSAFE.md @@ -10,7 +10,7 @@ Census basis: `unsafe` occurrences in CODE per file (comments stripped; `unsafe fn` signatures and the four `unsafe impl`s included). **The baseline is now MACHINE-ENFORCED** (H-11): `tools/unsafe-census.sh` counts `unsafe` in code (comments stripped) per file against -`tools/unsafe-baseline.txt` — **1223 occurrences across 25 files, 2026-11-13** +`tools/unsafe-baseline.txt` — **1290 occurrences across 25 files, 2026-12-02** — and FAILS if the total grows. Growth is not forbidden, it is required to be deliberate: add the new sites here with their purpose and audit date, then re-run with `--update` in the same commit. `cargo geiger`, the registry's @@ -20,10 +20,10 @@ unsafe in DEPENDENCIES, and ours are `libc` plus bindings-only `windows-sys`. | Module | Count | What the `unsafe` is for | Last audit | |---|---:|---|---| -| `alloc.rs` | 194 | **+14 on 2026-11-13 (the heap route, `docs/opps.md` "The `Allocator` route"):** `heap_malloc_fast` and `heap_zalloc_fast` (the bodies of `malloc` and `zalloc` with the heap's box passed in where they read the thread's: raw reads of the direct table and a pop, no reference to the heap formed) over `heap_malloc_impl`; `heap_realloc_fast` with `heap_realloc_flagged` and `heap_realloc_move_out` (the body of `realloc_live_body` and its two out-of-line halves, allocating from the named heap). Each is an `unsafe fn` and its block. No new invariant and nothing new dereferenced: the pops, the copies and the free are the existing helpers, called with the same arguments. The one thing argued afresh is that the cold symbols `malloc_dry_hb_first`, `malloc_slow_hb_first`, `zalloc_dry` and `zalloc_slow` accept a first-class heap's box where they documented the thread's: they read the box's own `deferred_due` flag and call its own generic path, and only the shared sentinel, which a `Heap` never holds, sends them to thread initialisation. The existing entry points are untouched (the LD_PRELOAD object's `.text` is byte-identical before and after). **+7 on 2026-11-12 (census 4, second round):** `free_flagged_local` (the local half of `free_general` for a caller that has the flags and has compared the owner), `malloc_slow_rare` and `zalloc_slow_rare` (the cold halves of the misses' one flag test; `&mut Heap` is formed only when the flag is clear, which the sentinel's never is), and the raw flag reads in `malloc_slow_body` / `zalloc_slow`. **+50 on 2026-11-11 (census 4, `docs/opps.md`):** the fast paths were split so their cold arms leave as tail calls, and each piece is an `unsafe fn` with its block. `free_body` (the one-compare local free, an `asm!` compare against `fs:0`) with `free_slow`, `free_slow_known` and `free_local_plain`; the dry-list arms `malloc_dry`, `malloc_dry_hb_first`, `zalloc_dry`, `malloc_or_dry_with` over `swap_trip` (writes only behind a non-null `local_free`, which the empty-page sentinel never has); `realloc_rust`, `realloc_live_body` (a leaf), `realloc_flagged`, `realloc_move_out`, `free_moved` with `free_slow_ret` / `retire_ret` (two more `asm!` gotos, the same two instructions `free_local_plain` documents); `copy_block` / `copy_small` (fixed-size overlapping copies, every access inside `[0, n)`); `usable_size_plain`. No new invariant: each forwards the contract of the function it was cut from. The public entry points: raw-pointer reads on the malloc fast path (must never form `&mut` on the shared empty-heap sentinel), pointer-derived metadata on the free path (`segment_of`/`page_of`), block-content copies in the realloc family. **+15 on 2026-08-22**: the free path's two `asm!` sites — the memory-destination `used--` whose flags drive the retire branch (its `label` block is a separate item and carries its own `unsafe`), and the fused `cmp {tid}, fs:0` in both `free_inline` and `free_general` — plus `malloc_or`/`malloc_or_slow`, which give `operator new` a fast path whose miss is a tail call. Each asm reads or writes exactly one field it already had a valid pointer to; none widens what the surrounding code could already touch. **+2 on 2026-09-24 (instruction-count campaign, LEDGER):** `realloc` split into an inline null test and `unsafe fn realloc_live(p: NonNull, ..)` — one signature, and the `NonNull::new_unchecked` sits inside the block that already called it, on a pointer the line above proved non-null. The body is the old one unchanged; nothing new is dereferenced. **+10 on 2026-09-24 (round two, LEDGER):** (a) `realloc_move`, the moving arm shared by the growth and the shrink — one `unsafe fn`, its body block, and the two call-site blocks: the old inline move code, now reached with the copy length each arm already holds; (b) `zalloc` in `malloc`'s raw-read shape — its fast-path block reads through `hb`, which may be the sentinel, exactly as `malloc` does (no `&mut`, no write unless a block was popped, which proves the heap is real), and the cold `unsafe fn zalloc_slow` that performs the sentinel test the fast path dropped (signature + block); (c) `free_local_owned` / `free_local_no_xheap`, `owner_heap` split so its heap-creating fallback is a tail call — two signatures and their two blocks, the same loads and the same `free_local_at` as before; (d) `malloc_aligned_pow2`, an `unsafe fn` only because its caller must have proven the alignment a power of two (a violation is not memory-unsafe — the bound test still refuses a mask at or above half a segment). Nothing new is dereferenced anywhere; each carries its SAFETY line. The baseline had drifted to 106 without a row edit; recorded now. **+4 on 2026-10-07 (the Miri Stacked Borrows failure on `main`):** the deferred-free hook used to fire inside `Heap::malloc_generic`, where `&mut self` is protected, so a hook that allocates re-entered the heap through a raw pointer under that borrow. It now fires at the allocation entries before any `&mut Heap` exists: `fire_deferred_if_due` (an `unsafe fn` and its block: a raw read and write of the heap's own `deferred_due` flag, then the hook) and `malloc_slow_deferred` (an `unsafe fn` and its block: the same, then the `malloc_generic` call `malloc_slow` already made). The nine entry blocks that call it existed before; nothing new is dereferenced **+13 on 2026-10-08 (vein census 3, `docs/opps.md`):** every one is a split or a re-shape of an existing path, and nothing new is dereferenced. `free_inline_impl` + `free_inline_flags_first` + `free_body` (the free fast path split by test order and by whether the page is already known: three `unsafe fn`s and the blocks that forward the contract); a second owner-test `asm!` arm whose label calls `remote_free` exactly as before; `remote_free_flagged` (an `unsafe fn`, its `unalign` block and its `remote_free` block: the same unalign `free_general` did for a remote aligned block); `realloc_live`'s page resolution (the `segment_of`/`page_of`/flags read `usable_size` did) and `realloc_move_at` replacing `realloc_move` (same allocate-copy-free, freeing through the page already resolved); `malloc_or_with`/`malloc_or_slow_with` (the `malloc_or` fast path and cold arm with a typed handler). The MSVC-unwind `sub`/`setle` arm sits inside the existing fast-path block | 2026-10-08 | -| `heap.rs` | 82 | **+2 on 2026-11-11 (census 4, `docs/opps.md`):** `park_full`, an `unsafe fn` and its block: the walk's park sequence, named so the walk can use it for the front page without collecting it twice. Owner-thread page/queue manipulation under raw pointers (no two `&mut Page` may coexist), the aligned-allocation peek, span carving. **+3 on 2026-08-19**: `try_unlink_huge_segment` split out of `remove_huge_segment`. **+15 on 2026-08-22**: `malloc_generic` split into a small entry plus `malloc_generic_walk`, with `grow_front`, `try_guarded` and `drain_delayed` as cold arms — each split adds an `unsafe fn` signature and its block while dereferencing nothing the single function did not — and the immortal `EMPTY_DELAYED` sentinel that lets the heartbeat read its list without a null test. **+2 on 2026-09-07 (P4e, §2.15 of `docs/plans/small-metal.md`)**: the reclamation fixes — one `unsafe` for the periodic `generic_collect` sweep and one for the reclaim-and-retry that runs before `malloc_generic` returns null. Both call `collect_inner`, which allocates nothing and touches only this heap’s own pages on the owner thread; each carries its SAFETY line. `malloc_generic` itself became a safe wrapper over the renamed `malloc_generic_once`, so the split added no signature. **+2 on 2026-09-08:** the medium collect-and-retry ahead of the heartbeat -- one `unsafe` around `page_collect` + `page_pop` on the bin queue front, one reading `free_is_zero` off the page just popped. Both are the SAME operations `malloc_generic_walk` performs on the same page a few lines later, on the owner thread under the heap lock: the block moves earlier, nothing new is dereferenced. Each carries its SAFETY line. **+2 on 2026-09-16 (Openheimer):** the two refuse arms in `malloc_aligned_at_slow` when `bins::aligned_at_from` reports that `block + offset + align` would wrap for a caller-chosen offset — each is one `free_local` of the block just allocated on this thread, which has not escaped. **+1 on 2026-09-24 (instruction-count campaign, LEDGER):** the medium collect-and-retry's `page_collect` + `page_pop` block became two blocks so the `saw_remote_free` latch is stored between them — same two calls on the same page, owner thread, in the same order; nothing new is dereferenced. **+1 on 2026-09-24 (round two):** a medium miss grows the front page directly — one block around the `capacity < reserved` test and the `grow_front` call, on the same page the block above just collected, which is `grow_front`'s whole contract **+2 on 2026-09-25 (CURIOSITY ROUND FOUR):** the medium arm pops the front page BEFORE collecting it — one `page_pop` block and the `free_is_zero` read beside it, the same two operations the collect-then-pop below already performs on the same owner-thread page. **+1 on 2026-10-07 (`docs/opps.md` vein census, vein 2):** `collect_inner` hands the per-heap cached large span (`Heap::large_cache`) back with `retire_span` — one block around `segment_of` on the cached page's own address and the same `retire_span` a large free performed before the cache existed, on the owner thread. **+2 the same day:** `free_large_span` — an `unsafe fn` and its block — is the large-span arm of `free_local_at` moved into its own function (double-free check, cache, free-run flag); the same operations on the same page, owner thread | 2026-10-07 | +| `alloc.rs` | 201 | **+4 on 2026-12-02 (optimization round, `docs/opps.md`):** `realloc_leaf` and `heap_realloc_leaf` (an `unsafe fn` and its block each) are the realloc leaf's pop, copy and free moved into a const-generic helper so the 65..=128-byte copy can have an arm of its own: the same operations on the same page and direct table `realloc_live_body` and `heap_realloc_fast` performed in their own blocks. `zalloc_generic_from` (an `unsafe fn`) replaces `zalloc_slow` one for one. **+3 on 2026-12-02 (issue 63):** `large_grows_in_place` (an `unsafe fn` and its block) reads the flags of a live block's page and its segment's owner, and calls `segment::span_grow` when the block is a large one this thread owns; `realloc_live_classic` calls it in one block, on the page it has just resolved. **+14 on 2026-11-13 (the heap route, `docs/opps.md` "The `Allocator` route"):** `heap_malloc_fast` and `heap_zalloc_fast` (the bodies of `malloc` and `zalloc` with the heap's box passed in where they read the thread's: raw reads of the direct table and a pop, no reference to the heap formed) over `heap_malloc_impl`; `heap_realloc_fast` with `heap_realloc_flagged` and `heap_realloc_move_out` (the body of `realloc_live_body` and its two out-of-line halves, allocating from the named heap). Each is an `unsafe fn` and its block. No new invariant and nothing new dereferenced: the pops, the copies and the free are the existing helpers, called with the same arguments. The one thing argued afresh is that the cold symbols `malloc_dry_hb_first`, `malloc_slow_hb_first`, `zalloc_dry` and `zalloc_slow` accept a first-class heap's box where they documented the thread's: they read the box's own `deferred_due` flag and call its own generic path, and only the shared sentinel, which a `Heap` never holds, sends them to thread initialisation. The existing entry points are untouched (the LD_PRELOAD object's `.text` is byte-identical before and after). **+7 on 2026-11-12 (census 4, second round):** `free_flagged_local` (the local half of `free_general` for a caller that has the flags and has compared the owner), `malloc_slow_rare` and `zalloc_slow_rare` (the cold halves of the misses' one flag test; `&mut Heap` is formed only when the flag is clear, which the sentinel's never is), and the raw flag reads in `malloc_slow_body` / `zalloc_slow`. **+50 on 2026-11-11 (census 4, `docs/opps.md`):** the fast paths were split so their cold arms leave as tail calls, and each piece is an `unsafe fn` with its block. `free_body` (the one-compare local free, an `asm!` compare against `fs:0`) with `free_slow`, `free_slow_known` and `free_local_plain`; the dry-list arms `malloc_dry`, `malloc_dry_hb_first`, `zalloc_dry`, `malloc_or_dry_with` over `swap_trip` (writes only behind a non-null `local_free`, which the empty-page sentinel never has); `realloc_rust`, `realloc_live_body` (a leaf), `realloc_flagged`, `realloc_move_out`, `free_moved` with `free_slow_ret` / `retire_ret` (two more `asm!` gotos, the same two instructions `free_local_plain` documents); `copy_block` / `copy_small` (fixed-size overlapping copies, every access inside `[0, n)`); `usable_size_plain`. No new invariant: each forwards the contract of the function it was cut from. The public entry points: raw-pointer reads on the malloc fast path (must never form `&mut` on the shared empty-heap sentinel), pointer-derived metadata on the free path (`segment_of`/`page_of`), block-content copies in the realloc family. **+15 on 2026-08-22**: the free path's two `asm!` sites — the memory-destination `used--` whose flags drive the retire branch (its `label` block is a separate item and carries its own `unsafe`), and the fused `cmp {tid}, fs:0` in both `free_inline` and `free_general` — plus `malloc_or`/`malloc_or_slow`, which give `operator new` a fast path whose miss is a tail call. Each asm reads or writes exactly one field it already had a valid pointer to; none widens what the surrounding code could already touch. **+2 on 2026-09-24 (instruction-count campaign, LEDGER):** `realloc` split into an inline null test and `unsafe fn realloc_live(p: NonNull, ..)` — one signature, and the `NonNull::new_unchecked` sits inside the block that already called it, on a pointer the line above proved non-null. The body is the old one unchanged; nothing new is dereferenced. **+10 on 2026-09-24 (round two, LEDGER):** (a) `realloc_move`, the moving arm shared by the growth and the shrink — one `unsafe fn`, its body block, and the two call-site blocks: the old inline move code, now reached with the copy length each arm already holds; (b) `zalloc` in `malloc`'s raw-read shape — its fast-path block reads through `hb`, which may be the sentinel, exactly as `malloc` does (no `&mut`, no write unless a block was popped, which proves the heap is real), and the cold `unsafe fn zalloc_slow` that performs the sentinel test the fast path dropped (signature + block); (c) `free_local_owned` / `free_local_no_xheap`, `owner_heap` split so its heap-creating fallback is a tail call — two signatures and their two blocks, the same loads and the same `free_local_at` as before; (d) `malloc_aligned_pow2`, an `unsafe fn` only because its caller must have proven the alignment a power of two (a violation is not memory-unsafe — the bound test still refuses a mask at or above half a segment). Nothing new is dereferenced anywhere; each carries its SAFETY line. The baseline had drifted to 106 without a row edit; recorded now. **+4 on 2026-10-07 (the Miri Stacked Borrows failure on `main`):** the deferred-free hook used to fire inside `Heap::malloc_generic`, where `&mut self` is protected, so a hook that allocates re-entered the heap through a raw pointer under that borrow. It now fires at the allocation entries before any `&mut Heap` exists: `fire_deferred_if_due` (an `unsafe fn` and its block: a raw read and write of the heap's own `deferred_due` flag, then the hook) and `malloc_slow_deferred` (an `unsafe fn` and its block: the same, then the `malloc_generic` call `malloc_slow` already made). The nine entry blocks that call it existed before; nothing new is dereferenced **+13 on 2026-10-08 (vein census 3, `docs/opps.md`):** every one is a split or a re-shape of an existing path, and nothing new is dereferenced. `free_inline_impl` + `free_inline_flags_first` + `free_body` (the free fast path split by test order and by whether the page is already known: three `unsafe fn`s and the blocks that forward the contract); a second owner-test `asm!` arm whose label calls `remote_free` exactly as before; `remote_free_flagged` (an `unsafe fn`, its `unalign` block and its `remote_free` block: the same unalign `free_general` did for a remote aligned block); `realloc_live`'s page resolution (the `segment_of`/`page_of`/flags read `usable_size` did) and `realloc_move_at` replacing `realloc_move` (same allocate-copy-free, freeing through the page already resolved); `malloc_or_with`/`malloc_or_slow_with` (the `malloc_or` fast path and cold arm with a typed handler). The MSVC-unwind `sub`/`setle` arm sits inside the existing fast-path block | 2026-10-08 | +| `heap.rs` | 88 | **+2 on 2026-12-02 (optimization round):** `collect_for_thread_exit`, an `unsafe fn` and its block: `collect_for_teardown` with the heap's `exiting` flag set around the same `collect_inner` call, on the owner thread. **+4 on 2026-12-02 (issue 63, `docs/plans/windows-commit-footprint.md`):** `purge_tick`, an `unsafe fn` and its block: under the heap lock it walks the heap's own segment list and calls `segment::purge_scheduled` on those with a deadline, the same call `collect_inner` makes on the same list. `carve`, an `unsafe fn` and its block inside `span_from_segments`: it forwards to `span_alloc` or `span_alloc_lazy` on the segment the caller already holds, and replaces three direct `span_alloc` calls in the existing block. **+2 on 2026-11-11 (census 4, `docs/opps.md`):** `park_full`, an `unsafe fn` and its block: the walk's park sequence, named so the walk can use it for the front page without collecting it twice. Owner-thread page/queue manipulation under raw pointers (no two `&mut Page` may coexist), the aligned-allocation peek, span carving. **+3 on 2026-08-19**: `try_unlink_huge_segment` split out of `remove_huge_segment`. **+15 on 2026-08-22**: `malloc_generic` split into a small entry plus `malloc_generic_walk`, with `grow_front`, `try_guarded` and `drain_delayed` as cold arms — each split adds an `unsafe fn` signature and its block while dereferencing nothing the single function did not — and the immortal `EMPTY_DELAYED` sentinel that lets the heartbeat read its list without a null test. **+2 on 2026-09-07 (P4e, §2.15 of `docs/plans/small-metal.md`)**: the reclamation fixes — one `unsafe` for the periodic `generic_collect` sweep and one for the reclaim-and-retry that runs before `malloc_generic` returns null. Both call `collect_inner`, which allocates nothing and touches only this heap’s own pages on the owner thread; each carries its SAFETY line. `malloc_generic` itself became a safe wrapper over the renamed `malloc_generic_once`, so the split added no signature. **+2 on 2026-09-08:** the medium collect-and-retry ahead of the heartbeat -- one `unsafe` around `page_collect` + `page_pop` on the bin queue front, one reading `free_is_zero` off the page just popped. Both are the SAME operations `malloc_generic_walk` performs on the same page a few lines later, on the owner thread under the heap lock: the block moves earlier, nothing new is dereferenced. Each carries its SAFETY line. **+2 on 2026-09-16 (Openheimer):** the two refuse arms in `malloc_aligned_at_slow` when `bins::aligned_at_from` reports that `block + offset + align` would wrap for a caller-chosen offset — each is one `free_local` of the block just allocated on this thread, which has not escaped. **+1 on 2026-09-24 (instruction-count campaign, LEDGER):** the medium collect-and-retry's `page_collect` + `page_pop` block became two blocks so the `saw_remote_free` latch is stored between them — same two calls on the same page, owner thread, in the same order; nothing new is dereferenced. **+1 on 2026-09-24 (round two):** a medium miss grows the front page directly — one block around the `capacity < reserved` test and the `grow_front` call, on the same page the block above just collected, which is `grow_front`'s whole contract **+2 on 2026-09-25 (CURIOSITY ROUND FOUR):** the medium arm pops the front page BEFORE collecting it — one `page_pop` block and the `free_is_zero` read beside it, the same two operations the collect-then-pop below already performs on the same owner-thread page. **+1 on 2026-10-07 (`docs/opps.md` vein census, vein 2):** `collect_inner` hands the per-heap cached large span (`Heap::large_cache`) back with `retire_span` — one block around `segment_of` on the cached page's own address and the same `retire_span` a large free performed before the cache existed, on the owner thread. **+2 the same day:** `free_large_span` — an `unsafe fn` and its block — is the large-span arm of `free_local_at` moved into its own function (double-free check, cache, free-run flag); the same operations on the same page, owner thread | 2026-10-07 | | `init.rs` | 44 | **+1 on 2026-11-11 (census 4, `docs/opps.md`):** the `--cfg ra_tls_local_exec` form of `heap_tls::get`, one `asm!` load through `fs` at a link-time offset (`@TPOFF`); the default build compiles the initial-exec block it always had. Thread/heap lifecycle: the initial-exec TLS slot (`global_asm!` + fs-relative asm reads), thread-pointer register reads (`fs:0`/`gs:0x30`/`tpidrro_el0`), heap-box creation/teardown, the abandonment path run inside platform TLS destructors. **+1 on 2026-09-09 (`firmware-what-is-left.md` §7.3): an ATTRIBUTE, not an operation** — `unsafe(link_section = ".rodata.…")` on `EMPTY_HEAP_BOX`, bare metal only, so the never-written sentinel lives in flash instead of costing 1,752 bytes of RAM. The token is counted because the census is a text search; the contract it rests on (raw reads only, no page ever stores its address) is the one the `Sync` impl below already carries, and a write would now fault against the flash cache instead of silently landing. `create_heap`'s template copy from it is a `ptr::read` inside the block that already existed. **+5 on 2026-09-16 (Openheimer, OH-rusty_alloc-13):** thread exit now abandons EVERY heap the dying thread still owns, not only the one in `done_slot` — a first-class heap that was never `heap_delete`d, or one installed with `set_default_heap`, used to stay DELAYED under a dead owner forever. `take_heap_owned_by` unlinks one such box under `HEAPS_LOCK` (one block: the registry walk); `thread_done` reads `owner_tid` off its own box and calls the split-out `unsafe fn thread_done_one` for the primary box and for each extra one (three sites plus the signature). Nothing new is dereferenced that the single function did not; each carries its SAFETY line. **+1 on 2026-10-30 (`docs/plans/shared-light-heap.md`, `--cfg ra_shared_light_heap` only):** `create_shared_heap_box` writes the shared box's `owner_tid` to `SHARED_TID` — a plain field write on a box it just created, done under `HEAPS_LOCK` because a dying thread's `take_heap_owned_by` reads every registered box's `owner_tid` under that lock | 2026-10-30 | -| `segment.rs` | 105 | **+2 on 2026-11-12 (census 4, second round):** `head_entry` (a span's owner-table entry is its head slot's pointer; the `u32` build derives the offset) and the `fill_owner` call in `scrub_recycled` (the whole table still cleared, through an opaque zero so it is not turned back into `memset`). **+11 on 2026-11-11 (census 4, `docs/opps.md`):** `owner_entry` / `entry_page` (the owner table now holds page pointers; `u32` offsets for the one build without header room), `slice_owner` (the table read that replaced `Page::slice_offset`), `fill_owner` in its scalar and SSE2 forms (16-byte stores of one value, each inside the run by the branch that guards it). Segment/page metadata addressing: the mask trick (`segment_of`), `page_of`'s contract-based indexing — **the bound is now PROVED for every in-segment offset by `proofs.rs` (Kani), not merely asserted** — span tiling, purge/recommit. The baseline had drifted to 36 without a row edit; recorded now. **+2 on 2026-10-04 (`docs/plans/recommit-failure-ignored.md`):** `restore_for_reuse` — an `unsafe fn` and its block — is the guard-lift and re-commit `segment_free` and `huge_free` each did inline, moved into one function so both can act on its answer: a segment whose memory the OS will not make accessible and committed again is released whole or retired in place, never recycled. It touches the same range the inline code did; `segment_free`'s own block became the expression that calls it (no net change). `span_recommit` now returns whether the span is backed (same block, same call). **+5 the same day, all `#[cfg(test)]`:** `a_failed_recommit_is_a_failed_span_not_an_unbacked_one` writes and frees the blocks it allocated (four blocks) and frees them at the end (one); each carries its SAFETY line. **+2 on 2026-10-07 (`docs/opps.md` vein census, vein 1):** `scrub_recycled` — an `unsafe fn` and its block — replaces the whole-header `write_bytes` that `segment_alloc` and `huge_alloc` did on every recycled chunk: it zeroes the 2 KB owner table (all of it for a Normal segment, entry 0 for a Huge one, which overwrites the rest) and the first `slots` page slots, inside the same header the old call covered. The other slots of a Normal segment are zeroed where the bump cursor first carves them (inside `span_alloc`'s existing block); a Huge segment reads only slots 0 and 1, and `wait_no_remote_in_flight` now scans slot 1 alone there. Nothing new is dereferenced. **+10 on 2026-10-09, all test-only:** `recommit_tests` gains the two merge tests for mechanism B of `docs/plans/recommit-failure-ignored.md` and their helpers (block writes and slot reads on the test's own live spans). The fix itself, carrying a merged neighbour's `purged` flag in `span_free`, adds none: it sits in the existing block **+9 on 2026-10-31 (segments commit on demand, `LAZY_COMMIT`):** five in production. `commit_frontier` is an `unsafe fn` (live Normal segment under its owner, `need` inside it) with one block, which commits `[commit_end, want)` of the segment's own reservation and moves `commit_end`. `segment_alloc` gains two: the commit of the header slice of the memory it just claimed, and the `os::free` that releases a fresh reservation whose header commit was refused (never published). `segment_free` gains one, a read of the dying segment's `commit_end`, `purged_any` and `guarded`. Four are in `lazy_commit_tests`: `carve_and_touch` (an `unsafe fn` and its block, which carves a span of the test's own segment and writes every byte, so a missing commit faults) and the two test bodies' blocks over segments from the tests' own exclusive arena **+5 the same day, all `#[cfg(test)]`:** `a_freed_guarded_object_recycles_its_chunk_with_purging_on` configures guarded sampling on its own heap, destroys it, and calls `free_one_guarded` (an `unsafe fn` and its block), which allocates, writes and frees one guarded object of that heap. The fix itself, committing before lifting the guard in `restore_for_reuse`, adds none **+16 the same day (a real `purge_delay`):** seven in production. `schedule_purge`, `purge_scheduled` and `purge_candidates` are each an `unsafe fn` (a live Normal segment under its owner) with one block: they read and write the segment's `purge_expire` and its free spans' `purged` and `capacity` (the free-since stamp; no reader looks at `capacity` while a span is free), and purge free spans through `os::purge`, as `span_free` and `purge_free_spans` already did. `segment_free` gains one block, `purge_free_spans` on the dying, empty segment before its chunk goes back. Nine are in `purge_delay_tests`: `freed_candidate` and `release` (an `unsafe fn` and a block each, carving and freeing spans of the tests' own exclusive-arena segment) and the test bodies' blocks over those spans and the heap blocks they allocate **Net 0 the same day (arena purge delay):** `segment_free` no longer purges a dying segment's free spans itself under a positive delay (its block is gone); the chunk goes back pending instead. `a_huge_buffer_loop_under_a_delay_never_purges_until_collected` adds one test block (writes to and frees its own huge blocks) **+7 the same day, all `#[cfg(test)]` (free-slot purge):** `free_slot_tests`: `pinned_page` reads its first block's page `reserved` count (a page lookup on a live block), then writes and frees the blocks it allocated; the pinned-page test also looks up the page of each re-allocated slot (live blocks) to prove the free list survived the purge; the three tests read a purged slot's last byte (still mapped and accessible, which is the point), refill and free the re-allocated slots, and free their pins | 2026-10-31 | +| `segment.rs` | 156 | **+5 on 2026-12-02 (optimization round):** `span_free` became a wrapper over `span_free_impl` (an `unsafe fn`; the body and its blocks are the ones `span_free` had), with `span_free_unscheduled` beside it (an `unsafe fn` and its block); `span_free` gained the wrapper's block. One more is the block of `a_decommitted_span_is_reported_zero_and_is` over spans of its own exclusive-arena segment. **+46 on 2026-12-02 (issue 63, `docs/plans/windows-commit-footprint.md`):** ten in production, net. `span_grow` (an `unsafe fn` and its block) extends a live large block's span into the bump cursor or the front of the free span that follows it, with the list and marking calls `span_alloc` and `span_free` make on the same slots, for the thread that owns the segment. `span_alloc` became a wrapper over `span_alloc_impl` (an `unsafe fn`; the body and its blocks are the ones `span_alloc` had), with `span_alloc_lazy` and `span_alloc_first` beside it (an `unsafe fn` and a block each, the same body asked to commit only the span's first slice, unit or bytes). `page_commit_to` (an `unsafe fn` and its block) commits `[lazy_end, want)` units of a live page's own span through `os::commit` and moves `lazy_end`; it replaces `span_recommit` (an `unsafe fn` and its block, gone: the free-list take now commits the bytes it takes inside `span_alloc_impl`'s existing block). `purge_aged` (an `unsafe fn` and its block) walks a live segment's free spans under its owner and purges those older than the age it is given, the loop `purge_candidates` already runs. `commit_frontier` commits from the cursor when that is above `commit_end`, `span_alloc_impl` commits a small page's first unit and a large block's OS pages at the cursor, and `huge_alloc` and `restore_for_reuse` decommit and re-commit a huge block's unused tail: all in existing blocks, all inside the segment's own reservation. Thirty-six are in `commit_footprint_tests`: `live_and_touch`, `purged_between_pins`, `release`, `large` and `kept_and_writable` (an `unsafe fn` and a block each, carving, writing and freeing spans of the tests' own exclusive-arena segment), and the test bodies' blocks over those spans and over heap blocks they allocate, write and free; each carries its SAFETY line. **+2 on 2026-11-12 (census 4, second round):** `head_entry` (a span's owner-table entry is its head slot's pointer; the `u32` build derives the offset) and the `fill_owner` call in `scrub_recycled` (the whole table still cleared, through an opaque zero so it is not turned back into `memset`). **+11 on 2026-11-11 (census 4, `docs/opps.md`):** `owner_entry` / `entry_page` (the owner table now holds page pointers; `u32` offsets for the one build without header room), `slice_owner` (the table read that replaced `Page::slice_offset`), `fill_owner` in its scalar and SSE2 forms (16-byte stores of one value, each inside the run by the branch that guards it). Segment/page metadata addressing: the mask trick (`segment_of`), `page_of`'s contract-based indexing — **the bound is now PROVED for every in-segment offset by `proofs.rs` (Kani), not merely asserted** — span tiling, purge/recommit. The baseline had drifted to 36 without a row edit; recorded now. **+2 on 2026-10-04 (`docs/plans/recommit-failure-ignored.md`):** `restore_for_reuse` — an `unsafe fn` and its block — is the guard-lift and re-commit `segment_free` and `huge_free` each did inline, moved into one function so both can act on its answer: a segment whose memory the OS will not make accessible and committed again is released whole or retired in place, never recycled. It touches the same range the inline code did; `segment_free`'s own block became the expression that calls it (no net change). `span_recommit` now returns whether the span is backed (same block, same call). **+5 the same day, all `#[cfg(test)]`:** `a_failed_recommit_is_a_failed_span_not_an_unbacked_one` writes and frees the blocks it allocated (four blocks) and frees them at the end (one); each carries its SAFETY line. **+2 on 2026-10-07 (`docs/opps.md` vein census, vein 1):** `scrub_recycled` — an `unsafe fn` and its block — replaces the whole-header `write_bytes` that `segment_alloc` and `huge_alloc` did on every recycled chunk: it zeroes the 2 KB owner table (all of it for a Normal segment, entry 0 for a Huge one, which overwrites the rest) and the first `slots` page slots, inside the same header the old call covered. The other slots of a Normal segment are zeroed where the bump cursor first carves them (inside `span_alloc`'s existing block); a Huge segment reads only slots 0 and 1, and `wait_no_remote_in_flight` now scans slot 1 alone there. Nothing new is dereferenced. **+10 on 2026-10-09, all test-only:** `recommit_tests` gains the two merge tests for mechanism B of `docs/plans/recommit-failure-ignored.md` and their helpers (block writes and slot reads on the test's own live spans). The fix itself, carrying a merged neighbour's `purged` flag in `span_free`, adds none: it sits in the existing block **+9 on 2026-10-31 (segments commit on demand, `LAZY_COMMIT`):** five in production. `commit_frontier` is an `unsafe fn` (live Normal segment under its owner, `need` inside it) with one block, which commits `[commit_end, want)` of the segment's own reservation and moves `commit_end`. `segment_alloc` gains two: the commit of the header slice of the memory it just claimed, and the `os::free` that releases a fresh reservation whose header commit was refused (never published). `segment_free` gains one, a read of the dying segment's `commit_end`, `purged_any` and `guarded`. Four are in `lazy_commit_tests`: `carve_and_touch` (an `unsafe fn` and its block, which carves a span of the test's own segment and writes every byte, so a missing commit faults) and the two test bodies' blocks over segments from the tests' own exclusive arena **+5 the same day, all `#[cfg(test)]`:** `a_freed_guarded_object_recycles_its_chunk_with_purging_on` configures guarded sampling on its own heap, destroys it, and calls `free_one_guarded` (an `unsafe fn` and its block), which allocates, writes and frees one guarded object of that heap. The fix itself, committing before lifting the guard in `restore_for_reuse`, adds none **+16 the same day (a real `purge_delay`):** seven in production. `schedule_purge`, `purge_scheduled` and `purge_candidates` are each an `unsafe fn` (a live Normal segment under its owner) with one block: they read and write the segment's `purge_expire` and its free spans' `purged` and `capacity` (the free-since stamp; no reader looks at `capacity` while a span is free), and purge free spans through `os::purge`, as `span_free` and `purge_free_spans` already did. `segment_free` gains one block, `purge_free_spans` on the dying, empty segment before its chunk goes back. Nine are in `purge_delay_tests`: `freed_candidate` and `release` (an `unsafe fn` and a block each, carving and freeing spans of the tests' own exclusive-arena segment) and the test bodies' blocks over those spans and the heap blocks they allocate **Net 0 the same day (arena purge delay):** `segment_free` no longer purges a dying segment's free spans itself under a positive delay (its block is gone); the chunk goes back pending instead. `a_huge_buffer_loop_under_a_delay_never_purges_until_collected` adds one test block (writes to and frees its own huge blocks) **+7 the same day, all `#[cfg(test)]` (free-slot purge):** `free_slot_tests`: `pinned_page` reads its first block's page `reserved` count (a page lookup on a live block), then writes and frees the blocks it allocated; the pinned-page test also looks up the page of each re-allocated slot (live blocks) to prove the free list survived the purge; the three tests read a purged slot's last byte (still mapped and accessible, which is the point), refill and free the re-allocated slots, and free their pins | 2026-10-31 | | `prim/windows.rs` | 36 | OS FFI: VirtualAlloc family, FLS destructors, QPC, BCryptGenRandom. **+3 on 2026-09-16 (Openheimer):** `range_is_reserved` (`zeroed` `MEMORY_BASIC_INFORMATION` + `VirtualQuery`, the same OS answer `unix.rs` gets from `mincore`), and `alloc_aligned` now refuses a garbage alignment and a `size + align` that wraps BEFORE it reserves anything, and releases a re-reservation that the OS placed anywhere but the aligned address it asked for instead of returning it misaligned (`VirtualFree`, one block). **+1 on 2026-09-24 (`docs/plans/youslowbro.md` §4):** `getenv` — one `GetEnvironmentVariableA` into a caller buffer of exactly the length passed, the allocation-free environment read that replaced `std::env::var`'s owned strings in the options pass (251 allocations through the global allocator on every process's first allocation, now none). **+2 on 2026-10-24 (2.2.7, the `ExitProcess` hang):** the `raw-dylib` declaration of ntdll's `RtlDllShutdownInProgress` (no arguments, returns a BOOLEAN) and the one call to it in `process_exiting`, which reads a loader flag and nothing else. Recorded late: this row was not updated in the 2.2.7 commit, and the ratchet failed on `main` from then until 2026-10-30 | 2026-10-30 | | `page.rs` | 57 | **+4 on 2026-11-12 (census 4, second round):** `remote_free_general` (the four-state retry loop, now out of line) and the straight-line NORMAL push in front of it in `remote_free` (the same exchange on the whole word, so the protocol the loom model checks is unchanged); `page_owner_assert_clear` (a debug read of the owner word). **+13 on 2026-11-11 (census 4, `docs/opps.md`):** `page_owner_sync` / `page_owner_clear` (the owner word: written only by the owning thread, a stale 0 costs speed and never correctness, a stale non-zero is asserted against in debug builds); `page_swap_pop`; `link_run` in its scalar form and its SSE2 `asm!` form (carving: two links a vector, every store the first word of one of the `n` blocks; `secure` and miri keep the scalar loop); `page_extend_inline`. Free-list links written into dead blocks, the lock-free `xthread_free` four-state protocol (loom-modeled in `tests/loom_xthread.rs`), the immortal `EMPTY_PAGE` sentinel — **+1 on 2026-09-09: the same `unsafe(link_section)` attribute as `init.rs`, placing it in flash on bare metal; its free list is permanently null, so nothing writes it**. **+8 on 2026-08-22**: `page_link_local` split out of `page_push_local` so the caller can decrement `used` in one memory-destination RMW, `page_collect_impl` const-generic over whether it also writes the protocol flag, and `USED_OFFSET` — whose value is asserted against `offset_of!(Page, used)` by a unit test, because an asm operand is not type-checked and a field reordering would silently decrement the wrong bytes **+2 on 2026-10-31 (free-slot purge):** `page_purge_free_slots`, an `unsafe fn` (owner thread, a collected live page whose blocks span two OS pages) with one block: it walks the page's own `free` and `local_free` lists through `block_next`, reads and writes the second and third words of each free block (inside its first OS page, which is never given back) and discards the block's later whole pages through `os::discard`. A page whose `free` list is still known zero is not stamped on that list. | 2026-10-31 | | `prim/unix.rs` | 35 | **+2 on 2026-11-11 (census 4, `docs/opps.md`):** `reserve_untrimmed`, an `unsafe fn` and its `mmap` block: an aligned reservation that keeps its unaligned head and tail mapped, for an arena that is never released. OS FFI: mmap family, madvise/decommit, pthread keys, /dev/urandom. **+1 on 2026-09-16 (Openheimer, OH-201):** `range_is_reserved` asks `mincore` whether a caller-supplied `manage_os_memory` range is mapped at all before it becomes an arena — one FFI call on a page-aligned probe. **+1 on 2026-09-24 (`docs/plans/youslowbro.md` §4):** `getenv` — `libc::getenv` and a byte-by-byte read of the returned C string up to its NUL or the caller buffer's end, nothing written through it; the same call upstream's prim makes, with the same standing caveat about a concurrent `setenv` **+2 on 2026-09-25:** `env_for_each` — an `unsafe extern "C"` declaration of `environ` and one block that walks it to its NULL terminator, handing each NUL-terminated entry on as a pointer; read only, with the same concurrent-`setenv` caveat as `getenv`. **+2 on 2026-10-01 (macOS):** the Apple arm of `range_is_reserved` — an `unsafe extern "C"` declaration of `mach_vm_region` and the `mach_task_self_` global, and one call per region: a read-only query of our own task into a `packed(4)` `vm_region_basic_info_64` whose 36-byte size is asserted at compile time and is exactly the word count passed, because XNU's `mincore` succeeds on unmapped ranges | 2026-10-01 | @@ -33,10 +33,10 @@ unsafe in DEPENDENCIES, and ours are `libc` plus bindings-only `windows-sys`. | `shared_light.rs` | 8 | **New 2026-10-30, `--cfg ra_shared_light_heap` only** (`docs/plans/shared-light-heap.md`; the module is absent from every default build). `stamp_if_shared` — an `unsafe fn` and its two blocks: compares a heap pointer to the shared box's (a read of the box's `heap` cell address, no field of either heap) and stores `SHARED_TID` into a segment the heap has just created or is adopting, before any of its blocks is handed out. `with_heap_locked` — an `unsafe fn` (the caller holds `SHARED_LOCK`) and its block: the one `&mut` to the shared heap, formed only under the lock that gives this thread exclusive use of it. Three call blocks (`try_alloc`, `collect`, `used_pages`), each inside a held lock. Nothing is dereferenced that a thread's own heap would not dereference on its owner thread; the lock stands in for ownership | 2026-10-30 | | `os.rs` | 16 | **+1 on 2026-11-11 (census 4, `docs/opps.md`):** the block in `reserve_aligned_forever` that calls `prim::reserve_untrimmed`. The prim-layer wrapper: commit/decommit/protect plumbing **+3 on 2026-10-31 (free-slot purge):** `discard`, an `unsafe fn` (the caller's range is committed, page-aligned and dead) with two blocks, forwarding to `prim::decommit` on Unix (which keeps the range accessible) or `prim::reset`, never a Windows decommit, which would make a live page's slots fault. | 2026-10-31 | | `prim/mock.rs` | 8 | Miri-only mock OS backend (never shipped; `cfg(miri)`) | 2026-08-06 | -| `arena.rs` | 24 | Lock-free chunk bitmap claim/verify, recycled-chunk scrubbing (the 0.1.0-alpha.2 UAF fix lives here: `wait_no_remote_in_flight` on every recycle path). The baseline had drifted to 13 without a row edit; recorded now. **+2 on 2026-09-16 (Openheimer, `docs/plans/openheimer-run.md`):** `arena_register` claims its slot with a CAS instead of a load-then-store, and the two new blocks are the REFUSE arm — `os::free` of the descriptor and of the OS mapping when the table is full or the slot was lost — so a refused arena leaks nothing. Both free memory this function allocated a few lines earlier and nothing else has seen; each carries its SAFETY line. **+1 on 2026-10-04 (`docs/plans/recommit-failure-ignored.md`):** `owns` — the range scan `chunk_free` already performs, asked without clearing the used bit, so the release path can tell an arena chunk (retire in place) from a reservation of its own (release to the OS). It reads each live descriptor's `base` and `chunks_live` and nothing else. **-1 on 2026-10-07:** `owns`, `chunk_free` and `chunk_free_n` now share one table scan, `find_arena` (`chunk_free` is `chunk_free_n(p, 1)`), so the three copies of the scan block became one. **+5 on 2026-10-31 (arena commit on claim):** `commit_claimed`, an `unsafe fn` (its caller holds the run's `used` bits and passes a live descriptor), with two blocks: one reads the run's `committed` bits, one commits the run through `os::commit` and, if the OS refuses, clears the `used` bits it was given. Two more are in `commit_tests`: the descriptor read behind `is_committed`, and the write to the first and last byte of a claimed chunk, which faults if the commit is missing **+1 the same day (segments commit on demand):** `chunk_free_marked` sets or clears the returned chunk's `committed` bit before `chunk_free_n` releases its `used` bit; the caller still holds the claim, so no other thread touches that bit until the release publishes it **+3 the same day (arena purge delay):** `chunk_free_n` and `chunk_free_marked` became wrappers of `chunk_release`, whose one block (the old `chunk_free_n` block, extended) sets or clears the run's `committed` bits, stamps `freed_ms` and sets `purge_pending` while the caller still holds the run, then releases `used`: `chunk_free_marked`'s own block is gone (-1). `purge_due` adds one block over the live descriptors: it claims each due chunk through its `used` bit (`fetch_or`, skipping chunks in use) before `os::purge` on it, clears its `committed` bit after a decommit, then releases it. Three are in `commit_tests`: the descriptor read behind `is_pending` and two writes to the test's own claimed chunk | 2026-10-31 | +| `arena.rs` | 26 | **+2 on 2026-12-02 (issue 63):** `commit_claimed_part` (an `unsafe fn` and its block) is `commit_claimed` with a byte count: it commits the first `bytes` of a run of chunks the caller has claimed, where `commit_claimed` committed all of the run, and marks only the chunks it covered whole. `commit_claimed` is now the call that passes the whole run (its block). Lock-free chunk bitmap claim/verify, recycled-chunk scrubbing (the 0.1.0-alpha.2 UAF fix lives here: `wait_no_remote_in_flight` on every recycle path). The baseline had drifted to 13 without a row edit; recorded now. **+2 on 2026-09-16 (Openheimer, `docs/plans/openheimer-run.md`):** `arena_register` claims its slot with a CAS instead of a load-then-store, and the two new blocks are the REFUSE arm — `os::free` of the descriptor and of the OS mapping when the table is full or the slot was lost — so a refused arena leaks nothing. Both free memory this function allocated a few lines earlier and nothing else has seen; each carries its SAFETY line. **+1 on 2026-10-04 (`docs/plans/recommit-failure-ignored.md`):** `owns` — the range scan `chunk_free` already performs, asked without clearing the used bit, so the release path can tell an arena chunk (retire in place) from a reservation of its own (release to the OS). It reads each live descriptor's `base` and `chunks_live` and nothing else. **-1 on 2026-10-07:** `owns`, `chunk_free` and `chunk_free_n` now share one table scan, `find_arena` (`chunk_free` is `chunk_free_n(p, 1)`), so the three copies of the scan block became one. **+5 on 2026-10-31 (arena commit on claim):** `commit_claimed`, an `unsafe fn` (its caller holds the run's `used` bits and passes a live descriptor), with two blocks: one reads the run's `committed` bits, one commits the run through `os::commit` and, if the OS refuses, clears the `used` bits it was given. Two more are in `commit_tests`: the descriptor read behind `is_committed`, and the write to the first and last byte of a claimed chunk, which faults if the commit is missing **+1 the same day (segments commit on demand):** `chunk_free_marked` sets or clears the returned chunk's `committed` bit before `chunk_free_n` releases its `used` bit; the caller still holds the claim, so no other thread touches that bit until the release publishes it **+3 the same day (arena purge delay):** `chunk_free_n` and `chunk_free_marked` became wrappers of `chunk_release`, whose one block (the old `chunk_free_n` block, extended) sets or clears the run's `committed` bits, stamps `freed_ms` and sets `purge_pending` while the caller still holds the run, then releases `used`: `chunk_free_marked`'s own block is gone (-1). `purge_due` adds one block over the live descriptors: it claims each due chunk through its `used` bit (`fetch_or`, skipping chunks in use) before `os::purge` on it, clears its `committed` bit after a decommit, then releases it. Three are in `commit_tests`: the descriptor read behind `is_pending` and two writes to the test's own claimed chunk | 2026-10-31 | | `prim/fixed.rs` | 37 | **New 2026-09-07 (P1 of `docs/plans/small-metal.md`).** The fixed-region backend for a target with no OS: memory is a `&'static mut [u8]` handed over once. **6 of the 18 are `unsafe fn` signatures the prim seam requires** (`alloc`/`free`/`commit`/`decommit`/`reset`/`protect`) whose *bodies contain no unsafe operation at all* — the free list is `AtomicUsize` arrays under a spin lock and the pointers are built with the safe `with_exposed_provenance_mut`, so this backend adds **zero** unsafe dereferences to the shipped crate. The other 12 are in `#[cfg(test)]`: two `&raw mut` static-region handoffs and ten calls through the `unsafe fn` seam, each with its SAFETY line. **+1 on 2026-09-07 (P2):** the region test became two-sided — where the shipped geometry refuses a segment-sized request from a 512 KiB region, the small profile SERVES one, so the test now frees it too. Audited at the site; the module is `allow(dead_code)` and unreachable on every platform that has an arm above it. **+7 on 2026-09-07 (P4b, §2.9/§2.10 of the same plan):** the two-ended `place` rule added ZERO unsafe to shipped code — `place` is a pure arithmetic `fn` and the scan around it is unchanged — and all seven are in `#[cfg(test)]`: one `slice::from_raw_parts_mut` carving the `REGION_ALIGN`-aligned window out of `BACKING` (replacing a `&mut *ptr` that a `repr(align(65536))` static would have needed, which rustc 1.97.1 on MSVC cannot compile), one `ptr::add` to reach that window, and five calls through the `unsafe fn` seam in the placement assertions and in `greedy_segments`, which allocates segments until refusal and frees every one before returning. Each carries its SAFETY line **+1 on 2026-09-09 (morning, `#21`):** the two-sided alignment test frees the SEGMENT_SIZE-aligned page it is served when the region straddles a boundary — `#[cfg(test)]`, banked without a row here at the time; recorded now. **+5 on 2026-09-09 (`docs/plans/finished/region-alignment-bug.md` §7): the module ships its first unsafe OPERATIONS.** (1) `unsafe impl Sync for Region` and (2) the `&mut *self.bytes.get()` in `Region::give` — the once-only handoff the Janus seam has carried since 2.0.0, moved here so the alignment travels with it; a module-wide `REGION_GIVEN` swap precedes the `&mut`, so a second `give` on any instance is refused before it could alias. (3) `unsafe impl Sync for FirstHeapBox`, the bare-metal static holding the first heap's descriptor (handed out once by `take_first_heap_box`, on the one thread such a build has). The other two are `#[cfg(test)]`: a `from_raw_parts_mut` carving the report's misaligned base out of a static for the refusal probe, and a `Box::new_zeroed().assume_init()` allocating a `Region` in place, because materialising a 64 KiB-aligned value on the stack first faults on Windows. Each carries its SAFETY line. **+2 on 2026-09-09 (`docs/plans/finished/region-alignment-dissolve.md`): zero new unsafe in shipped code** — segments now stride from the region's base, and every piece of that is safe: `stride_base` is a relaxed load, `place` takes an `origin` and does arithmetic, `install_region` aligns the base up. The two are `#[cfg(test)]`, the `--cfg ra_aligned_region` arm of the two-sided alignment test (an `alloc` and a `free` through the `unsafe fn` seam: the 2.0.4 straddle case, kept under the knob that restores the mask), and the `Box::new_zeroed().assume_init()` moved under that same cfg — the default arm is a plain `static Region` now, which a 16-byte-aligned type can be on every host toolchain. Each carries its SAFETY line. **+4 on 2026-09-09 (`docs/plans/finished/esp32-large-alloc-ceiling.md`): all four are `#[cfg(test)]`, and shipped code gained none.** The large-allocation ceiling reported from `rusty_zstd` is reproduced against the real extent allocator by `greedy_dedicated`, which serves `huge_alloc`-shaped reservations until the region refuses and frees every one before returning (two calls through the `unsafe fn` seam), plus one `alloc`/`free` pair modelling the whole segment a first small allocation claims. The fix itself -- the `ra_segment_size` geometry knob, `dedicated_segments`, `region_for_allocs` and `region_capacity` -- is arithmetic over the existing atomics and adds no unsafe operation at all. Each carries its SAFETY line | 2026-09-09 | | `prim/wasm.rs` | 6 | `memory.grow` linear-memory backend | 2026-08-06 | -| `options.rs` | 17 | Env parsing at init, registered-hook invocation. **+1 on 2026-09-24: `#[cfg(test)]` only** — `std::env::set_var` (an `unsafe fn` in edition 2024) seeding two probe variables for the in-place lookup test. Shipped code gained none: the pass itself went from 251 allocations to zero by building its keys in a stack buffer and reading through `prim::getenv` **+10 on 2026-09-25:** the one-walk environment pass (Linux) — three `unsafe fn` helpers (`strip`, `match_name`, `copy_value`) that read a NUL-terminated entry byte by byte and stop at the first mismatch or its NUL, and the blocks that call them; nothing is written through an entry | 2026-09-25 | +| `options.rs` | 18 | Env parsing at init, registered-hook invocation. **+1 on 2026-12-02 (panic sites to zero, `docs/opps.md`):** `write_stderr` on unix makes a `File` from fd 2 (`from_raw_fd`) under `ManuallyDrop`, so the descriptor is never closed and nothing else owns it; it replaces `std::io::stderr()`, whose lock carries panics an `Allocator` method may not reach. **+1 on 2026-09-24: `#[cfg(test)]` only** — `std::env::set_var` (an `unsafe fn` in edition 2024) seeding two probe variables for the in-place lookup test. Shipped code gained none: the pass itself went from 251 allocations to zero by building its keys in a stack buffer and reading through `prim::getenv` **+10 on 2026-09-25:** the one-walk environment pass (Linux) — three `unsafe fn` helpers (`strip`, `match_name`, `copy_value`) that read a NUL-terminated entry byte by byte and stop at the first mismatch or its NUL, and the blocks that call them; nothing is written through an entry | 2026-12-02 | | `stats.rs` | 3 | Volatile whole-struct snapshot of racy-by-design counters | 2026-08-06 | | `random.rs` | 2 | OS entropy seeding via the prim layer | 2026-08-08 | | `lib.rs` | 2 | **New 2026-09-07 (P3).** One `unsafe impl Sync for SingleThreadCell` — the `no_std` half of `ra_thread_local!`. With `std` the macro is `std::thread_local!` verbatim and this type does not exist; without it, a "thread-local" is a plain `static`, sound because the crate serves `no_std` only on single-threaded targets (the same standing assumption as `prim::fixed`: constant thread id, TLS destructors that never fire, a spin lock that never contends). A `no_std` build on a target that grows threads must revisit this type first — the SAFETY comment says so at the impl. **+1 on 2026-09-07 (P5): PROSE, not code.** The census is a text search, and the `compile_error!` that now forces `--cfg ra_single_threaded` on a `no_std` build names `unsafe impl Sync` in its message so the person who hits it knows what they are opting into. Counted, and left counted rather than reworded: the ratchet is allowed to be conservative, and a message that names the thing is worth one line of baseline | 2026-09-07 (P5) | diff --git a/crates/rusty_alloc/build.rs b/crates/rusty_alloc/build.rs new file mode 100644 index 0000000..1b5d3cf --- /dev/null +++ b/crates/rusty_alloc/build.rs @@ -0,0 +1,21 @@ +//! One fact the source cannot see for itself: the optimisation level. +//! +//! `rusty_alloc::NO_UNWIND_PROVEN` tells `rusty_alloc_api` it may run its +//! `Allocator` methods without the guard that turns an unwind into an abort. +//! That is true only where `tools/no-unwind-scan.sh` counts zero panic sites, +//! and the count depends on how hard the optimiser worked: zero at +//! `opt-level` 2 and 3 (fat LTO and Cargo's default release profile both), not +//! at `s`, `z` or 1, where a few table indexes keep their bounds checks. There +//! is no `cfg` for the level, but Cargo hands it to a build script. +//! +//! Reads one environment variable, writes one `cfg`. No dependencies, no +//! files, no network. + +fn main() { + println!("cargo::rustc-check-cfg=cfg(ra_opt_scanned)"); + println!("cargo::rerun-if-env-changed=OPT_LEVEL"); + println!("cargo::rerun-if-changed=build.rs"); + if matches!(std::env::var("OPT_LEVEL").as_deref(), Ok("2" | "3")) { + println!("cargo::rustc-cfg=ra_opt_scanned"); + } +} diff --git a/crates/rusty_alloc/src/alloc.rs b/crates/rusty_alloc/src/alloc.rs index 8af20c8..7a47cb7 100644 --- a/crates/rusty_alloc/src/alloc.rs +++ b/crates/rusty_alloc/src/alloc.rs @@ -767,20 +767,20 @@ pub fn zalloc(size: usize) -> *mut u8 { // `malloc_dry`. return zalloc_dry(hb, size, p); } - zalloc_slow(hb, size) + zalloc_generic_from(hb, size) } } /// [`zalloc`]'s small miss: the direct page's `free` list is dry. The swap /// trip of [`malloc_dry`], and then the zeroing with the page still in hand. /// -/// calloc's swap trip was dearer than malloc's: `zalloc_slow`, then +/// calloc's swap trip was dearer than malloc's: the old `zalloc_slow`, then /// `Heap::zalloc` trying the same dry list again, then the generic path, and /// then `usable_size` resolving the page from the block to learn how much to /// zero. Here the page is the one the fast path just read. /// /// # Safety -/// As [`malloc_dry`], `hb` first as [`zalloc_slow`] has it. +/// As [`malloc_dry`], `hb` first as [`zalloc_generic_from`] has it. #[cold] #[inline(never)] unsafe fn zalloc_dry(hb: *mut init::HeapBox, size: usize, pg: *mut Page) -> *mut u8 { @@ -793,26 +793,30 @@ unsafe fn zalloc_dry(hb: *mut init::HeapBox, size: usize, pg: *mut Page) -> *mut ptr::write_bytes(b, 0, (*pg).block_size); return b; } - zalloc_slow(hb, size) + zalloc_generic_from(hb, size) } } -/// [`zalloc`]'s miss: the sentinel test, then the heap's own zalloc. +/// [`zalloc`]'s miss: the sentinel test, then the heap's generic path. +/// +/// Every caller arrives having already asked the direct table, or knowing +/// the size is above it. This used to be `zalloc_slow`, which went through +/// `Heap::zalloc` and so asked the direct table again: dead for a size above +/// it, a size compare and a branch on every such `calloc`; and after a dry +/// page whose swap trip failed, a second pop of the same empty page. +/// +/// The one test: the sentinel's heap has the deferred-hook flag permanently +/// set (`Heap::sentinel`), so "no heap yet" and "the hook is due" are one +/// read, and both leave (census 4, vein 7). /// /// # Safety /// `hb` is `heap_box_fast()` of the calling thread. #[cold] #[inline(never)] -// (`hb` first here, unlike `malloc_slow`: calloc's size is the product it -// just computed, not an incoming register, and `size` first measured -// +1.06 Ir per calloc.) -unsafe fn zalloc_slow(hb: *mut init::HeapBox, size: usize) -> *mut u8 { - // The one test of `malloc_slow_body`: the sentinel's heap has the - // deferred-hook flag permanently set (`Heap::sentinel`), so "no heap - // yet" and "the hook is due" are one read, and both leave. With the - // hook's call gone from this body, nothing is live across a call and - // the common miss is a tail call into the heap (census 4, vein 7). - // +// (`hb` first, unlike `malloc_slow`: calloc's size is the product it just +// computed, not an incoming register, and `size` first measured +1.06 Ir +// per calloc.) +unsafe fn zalloc_generic_from(hb: *mut init::HeapBox, size: usize) -> *mut u8 { // SAFETY: a raw one-byte read of the TLS box's heap, real or sentinel; // `&mut Heap` is formed only when the flag is clear. unsafe { @@ -820,15 +824,15 @@ unsafe fn zalloc_slow(hb: *mut init::HeapBox, size: usize) -> *mut u8 { if (*h).deferred_due { return zalloc_slow_rare(hb, size); } - (*h).zalloc(size) + (*h).zalloc_generic(size) } } -/// The rare half of [`zalloc_slow`]: no heap yet, or the deferred-free hook -/// is due. +/// The rare half of [`zalloc_generic_from`]: no heap yet, or the +/// deferred-free hook is due. /// /// # Safety -/// As [`zalloc_slow`]. +/// As [`zalloc_generic_from`]. #[cold] #[inline(never)] unsafe fn zalloc_slow_rare(hb: *mut init::HeapBox, size: usize) -> *mut u8 { @@ -2271,9 +2275,37 @@ unsafe fn realloc_live_body(p: ptr::NonNull, newsize: usize) -> *mut u8 { } else { newsize }; + // Copies of 65..=128 bytes take the leaf too, on an arm of their own, + // so that a shorter copy asks exactly the question it asked before. if copy > 64 { - return realloc_move_out::(p, newsize, copy, pg); + if copy > SMALL_COPY_MAX { + return realloc_move_out::(p, newsize, copy, pg); + } + return realloc_leaf::(p, newsize, copy, pg); } + realloc_leaf::(p, newsize, copy, pg) + } +} + +/// The move of [`realloc_live_body`] as a leaf: pop a block of the new size +/// from this thread's direct table, copy, free the old block. `BIG`: the copy +/// is 65..=128 bytes (else at most 64), so it is two 64-byte copies with no +/// ladder above them. +/// +/// # Safety +/// As [`realloc_move_at`], with `pg == page_of(segment_of(p), p)` a plain +/// page and `copy <= SMALL_COPY_MAX`. +#[inline(always)] +unsafe fn realloc_leaf( + p: *mut u8, + newsize: usize, + copy: usize, + pg: *mut Page, +) -> *mut u8 { + // SAFETY: as `realloc_live_body`: `direct` entries are live pages of this + // thread's heap or the immortal empty page, and a non-null pop is a + // fresh block of at least `newsize >= copy` bytes, distinct from `p`. + unsafe { if newsize <= SMALL_SIZE_MAX { let hb = init::heap_box_fast(); let h = (*hb).heap.get(); @@ -2283,12 +2315,17 @@ unsafe fn realloc_live_body(p: ptr::NonNull, newsize: usize) -> *mut u8 { { (*h).stats.allocs += 1; } - copy_small(p, np, copy); + if BIG { + core::ptr::copy_nonoverlapping(p, np, 64); + core::ptr::copy_nonoverlapping(p.add(copy - 64), np.add(copy - 64), 64); + } else { + copy_small(p, np, copy); + } stat_realloc(false); return free_moved(p, pg, np); } } - realloc_move_out::(p, newsize, copy, pg) + realloc_move_out::(p, newsize, copy, pg) } } @@ -2479,6 +2516,16 @@ unsafe fn realloc_live_classic(p: ptr::NonNull, newsize: usize) -> *mut u8 { // growth arm paid that register's push and pop and the alignment pair // that came with it. let copy = if newsize > usable { + // A LARGE block grows where it is when what follows its span has + // the room (`segment::span_grow`): no fresh span, no copy, and no + // old span left behind in the wrong size. + // SAFETY: `pg` is `p`'s live page; a single-block page that is + // neither huge nor aligned is a large span of a Normal segment, and + // the owner check makes this thread the one that may reshape it. + if unsafe { large_grows_in_place(seg, pg, newsize) } { + stat_realloc(true); + return p; + } // A growth copies the whole old block. usable } else if newsize >= usable / 2 { @@ -2504,6 +2551,24 @@ unsafe fn realloc_live_classic(p: ptr::NonNull, newsize: usize) -> *mut u8 { unsafe { realloc_move_at(p, newsize, copy, seg, pg) } } +/// Whether the block on `pg` is a large one this thread owns and has just +/// been grown in place to `newsize` bytes. +/// +/// # Safety +/// `pg` is the live page of a live block of ours in `seg`. +#[inline] +unsafe fn large_grows_in_place(seg: *mut Segment, pg: *mut Page, newsize: usize) -> bool { + // SAFETY: caller contract. + unsafe { + let flags = (*pg).flags.load(Ordering::Relaxed); + flags & (pflags::HAS_ALIGNED | pflags::SINGLE_BLOCK | pflags::HUGE_SEGMENT) + == pflags::SINGLE_BLOCK + && newsize <= crate::types::LARGE_OBJ_SIZE_MAX + && (*seg).thread_id.load(Ordering::Relaxed) == init::thread_id() + && crate::segment::span_grow(seg, pg, newsize) + } +} + /// Allocate, copy `copy` bytes and free `p`, for a caller that has resolved /// `p`'s segment and page. /// @@ -2568,6 +2633,16 @@ unsafe fn copy_block(src: *const u8, dst: *mut u8, n: usize) { } } +/// The longest copy the realloc leaf makes in line, without `memcpy`. +/// +/// It was 64. The rung above it, 65 to 128 bytes, is the copy of every +/// growth out of a 128-byte block or a 96- or 112-byte one, and it left the +/// frameless leaf for `realloc_move_out`: three pushes, three pops, the +/// register moves for the call and `memcpy`'s own size dispatch around the +/// same eight loads and eight stores this does in line +/// (`realloc_leaf::`). +const SMALL_COPY_MAX: usize = 128; + /// Copy `n <= 64` bytes without a call or a loop. /// /// # Safety @@ -2906,7 +2981,7 @@ pub unsafe fn heap_zalloc_fast(hb: *mut init::HeapBox, size: usize) -> *mut u8 { } return zalloc_dry(hb, size, p); } - zalloc_slow(hb, size) + zalloc_generic_from(hb, size) } } @@ -2962,9 +3037,32 @@ pub unsafe fn heap_realloc_fast( } else { newsize }; + // As `realloc_live_body`: 65..=128 bytes on a leaf arm of their own. if copy > 64 { - return heap_realloc_move_out::(hb, p, newsize, copy, pg); + if copy > SMALL_COPY_MAX { + return heap_realloc_move_out::(hb, p, newsize, copy, pg); + } + return heap_realloc_leaf::(hb, p, newsize, copy, pg); } + heap_realloc_leaf::(hb, p, newsize, copy, pg) + } +} + +/// [`realloc_leaf`] from `hb`'s direct table. +/// +/// # Safety +/// As [`heap_realloc_fast`], with `pg == page_of(segment_of(p), p)` a plain +/// page and `copy <= SMALL_COPY_MAX` (more than 64 exactly when `BIG`). +#[inline(always)] +unsafe fn heap_realloc_leaf( + hb: *mut init::HeapBox, + p: *mut u8, + newsize: usize, + copy: usize, + pg: *mut Page, +) -> *mut u8 { + // SAFETY: as `heap_realloc_fast`. + unsafe { if newsize <= SMALL_SIZE_MAX { let h = (*hb).heap.get(); let np = crate::page::page_pop((*h).direct[crate::types::wsize_from_size(newsize)]); @@ -2973,12 +3071,17 @@ pub unsafe fn heap_realloc_fast( { (*h).stats.allocs += 1; } - copy_small(p, np, copy); + if BIG { + core::ptr::copy_nonoverlapping(p, np, 64); + core::ptr::copy_nonoverlapping(p.add(copy - 64), np.add(copy - 64), 64); + } else { + copy_small(p, np, copy); + } stat_realloc(false); return free_moved(p, pg, np); } } - heap_realloc_move_out::(hb, p, newsize, copy, pg) + heap_realloc_move_out::(hb, p, newsize, copy, pg) } } diff --git a/crates/rusty_alloc/src/arena.rs b/crates/rusty_alloc/src/arena.rs index d5d2928..28d1962 100644 --- a/crates/rusty_alloc/src/arena.rs +++ b/crates/rusty_alloc/src/arena.rs @@ -85,6 +85,13 @@ pub struct Arena { /// Wrapping milliseconds at which the earliest pending chunk falls due; 0 /// when none is pending. purge_due_ms: AtomicU32, + /// For a free chunk whose `committed` bit is clear: how many 4 KiB pages + /// from its base are committed all the same, 0 when none are known to + /// be. A Normal segment commits from its base as it carves, so the chunk + /// it returns has a committed prefix, and the next tenant need not + /// commit it again ([`chunk_claim_part`], [`chunk_release_part`]). + /// Written only by the holder of the chunk's `used` bit. + part: [AtomicU32; MAX_CHUNKS], } /// Milliseconds of `prim::clock_now`, wrapping in `u32`, never 0 (0 marks @@ -99,6 +106,21 @@ fn delay_ms() -> u32 { } /// Arm `a`'s deadline for `due` unless an earlier one is already armed. +impl Arena { + /// The live chunk count, bounded by the tables' length. + /// + /// It never exceeds `MAX_CHUNKS` (registration and in-place extension + /// both refuse more), but an atomic load says nothing to the optimiser, + /// so every bitmap index derived from it carried a bounds check and a + /// branch to `panic_bounds_check`: eleven of the panic sites an + /// `Allocator` method can reach were these. The `min` is one compare and + /// a conditional move per call, and it states the bound once. + #[inline(always)] + fn live_chunks(&self) -> usize { + self.chunks_live.load(Ordering::Acquire).min(MAX_CHUNKS) + } +} + fn arm(a: &Arena, due: u32) { let due = due.max(1); let mut cur = a.purge_due_ms.load(Ordering::Acquire); @@ -121,7 +143,11 @@ fn arm(a: &Arena, due: u32) { /// Set bits `from..to` of a chunk bitmap. fn set_bits(map: &[AtomicBitWord], from: usize, to: usize) { for j in from..to { - map[j / WORD_BITS].fetch_or(1 << (j % WORD_BITS), Ordering::AcqRel); + // `get`, not `[]`: no bounds-check panic on an allocator path + // (`tools/no-unwind-scan.sh`). The caller's range is in the map. + if let Some(w) = map.get(j / WORD_BITS) { + w.fetch_or(1 << (j % WORD_BITS), Ordering::AcqRel); + } } } @@ -136,32 +162,62 @@ fn set_bits(map: &[AtomicBitWord], from: usize, to: usize) { /// `a` is a live descriptor and `start..start + n` lies inside its live /// chunks. unsafe fn commit_claimed(a: *mut Arena, start: usize, n: usize) -> bool { + // SAFETY: forwarded contract. + unsafe { commit_claimed_part(a, start, n, n * SEGMENT_SIZE).is_some() } +} + +/// [`commit_claimed`] for a tenant that will use only the run's first +/// `bytes` bytes (a huge block): where the run is not committed already, +/// only that much is committed, and only the chunks it covers whole are +/// marked. Returns how many bytes from the run's start are sure to be +/// committed, which is all of it when it was committed already; `None` when +/// the OS refuses (the claim is then released). +/// +/// # Safety +/// As [`commit_claimed`]; `0 < bytes <= n * SEGMENT_SIZE`, a multiple of the +/// OS page size. +unsafe fn commit_claimed_part( + a: *mut Arena, + start: usize, + n: usize, + bytes: usize, +) -> Option { + let whole = n * SEGMENT_SIZE; if !crate::OS_PAGES { - return true; // memory there is committed whatever the bits say + return Some(whole); // memory there is committed whatever the bits say } + // The run's end, bounded by the tables' length for the optimiser (the + // contract already puts it inside the arena's live chunks; see + // `Arena::live_chunks`). + let end = start.saturating_add(n).min(MAX_CHUNKS); // SAFETY: live descriptor (caller contract). let all = unsafe { - (start..start + n).all(|j| { + (start..end).all(|j| { (*a).committed[j / WORD_BITS].load(Ordering::Acquire) & (1 << (j % WORD_BITS)) != 0 }) }; if all { - return true; + return Some(whole); } + let bytes = bytes.min(whole); // SAFETY: the run lies inside the arena's reservation (caller contract) // and is ours alone while its `used` bits are set. Committing a chunk // that already is committed keeps its contents on both platforms. unsafe { let p = (*a).base.add(start * SEGMENT_SIZE); - if os::commit(p, n * SEGMENT_SIZE).is_err() { - for j in start..start + n { + if os::commit(p, bytes).is_err() { + for j in start..end { (*a).used[j / WORD_BITS].fetch_and(!(1 << (j % WORD_BITS)), Ordering::AcqRel); } - return false; + return None; } - set_bits(&(*a).committed, start, start + n); + set_bits( + &(*a).committed, + start, + (start + bytes / SEGMENT_SIZE).min(end), + ); } - true + Some(bytes) } static ARENAS: [AtomicPtr; MAX_ARENAS] = @@ -334,7 +390,7 @@ pub fn manage_os_memory_ex( let a = ARENAS[id as usize].load(Ordering::Acquire); // SAFETY: freshly registered arena descriptor. unsafe { - let chunks = (*a).chunks_live.load(Ordering::Acquire); + let chunks = (*a).live_chunks(); for w in 0..chunks.div_ceil(WORD_BITS) { let bits = if (w + 1) * WORD_BITS <= chunks { BitWord::MAX @@ -427,10 +483,17 @@ pub fn chunk_alloc(restrict_id: i32) -> Option<(*mut u8, bool)> { /// chunk-is-zero, chunk-is-committed-in-full); the caller commits whatever it /// touches unless the last is true. pub fn chunk_claim(restrict_id: i32) -> Option<(*mut u8, bool, bool)> { + chunk_alloc_ex(restrict_id, false).map(|(p, zero, got)| (p, zero, got == SEGMENT_SIZE)) +} + +/// [`chunk_claim`] returning how many bytes from the chunk's base are +/// committed: all of it, none, or the prefix its last tenant left +/// ([`chunk_release_part`]). The caller commits what it touches past that. +pub fn chunk_claim_part(restrict_id: i32) -> Option<(*mut u8, bool, usize)> { chunk_alloc_ex(restrict_id, false) } -fn chunk_alloc_ex(restrict_id: i32, commit: bool) -> Option<(*mut u8, bool, bool)> { +fn chunk_alloc_ex(restrict_id: i32, commit: bool) -> Option<(*mut u8, bool, usize)> { // No arenas on a one-region target: every segment comes straight from the // region. Folding this here is what removes the registry scan from the // segment-allocation path on a chip. @@ -463,7 +526,7 @@ struct CommitRefused; fn chunk_alloc_inner( restrict_id: i32, commit: bool, -) -> Result, CommitRefused> { +) -> Result, CommitRefused> { let n = ARENA_COUNT.load(Ordering::Acquire).min(MAX_ARENAS); for id in 0..n { if restrict_id >= 0 && id != restrict_id as usize { @@ -478,7 +541,7 @@ fn chunk_alloc_inner( if restrict_id < 0 && (*a).exclusive { continue; } - let chunks = (*a).chunks_live.load(Ordering::Acquire); + let chunks = (*a).live_chunks(); let words = chunks.div_ceil(WORD_BITS); for w in 0..words { loop { @@ -512,13 +575,17 @@ fn chunk_alloc_inner( let idx = w * WORD_BITS + bit; // Before the dirty bit: a refused commit leaves the chunk // untouched, and still zero. + // Bytes committed from the base: all, or the prefix the + // last tenant recorded (a full commit supersedes it). let committed = if commit { if !commit_claimed(a, idx, 1) { return Err(CommitRefused); } - true + SEGMENT_SIZE + } else if (*a).committed[w].load(Ordering::Acquire) & (1 << bit) != 0 { + SEGMENT_SIZE } else { - (*a).committed[w].load(Ordering::Acquire) & (1 << bit) != 0 + (*a).part[idx].load(Ordering::Relaxed) as usize * 4096 }; let was_dirty = (*a).dirty[w].fetch_or(1 << bit, Ordering::AcqRel) & (1 << bit) != 0; @@ -537,6 +604,18 @@ static MULTI_LOCK: core::sync::atomic::AtomicBool = core::sync::atomic::AtomicBo /// multi-bit search; the single-chunk path stays lock-free. #[allow(clippy::needless_range_loop)] // indexed scan over a fixed atomic table pub fn chunk_alloc_n(restrict_id: i32, n: usize) -> Option<(*mut u8, bool)> { + chunk_alloc_n_part(restrict_id, n, n.saturating_mul(SEGMENT_SIZE)).map(|(p, zero, _)| (p, zero)) +} + +/// [`chunk_alloc_n`] for a tenant that will use only the first `bytes` bytes +/// of the run: a run that is not committed already has only that much +/// committed. The third value is how many bytes from the start are sure to +/// be committed (all of the run when it already was). +pub fn chunk_alloc_n_part( + restrict_id: i32, + n: usize, + bytes: usize, +) -> Option<(*mut u8, bool, usize)> { if crate::FIXED_REGION { return None; } @@ -546,12 +625,12 @@ pub fn chunk_alloc_n(restrict_id: i32, n: usize) -> Option<(*mut u8, bool)> { return None; } if n == 1 { - return chunk_alloc(restrict_id); + return chunk_alloc(restrict_id).map(|(p, zero)| (p, zero, SEGMENT_SIZE)); } if restrict_id < 0 && crate::options::is_enabled(27) { return None; } - match chunk_alloc_n_inner(restrict_id, n) { + match chunk_alloc_n_inner(restrict_id, n, bytes) { Ok(Some(r)) => return Some(r), Err(CommitRefused) => return None, // as in `chunk_alloc` Ok(None) => {} @@ -559,14 +638,15 @@ pub fn chunk_alloc_n(restrict_id: i32, n: usize) -> Option<(*mut u8, bool)> { if restrict_id >= 0 || !reserve_default_arena_on_miss() { return None; } - chunk_alloc_n_inner(restrict_id, n).ok().flatten() + chunk_alloc_n_inner(restrict_id, n, bytes).ok().flatten() } #[allow(clippy::needless_range_loop)] // indexed scan over a fixed atomic table fn chunk_alloc_n_inner( restrict_id: i32, n: usize, -) -> Result, CommitRefused> { + bytes: usize, +) -> Result, CommitRefused> { while MULTI_LOCK .compare_exchange_weak(false, true, Ordering::Acquire, Ordering::Relaxed) .is_err() @@ -588,7 +668,7 @@ fn chunk_alloc_n_inner( if restrict_id < 0 && (*a).exclusive { continue; } - let chunks = (*a).chunks_live.load(Ordering::Acquire); + let chunks = (*a).live_chunks(); if n > chunks { continue; } @@ -639,12 +719,12 @@ fn chunk_alloc_n_inner( cur_w = usize::MAX; // reload the live word continue; } - if !commit_claimed(a, start, n) { + let Some(got) = commit_claimed_part(a, start, n, bytes) else { return Err(CommitRefused); - } + }; let dirty_prev = (*a).dirty[w].fetch_or(mask, Ordering::AcqRel); let p = (*a).base.add(start * SEGMENT_SIZE); - return Ok(Some((p, dirty_prev & mask == 0))); + return Ok(Some((p, dirty_prev & mask == 0, got))); } // CLAIM-AND-VERIFY. MULTI_LOCK excludes other // multi-chunk claims but NOT the lock-free @@ -673,9 +753,9 @@ fn chunk_alloc_n_inner( cur_w = usize::MAX; // reload the live word continue; } - if !commit_claimed(a, start, n) { + let Some(got) = commit_claimed_part(a, start, n, bytes) else { return Err(CommitRefused); - } + }; let mut any_dirty = false; for j in start..=idx { any_dirty |= (*a).dirty[j / WORD_BITS] @@ -684,7 +764,7 @@ fn chunk_alloc_n_inner( != 0; } let p = (*a).base.add(start * SEGMENT_SIZE); - return Ok(Some((p, !any_dirty))); + return Ok(Some((p, !any_dirty, got))); } idx += 1; } @@ -712,7 +792,7 @@ fn find_arena(addr: usize) -> Option<(*mut Arena, usize, usize)> { } // SAFETY: live descriptor; only its base and live-chunk count are read. unsafe { - let chunks = (*a).chunks_live.load(Ordering::Acquire); + let chunks = (*a).live_chunks(); let Some(span) = chunks.checked_mul(SEGMENT_SIZE) else { continue; }; @@ -739,6 +819,25 @@ pub fn chunk_free_n(p: *mut u8, n: usize) -> bool { /// of the caller purging them now. True when the address belonged to an /// arena. pub fn chunk_release(p: *mut u8, n: usize, committed: Option, pending: bool) -> bool { + chunk_release_ex(p, n, committed, pending, 0) +} + +/// Return one chunk whose first `bytes` bytes are committed and whose rest is +/// not (`bytes` below the chunk, a multiple of 4 KiB). `pending` as in +/// [`chunk_release`]. True when the address was an arena's. +pub fn chunk_release_part(p: *mut u8, bytes: usize, pending: bool) -> bool { + chunk_release_ex(p, 1, Some(false), pending, (bytes / 4096) as u32) +} + +/// [`chunk_release`], recording `part_pages` as the first chunk's committed +/// prefix and clearing every other chunk's. +fn chunk_release_ex( + p: *mut u8, + n: usize, + committed: Option, + pending: bool, + part_pages: u32, +) -> bool { // Zero / overflowing `n` is false, not `start..start+n` OOB on the bitmap // (OH-rusty_alloc-25). if n == 0 { @@ -774,6 +873,11 @@ pub fn chunk_release(p: *mut u8, n: usize, committed: Option, pending: boo } } } + // The committed prefix, for the next tenant. Written before the + // `used` release below publishes the chunk. + for j in start..end { + (*a).part[j].store(if j == start { part_pages } else { 0 }, Ordering::Relaxed); + } if crate::OS_PAGES && pending { let now = now_ms(); for j in start..end { @@ -836,7 +940,7 @@ pub fn purge_due(force: bool) -> usize { } let delay = delay_ms(); let decommits = crate::options::is_enabled(5); // purge_decommits - let chunks = (*a).chunks_live.load(Ordering::Acquire); + let chunks = (*a).live_chunks(); let mut next: Option = None; for w in 0..chunks.div_ceil(WORD_BITS) { let mut pend = (*a).purge_pending[w].load(Ordering::Acquire); @@ -866,6 +970,7 @@ pub fn purge_due(force: bool) -> usize { if os::purge(p, SEGMENT_SIZE, decommits).is_ok() { if decommits { (*a).committed[w].fetch_and(!m, Ordering::AcqRel); + (*a).part[j].store(0, Ordering::Relaxed); } purged += 1; } @@ -969,7 +1074,7 @@ pub(crate) fn adopt_os_block(ptr: *mut u8, size: usize) -> Option { if (*a).exclusive || !(*a).owned { continue; } - let chunks = (*a).chunks_live.load(Ordering::Acquire); + let chunks = (*a).live_chunks(); if (*a).base.addr() + chunks * SEGMENT_SIZE != addr || chunks + n > MAX_CHUNKS { continue; } @@ -1020,7 +1125,7 @@ pub fn arena_area(id: i32) -> (*mut u8, usize) { } // SAFETY: live descriptor. unsafe { - let chunks = (*a).chunks_live.load(Ordering::Acquire); + let chunks = (*a).live_chunks(); ((*a).base, chunks.checked_mul(SEGMENT_SIZE).unwrap_or(0)) } } @@ -1045,7 +1150,7 @@ pub fn arenas_print(out: &mut dyn FnMut(&str)) { } // SAFETY: live descriptor. unsafe { - let chunks = (*a).chunks_live.load(Ordering::Acquire); + let chunks = (*a).live_chunks(); let mut used = 0usize; for w in 0..chunks.div_ceil(WORD_BITS) { used += (*a).used[w].load(Ordering::Relaxed).count_ones() as usize; diff --git a/crates/rusty_alloc/src/bins.rs b/crates/rusty_alloc/src/bins.rs index 04ca400..b918d79 100644 --- a/crates/rusty_alloc/src/bins.rs +++ b/crates/rusty_alloc/src/bins.rs @@ -15,6 +15,15 @@ pub const BIN_COUNT: usize = BIN_FULL + 1; /// Direct-table entries: one per small wsize 0..=128 (`MI_PAGES_DIRECT`). pub const PAGES_DIRECT: usize = crate::types::SMALL_WSIZE_MAX + 1; +/// A mask every medium bin index passes unchanged: see [`bin`]. +const MEDIUM_BIN_MASK: usize = 63; +// Every bin a size up to the medium maximum maps to passes the mask: bins +// grow with size, so the largest is the bound. +const _: () = assert!( + bin(MEDIUM_OBJ_SIZE_MAX) <= MEDIUM_BIN_MASK && MEDIUM_BIN_MASK < BIN_HUGE, + "a medium bin no longer fits the mask that bounds it" +); + /// Map a size to its bin index (`mi_bin`). Sizes above [`MEDIUM_OBJ_SIZE_MAX`] /// map to [`BIN_HUGE`], the dedicated-segment path. #[inline] @@ -42,7 +51,15 @@ pub const fn bin(size: usize) -> usize { // count and the bin index are both derived from it. Opscan `big` // +1.00, `aligned` +0.69, `mixed` +0.72. Leave it as written. let b = (usize::BITS - 1 - w.leading_zeros()) as usize; - ((b << 2) + ((w >> (b - 2)) & 0x03)) - 3 + // `& MEDIUM_BIN_MASK`: an identity here (the largest medium bin is + // below it, `const` asserted under this function), and the bound LLVM + // needs to prove the result below `BIN_COUNT`, which it cannot see + // through `leading_zeros` and the `- 3`. Without it every index of + // `Heap::pages` by this bin carried a compare and a branch to + // `panic_bounds_check`: one of the panic sites an `Allocator` method + // can reach, on every medium generic trip (`docs/opps.md`, the + // `Allocator` route). + (((b << 2) + ((w >> (b - 2)) & 0x03)) - 3) & MEDIUM_BIN_MASK } } @@ -73,7 +90,10 @@ static SMALL_BIN: [u8; crate::types::SMALL_WSIZE_MAX + 1] = { pub fn bin_by_wsize(size: usize, w: usize) -> usize { debug_assert_eq!(w, wsize_from_size(size)); if w <= crate::types::SMALL_WSIZE_MAX { - SMALL_BIN[w] as usize + // Masked for the same reason as `bin`'s medium arm: a `u8` from a + // table could be anything to LLVM, and the two arms meet at one + // index of `Heap::pages`, so either arm unbounded kept the check. + SMALL_BIN[w] as usize & MEDIUM_BIN_MASK } else { bin(size) } diff --git a/crates/rusty_alloc/src/heap.rs b/crates/rusty_alloc/src/heap.rs index c30c785..f0d7335 100644 --- a/crates/rusty_alloc/src/heap.rs +++ b/crates/rusty_alloc/src/heap.rs @@ -31,6 +31,34 @@ use crate::types::{ /// Largest bin index actually reachable from a size (rest are M3 large pages). pub const MAX_NORMAL_BIN: usize = bins_max(); +/// Groups of eight in [`Heap::queues_live`]: one byte per page queue, read +/// back eight at a time as a `u64`. Sixteen groups, so a mark indexes with +/// `bin & 127` and carries no bounds check; the sweep reads only the groups +/// that hold normal bins. +const LIVE_WORDS: usize = 16; +const _: () = assert!(BIN_COUNT <= 8 * LIVE_WORDS); +const SWEEP_WORDS: usize = MAX_NORMAL_BIN / 8 + 1; + +/// Group `w` of [`Heap::queues_live`] as one `u64`, byte `k` = bin `8w + k`. +#[inline(always)] +fn live_group(live: &[u8; 8 * LIVE_WORDS], w: usize) -> u64 { + let mut g = [0u8; 8]; + g.copy_from_slice(&live[w * 8..w * 8 + 8]); + u64::from_le_bytes(g) +} + +/// The bytes of [`Heap::queues_live`] that a collect sweeps, as `u64` masks: +/// bins `1..=MAX_NORMAL_BIN`, exactly the range the sweep walked one by one. +const NORMAL_BIN_BYTES: [u64; LIVE_WORDS] = { + let mut m = [0u64; LIVE_WORDS]; + let mut b = 1; + while b <= MAX_NORMAL_BIN { + m[b / 8] |= 0xFFu64 << ((b % 8) * 8); + b += 1; + } + m +}; + /// Largest bin whose block size still fits the `direct[]` fast-path table. /// /// `update_direct` returns immediately for anything above this, so the @@ -251,6 +279,35 @@ pub struct Heap { /// /// Last, so no other field moves. pub no_reclaim: bool, + /// When [`Heap::purge_tick`] next has something to do, as a + /// `prim::clock_now` time, or 0 for never: the earliest purge deadline + /// (`Segment::purge_expire`) [`Heap::retire_span`] has seen, or the end + /// of the current look's delay. + pub purge_next: u64, + /// When [`Heap::purge_tick`] last looked at this heap's free spans, in + /// milliseconds of `prim::clock_now`, wrapping. + pub purge_seen_ms: u32, + /// One bit per bin: this heap has carved a page for it + /// (`fresh_page`; maintained only under `PAGE_LAZY_COMMIT`). + pub bins_seen: u128, + /// One byte per page queue, non-zero when the queue MAY hold a page; zero + /// means the queue is empty. Set where a page enters an empty bin queue (a fresh + /// page, an adopted page, a full page returning), cleared only by the + /// collect sweep when it leaves a queue empty. The sweep visits the set + /// bits instead of all `MAX_NORMAL_BIN` queues: a thread that used three + /// size classes paid ~6.5 instructions for each of the other seventy at + /// exit (census 4, vein 10). Last in the struct so no hot field moves. + /// + /// Bytes, not bits: as a bitmap the mark was a word select, a shift, a + /// load, an OR and a store, ~6 instructions on every fresh page, and lua + /// (which never collects) paid +3,089 for it. A byte is one store. + /// + /// Flat, indexed by `bin & 127`: as `[[u8; 8]; 16]` indexed + /// `[bin >> 3 & 15][bin & 7]`, LLVM rebuilt the offset from two masks, + /// six instructions at every fresh page instead of two. + pub queues_live: [u8; 8 * LIVE_WORDS], + /// This heap's thread is ending (`collect_for_thread_exit`). + pub exiting: bool, } /// The page-queue table every heap starts from, with each bin's block size @@ -324,6 +381,11 @@ impl Heap { guarded_max: usize::MAX, stats: Stats::new(), no_reclaim: false, + purge_next: 0, + purge_seen_ms: 0, + bins_seen: 0, + queues_live: [0; 8 * LIVE_WORDS], + exiting: false, } } @@ -429,6 +491,10 @@ impl Heap { // the queue front's `free` list is always dry and the peek can never // hit. It pays only where a populated free list is actually left // behind, which is why it lives here and not there. + // `queue_at`'s check, then a plain index the check proves in range. + if bin > BIN_FULL { + crate::abort(); + } let p = self.pages[bin].first; if !p.is_null() { // SAFETY: queue members are live pages of this heap and we hold @@ -489,7 +555,7 @@ impl Heap { /// hit rate 94 %). Out here the fast path is a leaf. #[cold] #[inline(never)] - fn zalloc_generic(&mut self, size: usize) -> *mut u8 { + pub(crate) fn zalloc_generic(&mut self, size: usize) -> *mut u8 { // Slow/large path: rare, and the generic allocator has resolved the // page anyway. Recover the usable size the general way. let (b, is_zero) = self.malloc_generic(size); @@ -1036,6 +1102,11 @@ impl Heap { /// Carve a fresh page for `bin` from the segment list (new segment if all /// are exhausted) and push it to the queue front. fn fresh_page(&mut self, bin: usize, bsize: usize) -> *mut Page { + // Marked HERE, while `bin` is in its argument register, not beside + // the push: there it kept `bin` live across the carve and cost + // `malloc_generic_walk` ~9 instructions per fresh page (lua +5,446). + // A mark left by a failed carve only makes the sweep look once. + self.mark_queue_live(bin); let slices = if bsize <= SMALL_OBJ_SIZE_MAX { 1 } else { @@ -1043,7 +1114,22 @@ impl Heap { }; // SAFETY: heap lock held; segments list is owned by this heap. unsafe { - let Some((p, fresh)) = self.span_from_segments(slices) else { + // A medium page commits as it fills (`PAGE_LAZY_COMMIT`), and so + // does the FIRST small page this heap carves for a size class. + // That page is the one that may hold three blocks for the life + // of the thread; by its second page the class is in use, and a + // page that fills pays two more commit calls for nothing. + // Measured on fast-decomp, small pages held 2.1 MiB (one thread) + // and 7.2 MiB (six) committed and never touched. + let lazy = segment::PAGE_LAZY_COMMIT + && (slices > 1 || { + let bit = 1u128 << bin; + let first = self.bins_seen & bit == 0; + self.bins_seen |= bit; + first + }); + let first = if lazy { segment::lazy_first(slices) } else { 0 }; + let Some((p, fresh)) = self.span_from_segments(slices, first) else { return ptr::null_mut(); }; (*p).block_size = bsize; @@ -1098,22 +1184,102 @@ impl Heap { } } + /// Give back the free spans this heap has now seen free for a whole + /// `purge_delay`, in every segment it owns. + /// + /// A scheduled purge used to run only when the SAME segment freed another + /// candidate, or on the periodic collect (every 10,000 generic trips). A + /// heap that freed its large spans and went on to other work kept them + /// resident for as long as that took: on fast-decomp's Godot run that was + /// about 120 MiB of the peak (issue 63). Carving a span is where a heap + /// takes memory, so it is where it looks at what it is holding. + /// + /// It looks at most once a delay, and purges a span only if the span was + /// already free at the LAST look: free then, free now, a delay or more + /// apart. Purging everything due at the first carve after a pause is what + /// a first cut did, and it purged exactly the memory about to be reused: + /// a loop that frees 50 MiB, sleeps 25 ms and allocates it again ran its + /// allocations 2.2 times slower, every page refaulted. Under this rule + /// that loop purges nothing, and a span nobody takes goes back at the + /// second look. The clock is read only while a deadline is running. + /// + /// # Safety + /// Heap lock held. + #[cold] + #[inline(never)] + unsafe fn purge_tick(&mut self) { + if !(crate::OS_PAGES && crate::options::get(15) > 0) { + self.purge_next = 0; + return; + } + let now = crate::prim::clock_now(); + if now < self.purge_next { + return; + } + let delay = segment::delay_ms(); + let now_ms = (now / 1_000_000) as u32; + let since = now_ms.wrapping_sub(self.purge_seen_ms); + if since < delay { + // A deadline fell due inside the current look's delay. + self.purge_next = now.saturating_add(u64::from(delay - since) * 1_000_000); + return; + } + // SAFETY: heap lock held; the segment list is this heap's. + unsafe { + let mut left = false; + let mut s = self.segments; + while !s.is_null() { + if (*s).purge_expire != 0 { + self.stats.purges += segment::purge_aged(s, now, since) as u64; + left |= (*s).purge_expire != 0; + } + s = (*s).next; + } + self.purge_seen_ms = now_ms; + self.purge_next = if left { + now.saturating_add(u64::from(delay) * 1_000_000).max(1) + } else { + 0 + }; + } + } + /// First-fit a span across owned segments, allocating a new segment when /// all are exhausted. Returns (span start, span-is-fresh-zero). /// /// # Safety /// Heap lock held. - unsafe fn span_from_segments(&mut self, slices: usize) -> Option<(*mut Page, bool)> { + unsafe fn span_from_segments( + &mut self, + slices: usize, + lazy: usize, + ) -> Option<(*mut Page, bool)> { + /// `span_alloc`, or its lazily committing form for a caller that + /// asks: `lazy` is `segment::span_alloc_first`'s `first`, or 0. + #[inline(always)] + unsafe fn carve(seg: *mut Segment, slices: usize, lazy: usize) -> (*mut Page, bool) { + // SAFETY: forwarded contract. + unsafe { + if segment::PAGE_LAZY_COMMIT && lazy != 0 { + segment::span_alloc_first(seg, slices, lazy) + } else { + span_alloc(seg, slices) + } + } + } /// Stall guard, NOT a reclaim budget: a huge orphan backlog must not /// let a single allocation walk the whole abandoned list. const MAX_ADOPT: usize = 32; // SAFETY: heap lock held; segments list is owned by this heap. unsafe { + if self.purge_next != 0 { + self.purge_tick(); + } let mut seg = self.segments; while !seg.is_null() { let was_empty = (*seg).used_pages == 0; - let (p, fresh) = span_alloc(seg, slices); + let (p, fresh) = carve(seg, slices, lazy); if !p.is_null() { if was_empty { self.empty_segments -= 1; @@ -1151,7 +1317,7 @@ impl Heap { continue; } let was_empty = (*aseg).used_pages == 0; - let (p, fresh) = span_alloc(aseg, slices); + let (p, fresh) = carve(aseg, slices, lazy); if !p.is_null() { if was_empty && self.empty_segments > 0 { self.empty_segments -= 1; @@ -1161,10 +1327,16 @@ impl Heap { } // A first segment commits what the span needs; a later one a // whole step (see `later_segment_first`). - let first = if self.segments.is_null() { + // (A lazily committed page asks for its first slice only.) + let want = if segment::PAGE_LAZY_COMMIT && lazy != 0 { + 1 + } else { slices + }; + let first = if self.segments.is_null() { + want } else { - segment::later_segment_first(slices) + segment::later_segment_first(want) }; let seg = segment::segment_alloc_for(self.arena_id, first).ok()?; #[cfg(ra_shared_light_heap)] @@ -1172,7 +1344,7 @@ impl Heap { self.stats.segments += 1; (*seg).next = self.segments; self.segments = seg; - let (p, fresh) = span_alloc(seg, slices); + let (p, fresh) = carve(seg, slices, lazy); debug_assert!(!p.is_null()); Some((p, fresh)) } @@ -1190,7 +1362,11 @@ impl Heap { // the liveness and the contents' zero-ness change. self.large_freed = false; let c = self.large_cache; - if !c.is_null() && (*c).slice_count as usize == slices { + // (A cached span may be short: see `block_size` below.) + if !c.is_null() + && (*c).slice_count as usize == slices + && (!segment::PAGE_LAZY_COMMIT || (*c).block_size >= size) + { self.large_cache = ptr::null_mut(); (*c).used = 1; (*c).free_is_zero = false; @@ -1205,10 +1381,26 @@ impl Heap { // `free_large_span` did), and the extra call, inlined into // `malloc_generic_once`, cost every generic allocation +3 Ir (big // 92 -> 95, mixed +2.2) though none of them is large. - let Some((p, fresh)) = self.span_from_segments(slices) else { + // A span is whole slices and the block rarely is: commit the + // block's OS pages and leave the rest of its last slice reserved + // (`PAGE_LAZY_COMMIT`). On fast-decomp's OpenTTD run that tail + // was 32 KiB a block over 510 large blocks. The block's size is + // then what was committed, so nothing can be asked to use the + // tail: `usable_size`, and with it every in-place `realloc`, + // reads `block_size`. + let bytes = if segment::PAGE_LAZY_COMMIT { + crate::os::page_align_up(size) + } else { + 0 + }; + let Some((p, fresh)) = self.span_from_segments(slices, bytes) else { return (ptr::null_mut(), false); }; - (*p).block_size = slices * SEGMENT_SLICE_SIZE; + (*p).block_size = if segment::PAGE_LAZY_COMMIT && (*p).lazy_end != 0 { + bytes + } else { + slices * SEGMENT_SLICE_SIZE + }; (*p).reserved = 1; (*p).capacity = 1; (*p).used = 1; @@ -1660,6 +1852,43 @@ impl Heap { unsafe { self.collect_inner(true, false) } } + /// [`collect_for_teardown`](Self::collect_for_teardown) for a heap whose + /// THREAD is ending: every segment it keeps is next freed whole or + /// abandoned, so its freed spans are not scheduled for a delayed purge + /// (`segment::span_free_unscheduled`). + /// + /// # Safety + /// As [`collect`](Self::collect). + pub unsafe fn collect_for_thread_exit(&mut self) { + self.exiting = true; + // SAFETY: forwarded contract. + unsafe { self.collect_inner(true, false) }; + self.exiting = false; + } + + /// The queue of `bin`, a page's own bin, which is never past `BIN_FULL`. + /// + /// Checked into an abort, not a bounds-check panic: an `Allocator` method + /// must not unwind (`tools/no-unwind-scan.sh`), and a bin out of range is + /// a corrupted page, which the allocator aborts on everywhere else. It is + /// the bounds check's own compare and branch, so it costs nothing over + /// `self.pages[bin]`. REFUTED first: `bin.min(BIN_FULL)` is a `cmov`, which + /// takes no immediate, so a `mov` more: `aligned` +0.07 Ir/op, + /// `aligned_alloc` +0.06, exactly one per `malloc_aligned_at_slow`. + #[inline(always)] + fn queue_at(&mut self, bin: usize) -> *mut PageQueue { + if bin > BIN_FULL { + crate::abort(); + } + &raw mut self.pages[bin] + } + + /// Record that bin queue `bin` may now hold a page (see `queues_live`). + #[inline(always)] + fn mark_queue_live(&mut self, bin: usize) { + self.queues_live[bin & (8 * LIVE_WORDS - 1)] = 1; + } + /// # Safety /// Owner thread; `reclaim` only when this heap will REMAIN live. unsafe fn collect_inner(&mut self, force: bool, reclaim: bool) { @@ -1710,7 +1939,6 @@ impl Heap { } } self.process_delayed(); - let mut bin = 1; // Running queue pointer: `self.pages[bin]` re-indexed the array // (and re-borrowed `self`) on every one of the MAX_NORMAL_BIN // steps, on every collect. @@ -1733,54 +1961,72 @@ impl Heap { usize::MAX }; let mut slot_now: Option> = None; + // Only the queues `queues_live` marks, in ascending bin order as + // before; every other queue is empty by that field's invariant. + #[cfg(debug_assertions)] + for b in 1..=MAX_NORMAL_BIN { + debug_assert!( + self.queues_live[b] != 0 || self.pages[b].first.is_null(), + "bin {b} holds a page but is not marked live" + ); + } let qbase: *mut PageQueue = (&raw mut self.pages).cast::(); - let mut q: *mut PageQueue = qbase.add(1); - while bin <= MAX_NORMAL_BIN { - let mut p = (*q).first; - while !p.is_null() { - let next = (*p).next; - if page_collect(p) { - self.saw_remote_free = true; + let mut w = 0; + while w < SWEEP_WORDS { + let mut live = live_group(&self.queues_live, w) & NORMAL_BIN_BYTES[w]; + while live != 0 { + let k = (live.trailing_zeros() / 8) as usize; + live &= !(0xFFu64 << (k * 8)); + let bin = w * 8 + k; + let q: *mut PageQueue = qbase.add(bin); + let mut p = (*q).first; + while !p.is_null() { + let next = (*p).next; + if page_collect(p) { + self.saw_remote_free = true; + } + // An all-free page is freed HERE regardless of whether it + // is its bin's only one. That is upstream: + // `mi_heap_page_collect` calls `_mi_page_free` whenever + // `mi_page_all_free(page)`, at every collect level, with the + // comment "this will free retired pages as well". The + // keep-one-page-per-bin reuse cache is `mi_page_retire`'s + // policy, on the FREE path — not collect's. + // + // Ours borrowed that exemption into collect, so no collect + // at any level could return a size class's slice to a + // different class. Invisible at the shipped 32 MiB geometry + // (512 slices per segment absorb a cached page per class); + // fatal at the small profile's 16, where P4d watched 512 B + // capacity decay 168 -> 8 blocks and 22,533 of 50,000 churn + // allocations return null with 61,440 bytes of the region + // still free. docs/plans/small-metal.md §2.14. + if page_all_free(p) { + queue_remove(q, p); + self.update_direct(bin); + let seg = segment_of(p.cast::()); + // `seg` is not touched again; `next` is a QUEUED page, + // and a released segment has no queued pages (release + // requires used_pages == 0). + let _ = self.retire_span(seg, p); // nosemgrep: discarded-lifecycle-result -- terminal, see comment above + } else if purge_on && (*p).block_size >= slot_min { + let now = *slot_now.get_or_insert_with(|| { + (!force).then(|| (crate::prim::clock_now() / 1_000_000) as u32) + }); + self.stats.purges += crate::page::page_purge_free_slots( + p, + now, + crate::options::get(15).clamp(0, i64::from(u32::MAX / 2)) as u32, + crate::options::is_enabled(5), + ) as u64; + } + p = next; } - // An all-free page is freed HERE regardless of whether it - // is its bin's only one. That is upstream: - // `mi_heap_page_collect` calls `_mi_page_free` whenever - // `mi_page_all_free(page)`, at every collect level, with the - // comment "this will free retired pages as well". The - // keep-one-page-per-bin reuse cache is `mi_page_retire`'s - // policy, on the FREE path — not collect's. - // - // Ours borrowed that exemption into collect, so no collect - // at any level could return a size class's slice to a - // different class. Invisible at the shipped 32 MiB geometry - // (512 slices per segment absorb a cached page per class); - // fatal at the small profile's 16, where P4d watched 512 B - // capacity decay 168 -> 8 blocks and 22,533 of 50,000 churn - // allocations return null with 61,440 bytes of the region - // still free. docs/plans/small-metal.md §2.14. - if page_all_free(p) { - queue_remove(q, p); - self.update_direct(bin); - let seg = segment_of(p.cast::()); - // `seg` is not touched again; `next` is a QUEUED page, - // and a released segment has no queued pages (release - // requires used_pages == 0). - let _ = self.retire_span(seg, p); // nosemgrep: discarded-lifecycle-result -- terminal, see comment above - } else if purge_on && (*p).block_size >= slot_min { - let now = *slot_now.get_or_insert_with(|| { - (!force).then(|| (crate::prim::clock_now() / 1_000_000) as u32) - }); - self.stats.purges += crate::page::page_purge_free_slots( - p, - now, - crate::options::get(15).clamp(0, i64::from(u32::MAX / 2)) as u32, - crate::options::is_enabled(5), - ) as u64; + if (*q).first.is_null() { + self.queues_live[bin] = 0; } - p = next; } - bin += 1; - q = q.wrapping_add(1); + w += 1; } // Scheduled purges (positive `purge_delay`): those past their // deadline, or all of them on a forced collect, which is what @@ -1903,6 +2149,7 @@ impl Heap { // by the M8 parallel gate). Empty pages are queued // like any other and retired by the next collect. queue_push_front(&raw mut self.pages[bin], slot); + self.mark_queue_live(bin); } else { // Large single-block span: stays unqueued; a dead one // is retired by a later collect, same rule as above. @@ -1948,7 +2195,9 @@ impl Heap { let mut idx = segment::HEADER_SLICES; let mut retired_any = false; while saw_large_span && idx < (*seg).next_free_slice as usize { - let slot: *mut Page = &raw mut (*seg).pages[idx]; + // By pointer: `idx` is below `next_free_slice`, so in the + // table, and indexing kept a bounds check (a panic path). + let slot: *mut Page = (&raw mut (*seg).pages).cast::().add(idx); let len = ((*slot).slice_count as usize).max(1); if (*slot).block_size > 0 && segment::slice_owner(seg, idx) == slot @@ -2067,7 +2316,7 @@ impl Heap { // SAFETY: forwarded contract. unsafe { let bin = (*pg).bin as usize; - let q: *mut PageQueue = &raw mut self.pages[bin]; + let q: *mut PageQueue = self.queue_at(bin); // NOTE (RSS investigation, 2026-08-06): deferring this retire — // keeping the emptied page queued so the next round reuses the SAME // memory instead of first-fitting a span elsewhere — was tried and @@ -2155,10 +2404,12 @@ impl Heap { // `update_direct` is needed ONLY when the queue was // empty, because that is the only way a push to the // BACK can move the head the table tracks. - let q: *mut PageQueue = &raw mut self.pages[bin]; + let q: *mut PageQueue = self.queue_at(bin); let was_empty = (*q).first.is_null(); queue_push_back(q, pg); if was_empty { + // A non-empty queue is already marked live. + self.mark_queue_live(bin); self.update_direct(bin); } } @@ -2170,7 +2421,7 @@ impl Heap { // that is already hot in L1 costs less than spilling. if page_all_free(pg) { let bin = (*pg).bin as usize; - let q: *mut PageQueue = &raw mut self.pages[bin]; + let q: *mut PageQueue = self.queue_at(bin); // `first == pg` is also exactly the condition under // which `queue_remove` moves the head. let was_first = (*q).first == pg; @@ -2254,8 +2505,17 @@ impl Heap { unsafe { // span_free coalesces, then purges the merged span (the RSS // lever) and reports whether it did. - self.stats.purges += span_free(seg, pg) as u64; + self.stats.purges += if self.exiting { + segment::span_free_unscheduled(seg, pg) + } else { + span_free(seg, pg) + } as u64; self.stats.pages_retired += 1; + // A purge candidate is waiting in `seg`: remember when it is due. + let due = (*seg).purge_expire; + if due != 0 && (self.purge_next == 0 || due < self.purge_next) { + self.purge_next = due; + } if (*seg).used_pages == 0 { if self.empty_segments == 0 { // Park one empty segment for reuse (stays in the list — @@ -2364,6 +2624,13 @@ impl Heap { // `bins::bin_size`'s shift-and-mask arithmetic on every call was work // the struct had already done — and the load is free, because the very // next line touches `self.pages[bin]` anyway. + // + // Checked like `queue_at`, into an abort: without it the index here + // keeps a bounds check (a panic path; `tools/no-unwind-scan.sh`) where + // the caller's own check does not reach. Where it does, this folds. + if bin > BIN_FULL { + crate::abort(); + } let bsize = self.pages[bin].block_size; if bsize > SMALL_SIZE_MAX { return; @@ -2454,7 +2721,12 @@ pub unsafe fn visit_segment_blocks( return true; } let bsize = (*pg).block_size; - let block = seg.cast::().add((*seg).total_size - bsize); + // The block starts at the page's area. (This was + // `seg + total_size - bsize`, right while `block_size` was the + // whole reservation past the block's start and wrong since it + // became the size asked for: a 33 MiB block in a 64 MiB chunk + // pair was reported 31 MiB above where it is.) + let block = (*pg).area; let area = AreaInfo { blocks: block, reserved: bsize, diff --git a/crates/rusty_alloc/src/init.rs b/crates/rusty_alloc/src/init.rs index 357a86b..e043e35 100644 --- a/crates/rusty_alloc/src/init.rs +++ b/crates/rusty_alloc/src/init.rs @@ -753,13 +753,13 @@ fn create_heap_uninstalled(tag: i32, allow_destroy: bool, arena_id: i32) -> *mut // threads). (*(*hb).heap.get()).generic_countdown = crate::options::get_clamp(crate::options::GENERIC_COLLECT, 1, 1_000_000) as usize; - // Per-heap CSPRNG stream (free-list keys, guarded sampling) -- seeded - // only where something draws from it. A build with neither `secure` - // nor guard pages has no consumer, and seeding still cost the ChaCha - // block function plus the splitmix fallback in flash. - if crate::RNG_USED { - (*(*hb).heap.get()).rng.reseed(); - } + // No per-heap CSPRNG seeding here: the stream (free-list keys under + // `secure`, guarded sampling) seeds itself at its first draw + // (`Random::refill`). A heap that never draws, which is every heap + // of a build without `secure` and with `guarded_max` unset, used to + // pay at creation for an `open`, a `read` and a `close` of + // `/dev/urandom` and the ChaCha key setup: three system calls and + // about 130 instructions at every thread's first allocation. // Guarded objects follow the option table (MI_GUARDED-equivalent) -- // where a guard page can exist at all. `GUARD_PAGES` first, so that on // a target without one the option reads fold away with the sampler @@ -943,8 +943,9 @@ unsafe fn thread_done_one(hb: *mut HeapBox) { let h = &mut *(*hb).heap.get(); // Retire everything that is already dead (also drains delayed once). // TEARDOWN variant: must NOT adopt orphans into a heap we are about to - // destroy — that was the 0.3.1 segfault. - h.collect_for_teardown(); + // destroy — that was the 0.3.1 segfault. And the THREAD-EXIT one: + // every segment below is freed or abandoned, so nothing is scheduled. + h.collect_for_thread_exit(); // Walk remaining segments: transition pages to NEVER, disown, publish. let mut seg = h.segments; h.segments = ptr::null_mut(); @@ -1272,7 +1273,16 @@ pub fn subproc_add_current_thread(id: usize) { } fn my_subproc() -> usize { - SUBPROC.with(|c| c.get()) + let sp = SUBPROC.with(|c| c.get()); + // Only a valid id is ever stored (`subproc_add_current_thread`), but the + // optimiser cannot see through the thread-local: without LTO every + // `ABANDONED_HEADS[sp]` kept a bounds check, a panic path on the allocator + // (`tools/no-unwind-scan.sh`, default profile). An abort instead, the + // allocator's answer to corrupted state; the same compare and branch. + if sp >= MAX_SUBPROCS { + crate::abort(); + } + sp } /// `mi_abandoned_visit_blocks`: visit live pages/blocks of a subprocess's @@ -1332,11 +1342,17 @@ fn abandoned_push(seg: *mut Segment, sp: usize) { // touched stays resident for an unbounded time and nothing can reuse it. // Done here, before publishing to the list, because this is the last // instant the caller still exclusively owns the segment. - if crate::options::is_enabled(30) { - // SAFETY: still owned by the dying thread; free spans hold no live - // blocks, and each purged span is marked so reuse re-commits it. - unsafe { crate::segment::purge_free_spans(seg) }; - } + // + // Unconditional, as `options` documents for `abandoned_page_purge`. From + // 0.3.0 until 2.6.1 this was gated on `options::is_enabled(30)`, which is + // `guarded_min` (0 unless guarded sampling is configured), not the purge + // option (12): the purge here never ran by default. A dying thread's + // spans were purged instead by the forced pass of its teardown collect, + // which is gone (`Heap::collect_for_thread_exit`); a segment abandoned + // some other way (`heap_delete` adopts instead) kept its pages. + // SAFETY: still owned by the dying thread; free spans hold no live + // blocks, and each purged span is marked so reuse re-commits it. + unsafe { crate::segment::purge_free_spans(seg) }; abandoned_lock(); // SAFETY: seg is disowned; its `next` is ours to use as the list link. unsafe { diff --git a/crates/rusty_alloc/src/lib.rs b/crates/rusty_alloc/src/lib.rs index cc6ac5e..07d5626 100644 --- a/crates/rusty_alloc/src/lib.rs +++ b/crates/rusty_alloc/src/lib.rs @@ -45,6 +45,56 @@ pub(crate) fn abort() -> ! { } } +/// Whether this build is the shape `tools/no-unwind-scan.sh` proves free of +/// panics on every path an `Allocator` method reaches: x86-64 Linux, no debug +/// assertions, `opt-level` 2 or 3 (`build.rs`), the default features and no +/// `ra_*` geometry. The scan counts the panic call sites in the machine code +/// under fat LTO and under Cargo's default release profile, and holds both to +/// zero in CI. At `opt-level` `s`, `z` and 1 a few table indexes keep their +/// bounds checks (2, 5 and 16 sites when this was written), so it is `false`. +/// +/// One shape it cannot tell apart: a release profile that turns +/// `overflow-checks` on. Neither `cfg` nor a build script can see that +/// setting. The debug test suite runs with overflow checks, so no tested path +/// overflows; one that did would be reading corrupted state. +/// +/// `rusty_alloc_api` reads it: where it is `true` its `Allocator` methods run +/// bare, and elsewhere under a guard that turns an unwind into an abort. A +/// downstream crate cannot see this crate's features through `cfg`, so the +/// answer has to come from here. Not a stable interface. +#[doc(hidden)] +pub const NO_UNWIND_PROVEN: bool = cfg!(all( + target_arch = "x86_64", + target_os = "linux", + target_env = "gnu", + not(debug_assertions), + ra_opt_scanned, + feature = "std", + not(any( + feature = "debug_checks", + feature = "profile", + feature = "linkcheck", + feature = "blockmap", + feature = "secure", + loom, + kani, + ra_small_profile, + ra_single_threaded, + ra_max_extents = "8", + ra_max_extents = "16", + ra_max_extents = "64", + ra_aligned_region, + ra_segment_size = "256k", + ra_generic_collect = "64", + ra_generic_collect = "4096", + ra_generic_collect = "65536", + ra_small_wsize = "256", + ra_small_wsize = "512", + ra_shared_light_heap, + ra_tls_local_exec, + )) +)); + /// A `thread_local!` that survives `no_std` — the single-heap profile. /// /// With `std` this expands to `std::thread_local!` unchanged, so the shipped @@ -151,10 +201,23 @@ impl SingleThreadCell { pub(crate) const fn new(v: T) -> Self { Self(v) } - /// Mirrors `LocalKey::with`, which is the only accessor the crate uses. + /// Mirrors `LocalKey::with`. pub(crate) fn with(&self, f: impl FnOnce(&T) -> R) -> R { f(&self.0) } + /// Mirrors `LocalKey::try_with`, which `options::out_fmt` uses so that a + /// hook called after the thread's locals are gone does not panic. A + /// `static` is never gone, so this always succeeds. + #[allow( + clippy::unnecessary_wraps, + reason = "the signature is `LocalKey::try_with`'s" + )] + pub(crate) fn try_with( + &self, + f: impl FnOnce(&T) -> R, + ) -> Result { + Ok(f(&self.0)) + } } /// `true` exactly when this build has ONE thread for the life of the program, @@ -228,10 +291,6 @@ pub(crate) const GUARD_PAGES: bool = cfg!(any(unix, windows, miri)); /// had added 2,768 bytes gzipped to a 20,873-byte module. pub(crate) const OS_PAGES: bool = cfg!(any(unix, windows, miri)); -/// Whether anything draws from a heap's CSPRNG: `secure` free-list keys, or -/// guarded sampling. A build with neither never seeds it. -pub(crate) const RNG_USED: bool = GUARD_PAGES || cfg!(feature = "secure"); - /// `true` where the prim is `prim::fixed`: one region, handed over once, with /// no OS behind it. The arena layer folds on this constant — there is nothing /// to reserve from, and a range managed from outside would carve its chunks diff --git a/crates/rusty_alloc/src/options.rs b/crates/rusty_alloc/src/options.rs index d93e694..8a2b60c 100644 --- a/crates/rusty_alloc/src/options.rs +++ b/crates/rusty_alloc/src/options.rs @@ -17,7 +17,7 @@ //! |---|---| //! | `show_errors` (0) | print error codes to stderr when no error hook is registered | //! | `purge_decommits` (5) | purge by decommit (on) or by reset (off) | -//! | `purge_delay` (15) | milliseconds a freed span of at least `MEDIUM_PAGE_SLICES` slices, or a chunk returned to an arena, stays resident before it is purged: `> 0` (default 10 on Windows and Unix, as upstream) purges once it has stayed free that long (checked on the segment's later span frees and on each collect; a forced collect purges at once), `0` purges at once, `< 0` never purges (the default where purging is a no-op). | +//! | `purge_delay` (15) | milliseconds a freed span of at least two slices (128 KiB), or a chunk returned to an arena, stays resident before it is purged: `> 0` (default 10 on Windows and Unix, as upstream) purges once it has stayed free that long (checked on the segment's later span frees and on each collect; a forced collect purges at once), `0` purges at once, `< 0` never purges (the default where purging is a no-op). | //! | `arena_reserve` (23) | size of the arena reservation (KiB) | //! | `disallow_arena_alloc` (27) | never place segments in the arena | //! | `guarded_min` / `guarded_max` (30, 31) | size bounds for guard-page sampling | @@ -425,6 +425,24 @@ const DEFAULTS: [i64; OPTION_COUNT] = [ static VALUES: [AtomicI64; OPTION_COUNT] = [const { AtomicI64::new(i64::MIN) }; OPTION_COUNT]; static ENV_PARSED: AtomicBool = AtomicBool::new(false); +/// Fill an option's `slot` with `v` during the start-up pass, unless it was +/// [`set`] meanwhile. Takes the slot, not an index, so it has no bounds check +/// of its own: callers index inside loops over the table's own length. +/// +/// The pass runs on whichever thread reads an option first, AFTER the +/// `ENV_PARSED` swap, so other threads already take the fast path and may +/// [`set`] an option while the pass is still writing the table. A plain store +/// here overwrote that `set`: a test that lowered `generic_collect` to 8 got +/// the default 10,000 back about one run in five on Windows +/// (`tests/heaps.rs`, `generic_collect_fires_on_its_own`), because a +/// neighbouring test's first option read was running the pass. Filling only +/// the `i64::MIN` sentinel keeps the pass's precedence (environment first, +/// then the defaults fill what is left) and lets an explicit `set` win +/// whenever it lands. Cold path only: `get` and `set` are unchanged. +fn fill(slot: &AtomicI64, v: i64) { + let _ = slot.compare_exchange(i64::MIN, v, Ordering::AcqRel, Ordering::Acquire); +} + /// Parse the environment once. The common case — every call after the first — /// is one plain load and a branch, inlined into the caller. /// @@ -452,9 +470,6 @@ fn ensure_init_slow() { // the no_std option story (P3 of `docs/plans/small-metal.md`, §2.5). This // is deletion, not a port: there is nothing to read, so the environment // pass does not exist rather than existing and returning nothing. - for i in 0..OPTION_COUNT { - VALUES[i].store(DEFAULTS[i], Ordering::Release); - } // ...and neither has `wasm32-unknown-unknown`. `std::env::var` there is a // stub that always fails, so the pass used to format 76 strings, allocate // 76 `String`s and read an environment that cannot exist — on every @@ -473,6 +488,11 @@ fn ensure_init_slow() { not(all(target_arch = "wasm32", target_os = "unknown")) ))] env::pass(); + // The defaults take every slot the environment left unset and no + // concurrent `set` has claimed (see `fill`). + for (slot, &d) in VALUES.iter().zip(DEFAULTS.iter()) { + fill(slot, d); + } } /// The environment pass, and why it owns no memory. @@ -496,8 +516,6 @@ fn ensure_init_slow() { not(all(target_arch = "wasm32", target_os = "unknown")) ))] mod env { - use core::sync::atomic::Ordering; - use super::{OPTION_COUNT, OPTION_NAMES, VALUES}; /// Longest option name: the key buffer is sized by the table, not by hand. @@ -568,8 +586,8 @@ mod env { // SAFETY: each non-null entry points at a NUL-terminated value. let got = unsafe { copy_value(rusty[i], &mut val).or_else(|| copy_value(mi[i], &mut val)) }; - if let Some(v) = got.and_then(|len| parse_value(&val[..len])) { - VALUES[i].store(v, Ordering::Release); + if let Some(v) = got.and_then(|len| parse_value(val.get(..len)?)) { + super::fill(&VALUES[i], v); } } } @@ -640,8 +658,8 @@ mod env { let n = build_key(&mut key, b"MIMALLOC_", name); lookup(&key[..n], &mut val) }); - if let Some(v) = got.and_then(|len| parse_value(&val[..len])) { - VALUES[i].store(v, Ordering::Release); + if let Some(v) = got.and_then(|len| parse_value(val.get(..len)?)) { + super::fill(&VALUES[i], v); } } } @@ -947,19 +965,19 @@ pub fn out_fmt(msg: &str) { // of wasm that this one interpolation of an ALREADY-`&str` argument // pulled into every build. Bytes to a writer need none of it. #[cfg(feature = "std")] - { - use std::io::Write; - let _ = std::io::stderr().write_all(msg.as_bytes()); - } + write_stderr(msg.as_bytes()); return; } // A hook that calls `out_fmt` again recurses until the stack dies // (OH-rusty_alloc-24). - if IN_OUTPUT.with(|c| c.get()) { + // `try_with`: `with` panics once the thread's locals are gone, and a hook + // may be called that late; there the call is dropped. + if IN_OUTPUT.try_with(|c| c.replace(true)).unwrap_or(true) { return; } - IN_OUTPUT.with(|c| c.set(true)); - let _clear = HookExit(|| IN_OUTPUT.with(|c| c.set(false))); + let _clear = HookExit(|| { + let _ = IN_OUTPUT.try_with(|c| c.set(false)); + }); // NUL-terminate on the stack for the C hook (bounded copy). let bytes = msg.as_bytes(); let mut buf = [0u8; 512]; @@ -973,6 +991,42 @@ pub fn out_fmt(msg: &str) { } } +/// `bytes` to standard error, best effort. +/// +/// On unix straight to fd 2, not through `std::io::stderr()`: its reentrant +/// lock and `write_all` carry panics (a lock-count `expect`, a `RefCell` +/// borrow, a reslice by the returned count) that an `Allocator` method may +/// not reach (`tools/no-unwind-scan.sh`). Stderr is unbuffered either way, so +/// the bytes are the same; only the lock is gone, and these are whole lines +/// written in one call. +#[cfg(all(unix, feature = "std"))] +fn write_stderr(bytes: &[u8]) { + use std::io::Write; + use std::os::fd::FromRawFd; + // SAFETY: fd 2 is the process's standard error; `ManuallyDrop` keeps the + // `File` from closing it. + let f = core::mem::ManuallyDrop::new(unsafe { std::fs::File::from_raw_fd(2) }); + let mut done = 0usize; + while let Some(rest) = bytes.get(done..) { + if rest.is_empty() { + return; + } + match (&*f).write(rest) { + Ok(0) => return, + Ok(n) => done = done.saturating_add(n), + Err(e) if e.kind() == std::io::ErrorKind::Interrupted => {} + Err(_) => return, + } + } +} + +/// `bytes` to standard error, best effort. +#[cfg(all(not(unix), feature = "std"))] +fn write_stderr(bytes: &[u8]) { + use std::io::Write; + let _ = std::io::stderr().write_all(bytes); +} + /// `"rusty_alloc: error \n"` into `buf`, without a formatter. /// /// Hand-rendered because `format!` on a single integer is what dragged diff --git a/crates/rusty_alloc/src/os.rs b/crates/rusty_alloc/src/os.rs index 07188b0..081c4a0 100644 --- a/crates/rusty_alloc/src/os.rs +++ b/crates/rusty_alloc/src/os.rs @@ -256,7 +256,12 @@ pub unsafe fn commit(ptr: *mut u8, size: usize) -> Result { return Err(test_hooks::INJECTED); } // SAFETY: forwarded contract. - unsafe { prim::commit(ptr, page_align_up(size)) } + let r = unsafe { prim::commit(ptr, page_align_up(size)) }; + #[cfg(all(test, feature = "std"))] + if r.is_ok() { + test_hooks::count_commit(page_align_up(size)); + } + r } /// Test-only fault injection: make this thread's next `n` commits fail, the @@ -271,9 +276,19 @@ pub(crate) mod test_hooks { std::thread_local! { static FAIL_COMMITS: Cell = const { Cell::new(0) }; + static COMMITTED: Cell = const { Cell::new(0) }; static FAIL_PURGES: Cell = const { Cell::new(0) }; } + /// Bytes this thread has committed through [`super::commit`], ever. + pub fn committed_bytes() -> usize { + COMMITTED.with(Cell::get) + } + + pub(super) fn count_commit(bytes: usize) { + COMMITTED.with(|c| c.set(c.get() + bytes)); + } + /// Fail this thread's next `n` purges. pub fn fail_next_purges(n: usize) { FAIL_PURGES.with(|c| c.set(n)); diff --git a/crates/rusty_alloc/src/page.rs b/crates/rusty_alloc/src/page.rs index 7d921bf..2850aef 100644 --- a/crates/rusty_alloc/src/page.rs +++ b/crates/rusty_alloc/src/page.rs @@ -453,13 +453,28 @@ pub struct Page { /// Written only by the owning thread; read by any thread, hence atomic. /// Measured: 6 -> 3 instructions on every local free (census 4, vein 1). pub owner_plain: OwnerWord, - /// The un-extended tail AND current free list are known zero. + /// The un-extended tail AND current free list are known zero. On a FREE + /// span's slot: the whole span reads as zero (it was decommitted whole + /// and nothing has written it since), so a block carved from it needs + /// no zeroing (`segment::span_alloc`). pub free_is_zero: bool, /// This span's memory was PURGED (decommitted/reset) while free. It must /// be re-committed before reuse — on Windows a decommitted range faults /// on touch (Linux MADV_DONTNEED does not, which is exactly why this was /// a Windows-only access violation until the recommit landed). pub purged: bool, + /// On a FREE span flagged [`Page::purged`]: some of it may still be + /// committed (a merge of purged and resident parts, or a page freed + /// before it was committed whole), so it is still a purge candidate. + /// Never set without `purged`; false on a live span. + pub partly: bool, + /// On a LIVE span carved under [`crate::segment::PAGE_LAZY_COMMIT`]: how + /// much of it is committed, counted from its start in + /// [`crate::segment::LAZY_UNIT`]s (16 KiB), when that is less than all of + /// it; 0 = the whole span is committed. Only a small or medium page is + /// ever carved short, and [`page_extend`] commits the rest as the page's + /// carved blocks reach it. + pub lazy_end: u8, /// Owning heap's tag (`mi_heap_new_ex`) — survives abandonment so /// `mi_abandoned_visit_blocks` can filter (upstream stores it on the page /// for the same reason). @@ -578,6 +593,8 @@ impl Page { owner_plain: OwnerWord::new(0), free_is_zero: false, purged: false, + partly: false, + lazy_end: 0, heap_tag: 0, #[cfg(feature = "secure")] keys: [0; 2], @@ -1568,6 +1585,48 @@ pub unsafe fn page_extend_inline(page: *mut Page, area: *mut u8) { // short thread carved twice what it used. let take = ((reserved >> span_shift).max(MIN_EXTEND).max(capacity)).min(reserved - capacity); + // A page committed as it fills (`segment::PAGE_LAZY_COMMIT`). + let take = if crate::segment::PAGE_LAZY_COMMIT && (*page).lazy_end != 0 { + // One slice of blocks a trip, and at least one block. The batch + // rule above links four blocks at least and doubles, which for a + // 40 KiB class is 160 KiB carved, and so committed, for the + // page's first block: on fast-decomp, medium pages held 6.3 MiB + // of carved blocks for 3.2 MiB requested (issue 63). A slice is + // `reserved / slice_count` blocks, and the span is a power of two + // of slices, so this is a shift. + // + // A small page (one slice) carves a unit of blocks a trip, a + // quarter of its `reserved`, for the same reason. + let small = (*page).slice_count == 1; + let chunk = if small { + reserved >> 2 + } else { + reserved >> (*page).slice_count.trailing_zeros() + }; + let take = take.min(chunk.max(1)); + // Back the blocks about to be linked. The first trip never needs + // to: a medium block is at most a slice (`MEDIUM_OBJ_SIZE_MAX`), + // a small one at most half a unit, and a lazily carved span has + // its first slice or unit. That is what lets `fresh_page`'s + // caller pop without looking. A refusal leaves the page as it + // was, with no free block, and the caller treats it as it treats + // a full page. + let end = (capacity + take) * bsize; + let first = if small { + crate::segment::LAZY_UNIT + } else { + crate::types::SEGMENT_SLICE_SIZE + }; + debug_assert!(capacity != 0 || end <= first); + if end > (*page).lazy_end as usize * crate::segment::LAZY_UNIT + && !crate::segment::page_commit_to(page, end) + { + return; + } + take + } else { + take + }; let start = area.add(capacity * bsize); // Link the fresh blocks in address order. // @@ -1656,7 +1715,7 @@ pub unsafe fn page_purge_free_slots( } }; if due { - let start = (addr + 3 * core::mem::size_of::()).next_multiple_of(ps); + let start = (addr + 3 * core::mem::size_of::() + ps - 1) & !(ps - 1); let end = (addr + bsize) & !(ps - 1); if end > start && crate::os::discard( diff --git a/crates/rusty_alloc/src/random.rs b/crates/rusty_alloc/src/random.rs index 3b26267..6d2ee05 100644 --- a/crates/rusty_alloc/src/random.rs +++ b/crates/rusty_alloc/src/random.rs @@ -28,7 +28,9 @@ fn qround(x: &mut [u32; 16], a: usize, b: usize, c: usize, d: usize) { } impl Random { - /// Empty (unseeded) stream — call [`reseed`](Self::reseed) before use. + /// Empty (unseeded) stream. It seeds itself from OS entropy at its first + /// draw; [`reseed`](Self::reseed) or [`seed_from`](Self::seed_from) seed + /// it sooner. pub const fn new() -> Random { Random { state: [0; 16], @@ -37,6 +39,13 @@ impl Random { } } + /// Whether this stream has been seeded ([`seed_from`](Self::seed_from) + /// writes the constant words; [`new`](Self::new) leaves them zero). + #[inline] + pub const fn is_seeded(&self) -> bool { + self.state[0] != 0 + } + /// Seed from `key` (32 bytes as 8 words) and a stream id. pub fn seed_from(&mut self, key: [u32; 8], stream: u64) { // "expand 32-byte k" @@ -83,6 +92,12 @@ impl Random { } fn refill(&mut self) { + // A stream is seeded at its first draw, not when it is made: most + // heaps never draw (see `init::create_heap_uninstalled`). One load + // and a branch per sixteen words. + if !self.is_seeded() { + self.reseed(); + } let mut x = self.state; for _ in 0..4 { // 8 rounds = 4 double-rounds @@ -110,12 +125,16 @@ impl Random { /// Next 32 random bits. #[inline] pub fn next_u32(&mut self) -> u32 { - if self.used >= 16 { + // The index is `used` or, after a refill, 0: the `else` arm is + // below 16, so the optimiser drops the bounds check and its panic. + let i = if self.used >= 16 { self.refill(); - } - let v = self.out[self.used]; - self.used += 1; - v + 0 + } else { + self.used + }; + self.used = i + 1; + self.out[i] } /// A full `usize` of random bits. @@ -201,7 +220,22 @@ fn os_entropy(key: &mut [u32; 8]) -> bool { // SAFETY: reinterpreting our own [u32; 8] as bytes for the read. let buf = unsafe { core::slice::from_raw_parts_mut(key.as_mut_ptr().cast::(), key.len() * 4) }; - f.read_exact(buf).is_ok() + // `read_exact` reslices by the count `read` returns, and a count past the + // end would be a panic (a bounds check std cannot drop). Here a bad count + // ends the loop through `get_mut`: no panic site on the allocator's paths. + let mut got = 0usize; + while let Some(rest) = buf.get_mut(got..) { + if rest.is_empty() { + return true; + } + match f.read(rest) { + Ok(0) => return false, + Ok(n) => got = got.saturating_add(n), + Err(e) if e.kind() == std::io::ErrorKind::Interrupted => {} + Err(_) => return false, + } + } + false } #[cfg(miri)] diff --git a/crates/rusty_alloc/src/segment.rs b/crates/rusty_alloc/src/segment.rs index 98b7a76..0687be2 100644 --- a/crates/rusty_alloc/src/segment.rs +++ b/crates/rusty_alloc/src/segment.rs @@ -48,12 +48,12 @@ pub struct Segment { pub total_size: usize, /// Bump cursor: slices at/after this index have never been carved. pub next_free_slice: u32, - /// Slices below this index are committed, apart from free spans flagged - /// `purged`; slices at/after it are reserved only. Always - /// `>= next_free_slice`, because only the bump cursor advances into new - /// slices ([`span_alloc`] commits ahead of it) and freed spans never - /// rejoin the frontier. `SLICES_PER_SEGMENT` for a segment committed when - /// it was reserved. + /// Slices at/after this index are reserved only. Slices below it are + /// committed, apart from free spans flagged `purged` and, under + /// [`PAGE_LAZY_COMMIT`], the tail of a live page past its + /// [`Page::lazy_end`] (which may also lie above this index: the cursor + /// steps over such a tail). `SLICES_PER_SEGMENT` for a segment committed + /// when it was reserved. pub commit_end: u32, /// Live pages carved from this segment. pub used_pages: u32, @@ -63,13 +63,22 @@ pub struct Segment { /// The mapping's never-carved region is known zero (fresh OS memory). /// False for recycled arena chunks — bump-fresh spans then are NOT zero. pub mem_is_zero: bool, - /// Any span of this segment was purged (decommitted) at some point. The + /// Any span of this segment was purged (decommitted) at some point, or a + /// page was carved without committing all of it. The /// segment must be RE-COMMITTED in full before it goes back to an arena: /// the next tenant bump-allocates from it and would otherwise touch /// decommitted pages (Windows access violation — the M8 defect). pub purged_any: bool, + /// A Huge segment whose tail past its block was given back when it was + /// carved ([`huge_alloc`]): how many bytes from the segment's base are + /// still committed. 0 = no such tail (and always 0 on a Normal segment). + /// `restore_for_reuse` commits exactly the tail back. Committing the + /// whole reservation instead is charged in full while the call runs, + /// committed pages included: a freed 61 MiB block took the process's + /// peak commit from 66 to 127 MiB. + pub huge_trim: usize, /// `prim::clock_now` deadline after which this segment's purge candidates - /// (free, unpurged spans of at least `MEDIUM_PAGE_SLICES` slices) are + /// (free, unpurged spans of at least [`PURGE_MIN_SLICES`] slices) are /// purged; 0 = none scheduled. Set by the first candidate freed under a /// positive `purge_delay`, cleared when the candidates are purged /// ([`purge_scheduled`]). @@ -219,11 +228,55 @@ const _: () = assert!( pub const LAZY_COMMIT: bool = cfg!(all(any(windows, unix), not(miri))) && !crate::FIXED_REGION && SEGMENT_SIZE >= 4 << 20; +/// The unit [`Page::lazy_end`] counts in, and the least a lazily committed +/// page commits: 16 KiB, a quarter of a slice. A medium page commits whole +/// slices; a small page, which is one slice, commits 16, 32 and then all 64. +pub const LAZY_UNIT: usize = SEGMENT_SLICE_SIZE / 4; + +/// What a lazily carved span of `slices` slices has committed at the least: +/// a slice of a medium page, a unit of a small one. +pub const fn lazy_first(slices: usize) -> usize { + if slices == 1 { + LAZY_UNIT + } else { + SEGMENT_SLICE_SIZE + } +} + +/// A medium page commits its slices as its blocks are carved, instead of +/// all 512 KiB when its span is carved. +/// +/// A page is carved for its first block and filled 4 KiB or four blocks at a +/// time, so most of a medium page's span is committed long before anything +/// is written to it, and for a size class that holds a handful of blocks it +/// never is. Measured on fast-decomp (issue 63, Windows, six threads): +/// committed and never touched inside medium pages was 23.2 MiB of the 84 +/// committed on ninja and 33.5 MiB on OpenTTD +/// (`docs/plans/windows-commit-footprint.md`). +/// +/// Windows only: it is where committed memory is charged whether or not it is +/// touched. Elsewhere a commit is an `mprotect` that changes no accounting +/// under the default overcommit, so the extra calls would buy nothing. Off +/// under `blockmap`, whose map lives at the END of the page's span. +pub const PAGE_LAZY_COMMIT: bool = cfg!(windows) + && LAZY_COMMIT + && !cfg!(feature = "blockmap") + && crate::types::MEDIUM_PAGE_SLICES > 1; + /// The most a frontier commit extends `commit_end` past what it must: commits -/// double from the header up to this step, so a full segment costs about a -/// dozen commit calls and the committed-but-uncarved tail stays under -/// max(the carved size, 4 MiB). -const COMMIT_STEP_MAX_SLICES: usize = (4 << 20) / SEGMENT_SLICE_SIZE; +/// double from the header up to this step, so the committed-but-uncarved tail +/// of a segment stays under the step. +/// +/// 4 MiB where commit is not charged until touched. 256 KiB on Windows, where +/// it is: every thread's segment carried up to 4 MiB of commit nothing had +/// asked for, which on fast-decomp was 3.75 MiB of 32 on one thread and +/// 14.3 MiB of 84 on six (issue 63). The smaller step removed exactly that, +/// and costs a commit call per 256 KiB carved instead of per 4 MiB. +const COMMIT_STEP_MAX_SLICES: usize = if cfg!(windows) { + (256 << 10) / SEGMENT_SLICE_SIZE +} else { + (4 << 20) / SEGMENT_SLICE_SIZE +}; /// How many slices to commit at the creation of a segment for a heap that /// already owns one, when it wants `slices` from it: a whole step. @@ -588,21 +641,34 @@ pub fn segment_alloc(arena_id: i32) -> Result<*mut Segment, PrimError> { pub fn segment_alloc_for(arena_id: i32, first: usize) -> Result<*mut Segment, PrimError> { let mut init = (HEADER_SLICES + first).min(SLICES_PER_SEGMENT); let claim = if LAZY_COMMIT { - crate::arena::chunk_claim(arena_id) + crate::arena::chunk_claim_part(arena_id) } else { - crate::arena::chunk_alloc(arena_id).map(|(p, zero)| (p, zero, true)) + crate::arena::chunk_alloc(arena_id).map(|(p, zero)| (p, zero, SEGMENT_SIZE)) }; - let (ptr_, size, mem_zero, committed) = match claim { - Some((p, zero, committed)) => (p, SEGMENT_SIZE, zero, committed), + // `had`: whole slices already committed from the base. A chunk that held + // a segment comes back with the prefix its tenant committed + // (`segment_free`), and a thread that takes it over commits none of that + // again: the short-lived-threads probe made three `mprotect` calls a + // thread to commit memory the previous thread had left committed. + let (ptr_, size, mem_zero, had) = match claim { + Some((p, zero, got)) => (p, SEGMENT_SIZE, zero, got / SEGMENT_SLICE_SIZE), None => { if arena_id >= 0 { return Err(0); // exclusive-arena heap and its arena is full } let (p, sz, zero) = reserve_backing(SEGMENT_SIZE, !LAZY_COMMIT)?; - (p, sz, zero, !LAZY_COMMIT) + ( + p, + sz, + zero, + if LAZY_COMMIT { 0 } else { SLICES_PER_SEGMENT }, + ) } }; - if !committed { + let committed = had == SLICES_PER_SEGMENT; + if had >= init { + init = had; + } else { // The header is written next, so it is committed first. On refusal // the memory goes back untouched: its chunk keeps a clear // `committed` bit, a fresh reservation is released whole. @@ -649,6 +715,7 @@ pub fn segment_alloc_for(arena_id: i32, first: usize) -> Result<*mut Segment, Pr (*seg).thread_id = AtomicUsize::new(crate::init::thread_id()); (*seg).mem_is_zero = mem_zero; (*seg).purged_any = false; + (*seg).huge_trim = 0; (*seg).purge_expire = 0; (*seg).guarded = false; (*seg).next = ptr::null_mut(); @@ -676,17 +743,26 @@ unsafe fn restore_for_reuse(seg: *mut Segment) -> bool { } let base = seg.cast::().add(HEADER_SLICES * SEGMENT_SLICE_SIZE); let bytes = (*seg).total_size - HEADER_SLICES * SEGMENT_SLICE_SIZE; + // What is not committed: all of it after a purge, or only the tail + // a huge block never had (`Segment::huge_trim`). + let trim = (*seg).huge_trim; + let (cbase, cbytes) = if trim != 0 { + (seg.cast::().add(trim), (*seg).total_size - trim) + } else { + (base, bytes) + }; // Commit BEFORE lifting the guard. A purged guarded segment (purging // on, `huge_free`) has its guard page decommitted with the rest, and // Windows' `VirtualProtect` refuses decommitted pages, so the old // order failed on every such free and retired the chunk in place // (`recommit_tests::a_freed_guarded_object_recycles_its_chunk_with_purging_on`). // Once all of it is committed the protect succeeds either way. - if os::commit(base, bytes).is_err() || os::protect(base, bytes, false).is_err() { + if os::commit(cbase, cbytes).is_err() || os::protect(base, bytes, false).is_err() { crate::stats::commit_failed(); return false; } (*seg).purged_any = false; + (*seg).huge_trim = 0; (*seg).guarded = false; true } @@ -712,11 +788,22 @@ pub unsafe fn segment_free(seg: *mut Segment) -> Result<(), PrimError> { // purged or never-committed slices are recorded on the chunk instead // of committed back, so the next tenant commits only what it carves. // SAFETY: seg is live per the contract; reading its header. - let full = unsafe { + // A segment with no hole below `commit_end` hands its chunk back + // with that prefix recorded; one with a purged span or a short page + // in it, as uncommitted (its holes are not tracked on the chunk). + // SAFETY: seg is live per the contract; reading its header. + let (end, clean) = unsafe { debug_assert!(!(*seg).guarded, "guard page in a Normal segment"); - (*seg).commit_end as usize == SLICES_PER_SEGMENT && !(*seg).purged_any + ((*seg).commit_end as usize, !(*seg).purged_any) + }; + let released = if clean && end == SLICES_PER_SEGMENT { + crate::arena::chunk_release(seg.cast(), 1, Some(true), pending) + } else if clean { + crate::arena::chunk_release_part(seg.cast(), end * SEGMENT_SLICE_SIZE, pending) + } else { + crate::arena::chunk_release(seg.cast(), 1, Some(false), pending) }; - if crate::arena::chunk_release(seg.cast(), 1, Some(full), pending) { + if released { return Ok(()); } } @@ -1067,19 +1154,114 @@ pub unsafe fn debug_validate_segment(seg: *mut Segment, where_: &str) { /// # Safety /// `seg` must be a live Normal segment under the heap lock. pub unsafe fn span_alloc(seg: *mut Segment, slices: usize) -> (*mut Page, bool) { + // SAFETY: forwarded contract. + unsafe { span_alloc_impl(seg, slices, 0) } +} + +/// [`span_alloc`] for a page that commits as it fills +/// ([`PAGE_LAZY_COMMIT`]): only the span's first slice (of a small page, its +/// first [`LAZY_UNIT`]) is sure to be committed on return, and +/// [`Page::lazy_end`] says how much is. The caller +/// commits further with [`page_commit_to`] before writing past them. +/// +/// # Safety +/// As [`span_alloc`]. +pub unsafe fn span_alloc_lazy(seg: *mut Segment, slices: usize) -> (*mut Page, bool) { + // SAFETY: forwarded contract. + unsafe { span_alloc_first(seg, slices, lazy_first(slices)) } +} + +/// [`span_alloc`] committing only the span's first `first` bytes where the +/// span is not already committed ([`PAGE_LAZY_COMMIT`]; elsewhere this is +/// `span_alloc`). `first` is [`lazy_first`] for a page, or, for a large +/// block, its size rounded up to OS pages: a span is whole slices, and a +/// 70 KiB block otherwise commits 128. On return [`Page::lazy_end`] is +/// non-zero if the span is short, and then exactly `first` bytes of it are +/// sure to be backed. +/// +/// # Safety +/// As [`span_alloc`]; `0 < first <= slices * SEGMENT_SLICE_SIZE`, a multiple +/// of the OS page size. +pub unsafe fn span_alloc_first( + seg: *mut Segment, + slices: usize, + first: usize, +) -> (*mut Page, bool) { + // SAFETY: forwarded contract. + unsafe { span_alloc_impl(seg, slices, if PAGE_LAZY_COMMIT { first } else { 0 }) } +} + +/// The shortest free span that is purged: two slices (128 KiB), or a medium +/// page where that is shorter. +/// +/// It was a medium page (eight slices, 512 KiB), on the reasoning that a +/// system call costs more than a few slices return. Measured on fast-decomp +/// with the purge delay in force (issue 63, six threads, medians): OpenTTD's +/// peak 403 MiB at eight slices, 390 at four, 392 at two, 398 at one; +/// Godot's 1,165 at eight, 1,143 at two, 1,111 at one; run time the same in +/// every arm. Free spans of two to seven slices are what a heap is left with +/// between its live pages, and under a delay only those that stay free are +/// purged. One slice stays exempt: it is every small page a size class +/// retires and takes back. +const PURGE_MIN_SLICES: usize = if crate::types::MEDIUM_PAGE_SLICES > 2 { + 2 +} else { + crate::types::MEDIUM_PAGE_SLICES +}; + +/// Whether memory this platform has decommitted reads as zero once it is +/// committed again: Linux `MADV_DONTNEED` on private anonymous memory, the +/// Darwin remap (`prim::unix::decommit`), Windows `MEM_DECOMMIT` and a later +/// `MEM_COMMIT`. Not miri's mock, whose decommit leaves the bytes as they are. +const DECOMMIT_ZEROES: bool = cfg!(all(any(unix, windows), not(miri))); + +/// Whether a purge done with `decommits` leaves the span reading as zero +/// (a reset, `MADV_FREE` / `MEM_RESET`, leaves it undefined). +#[inline] +const fn purge_zeroes(decommits: bool) -> bool { + decommits && DECOMMIT_ZEROES +} + +/// What [`Page::lazy_end`] holds on a short LARGE span: only that it is +/// short. Its committed extent is its `block_size`. +const LAZY_LARGE: u8 = u8::MAX; + +/// The body of [`span_alloc`] and [`span_alloc_first`]: `lazy_bytes` is the +/// latter's `first`, or 0 for a span committed whole. +/// +/// # Safety +/// As [`span_alloc_first`]. +#[inline(always)] +unsafe fn span_alloc_impl( + seg: *mut Segment, + slices: usize, + lazy_bytes: usize, +) -> (*mut Page, bool) { + let whole = slices * SEGMENT_SLICE_SIZE; + // A request for all of it is not lazy. + let lazy = lazy_bytes != 0 && lazy_bytes < whole; + // A large block's exact extent, as against a page's first slice or unit. + let large = lazy && lazy_bytes > SEGMENT_SLICE_SIZE; + // How many bytes of a span that is not known to be committed are + // committed here. + let first = if lazy { lazy_bytes } else { whole }; // SAFETY: caller contract — seg is live under the owner. unsafe { debug_validate_segment(seg, "span_alloc:enter") }; // SAFETY: heap lock held; list and indices maintained by the invariants // in the module docs. unsafe { - // First fit over reclaimed spans (recycled memory — NOT zero). + // First fit over reclaimed spans: recycled memory, not zero, unless + // it was purged by a decommit and nothing has written it since + // (`free_is_zero` on a free span's slot, set where it is purged). let mut s = (*seg).free_spans; while !s.is_null() { let len = (*s).slice_count as usize; if len >= slices { let idx = page_index(seg, s); - // Re-commit BEFORE splitting so both halves are backed; the - // remainder inherits the (now cleared) purged state. + // Re-commit what is TAKEN, before anything changes; the + // remainder keeps the flags of the span it is split from. + // (Until 2.6.0 the whole free span was re-committed here, so + // taking one slice from a purged 6 MiB span committed 6 MiB.) // // A failed re-commit is a failed allocation, never a span // handed out unbacked: Windows has no overcommit, so @@ -1090,21 +1272,44 @@ pub unsafe fn span_alloc(seg: *mut Segment, slices: usize) -> (*mut Page, bool) // on the free list, still marked purged; null sends the // caller to another segment, and a fresh one fails its own // commit cleanly. - if !span_recommit(seg, idx, len) { - return (ptr::null_mut(), false); + let (was_purged, was_partly) = ((*s).purged, (*s).partly); + // A span decommitted whole reads as zero once committed: + // `calloc` of it zeroes nothing, as of fresh memory, where it + // used to write every byte of a large block back to zero. + let mut was_zero = false; + if was_purged { + was_zero = !was_partly && (*s).free_is_zero; + let area = page_area(seg, idx); + if os::commit(area, first).is_err() { + crate::stats::commit_failed(); + return (ptr::null_mut(), false); + } } span_list_remove(seg, s); if len > slices { // The remainder starts at a new slice: re-mark all of it. let rest = s.add(slices); span_mark_free(seg, rest, idx + slices, len - slices, 1); - // It has been free as long as the span it came from. + // It has been free as long as the span it came from, and + // is backed exactly as that span was. (*rest).capacity = (*s).capacity; + (*rest).purged = was_purged; + (*rest).partly = was_partly; + (*rest).free_is_zero = was_zero; } // The FRONT of a free span: its interiors already point here. span_mark(seg, s, idx, slices, slices); + (*s).purged = false; + (*s).partly = false; + (*s).lazy_end = if !(was_purged && lazy) { + 0 + } else if large { + LAZY_LARGE + } else { + (first / LAZY_UNIT) as u8 + }; (*seg).used_pages += 1; - return (s, false); + return (s, was_zero); } s = (*s).next; } @@ -1116,11 +1321,54 @@ pub unsafe fn span_alloc(seg: *mut Segment, slices: usize) -> (*mut Page, bool) } // Commit ahead of the cursor before anything is carved. A refusal is // a failed span, exactly as a refused re-commit above. - if LAZY_COMMIT - && idx + slices > (*seg).commit_end as usize - && !commit_frontier(seg, idx + slices) - { - return (ptr::null_mut(), false); + // + // A lazy span takes what is already committed at the cursor, and one + // slice when nothing is: `commit_frontier` then adds no read-ahead. + let mut lazy_end = 0; + if LAZY_COMMIT && large { + // A large block: commit from what the frontier already covers + // to the block's last OS page, and step `commit_end` past the + // span. The rest of its last slice stays reserved. + let have = (*seg).commit_end as usize; + if idx + slices > have { + let from = have.max(idx) * SEGMENT_SLICE_SIZE; + let end = idx * SEGMENT_SLICE_SIZE + first; + if end > from && os::commit(seg.cast::().add(from), end - from).is_err() { + crate::stats::commit_failed(); + return (ptr::null_mut(), false); + } + (*seg).commit_end = (idx + slices) as u32; + lazy_end = LAZY_LARGE; + (*seg).purged_any = true; + } + } else if LAZY_COMMIT && lazy && slices == 1 { + // A small page: whole if its slice is already committed, else + // its first unit. `commit_end` steps past the slice: the rest + // of it is this page's to commit. + if idx >= (*seg).commit_end as usize { + if os::commit(page_area(seg, idx), LAZY_UNIT).is_err() { + crate::stats::commit_failed(); + return (ptr::null_mut(), false); + } + (*seg).commit_end = (idx + 1) as u32; + lazy_end = 1; + (*seg).purged_any = true; + } + } else if LAZY_COMMIT { + let need = if lazy { 1 } else { slices }; + if idx + need > (*seg).commit_end as usize + && !commit_frontier(seg, idx, idx + need, !lazy) + { + return (ptr::null_mut(), false); + } + if lazy { + let got = (*seg).commit_end as usize - idx; + if got < slices { + lazy_end = (got * (SEGMENT_SLICE_SIZE / LAZY_UNIT)) as u8; + // The segment now has a hole below its cursor. + (*seg).purged_any = true; + } + } } // First carve of these slots in this tenancy: on a recycled chunk // they still hold the previous tenant's bytes (`scrub_recycled` left @@ -1134,10 +1382,168 @@ pub unsafe fn span_alloc(seg: *mut Segment, slices: usize) -> (*mut Page, bool) (*seg).used_pages += 1; // Never-carved slices: mark all of them. span_mark(seg, start, idx, slices, 1); + (*start).lazy_end = lazy_end; (start, (*seg).mem_is_zero) } } +/// Grow a live LARGE block in place to hold `bytes` bytes, if what follows +/// its span is the bump cursor or a free span with the room. Returns whether +/// it did; on false nothing has changed, and the caller moves the block. +/// +/// A large block that grows is a buffer being appended to, and until now it +/// moved every time: a fresh span, a copy of the whole block, and the old +/// span left free behind it, the wrong size for the next growth. Measured on +/// fast-decomp's OpenTTD run (issue 63), by bytes of large span freed: the +/// cursor followed 12 %, a free span at least as long 23 %, a shorter free +/// span 24 %. Those are the cases this serves, without the copy. +/// +/// The block's size becomes `bytes` rounded up to OS pages where a span +/// commits short ([`PAGE_LAZY_COMMIT`]), else its whole slices. +/// +/// # Safety +/// `page` is a live single-block span start of the Normal segment `seg`, +/// neither huge nor an aligned placement, and the caller is the thread that +/// owns `seg`; `bytes` is more than the block's size and at most +/// `LARGE_OBJ_SIZE_MAX`. +#[cold] +pub unsafe fn span_grow(seg: *mut Segment, page: *mut Page, bytes: usize) -> bool { + // SAFETY: caller contract; every index below is inside the segment, and + // every range committed is inside the grown span. + unsafe { + debug_validate_segment(seg, "span_grow:enter"); + let idx = page_index(seg, page); + let old = (*page).slice_count as usize; + let need = bytes.div_ceil(SEGMENT_SLICE_SIZE); + if idx + need > SLICES_PER_SEGMENT { + return false; + } + let area = (*page).area; + // What is backed now, and what will be: to the last OS page where a + // span commits short, to the last slice otherwise. + let short = (*page).lazy_end != 0; + let have = if short { + (*page).block_size + } else { + old * SEGMENT_SLICE_SIZE + }; + let want = if PAGE_LAZY_COMMIT { + os::page_align_up(bytes) + } else { + need * SEGMENT_SLICE_SIZE + }; + let next = idx + old; + if need > old { + if next == (*seg).next_free_slice as usize { + // The cursor follows: the span takes never-carved slices. + // Read-ahead may have committed some of them already. + let from = if short { + have + } else { + ((*seg).commit_end as usize) + .clamp(next, idx + need) + .saturating_sub(idx) + * SEGMENT_SLICE_SIZE + }; + if want > from && LAZY_COMMIT && os::commit(area.add(from), want - from).is_err() { + crate::stats::commit_failed(); + return false; + } + let first: *mut Page = (&raw mut (*seg).pages).cast::().add(next); + if !(*seg).mem_is_zero { + ptr::write_bytes(first, 0, need - old); + } + (*seg).next_free_slice = (idx + need) as u32; + if LAZY_COMMIT && (idx + need) as u32 > (*seg).commit_end { + (*seg).commit_end = (idx + need) as u32; + } + } else { + // A free span follows, or nothing that helps. + let f: *mut Page = (&raw mut (*seg).pages).cast::().add(next); + if next > (*seg).next_free_slice as usize || (*f).block_size != 0 { + return false; + } + let flen = (*f).slice_count as usize; + if old + flen < need { + return false; + } + // Back what is not known to be: our own short tail, and a + // neighbour flagged for re-commit. A neighbour that is backed + // is not committed again (the call would be charged in full + // while it ran), and the block then has all of its slices. + let (f_purged, f_partly) = ((*f).purged, (*f).partly); + let whole = need * SEGMENT_SLICE_SIZE; + let (from, to, want) = if f_purged { + ( + if short { + have + } else { + old * SEGMENT_SLICE_SIZE + }, + want, + want, + ) + } else if short { + (have, old * SEGMENT_SLICE_SIZE, whole) + } else { + (0, 0, whole) + }; + if to > from && os::commit(area.add(from), to - from).is_err() { + crate::stats::commit_failed(); + return false; + } + span_list_remove(seg, f); + if old + flen > need { + // The remainder starts at a new slice: re-mark all of + // it. It has been free as long as the span it came from, + // and is backed exactly as that span was. + let rest = f.add(need - old); + let stamp = (*f).capacity; + let zero = f_purged && !f_partly && (*f).free_is_zero; + span_mark_free(seg, rest, idx + need, old + flen - need, 1); + (*rest).capacity = stamp; + (*rest).purged = f_purged; + (*rest).partly = f_partly; + (*rest).free_is_zero = zero; + } + // The taken slot is an interior slice of ours now. + (*f).purged = false; + (*f).partly = false; + span_mark(seg, page, idx, need, old); + (*page).block_size = want; + (*page).lazy_end = if want < need * SEGMENT_SLICE_SIZE { + (*seg).purged_any = true; + LAZY_LARGE + } else { + 0 + }; + (*page).free_is_zero = false; + debug_validate_segment(seg, "span_grow:exit"); + return true; + } + span_mark(seg, page, idx, need, old); + } else if want > have && os::commit(area.add(have), want - have).is_err() { + // Room in its own last slice, which a short span left reserved. + crate::stats::commit_failed(); + return false; + } + (*page).block_size = if LAZY_COMMIT { + want + } else { + need * SEGMENT_SLICE_SIZE + }; + (*page).lazy_end = if LAZY_COMMIT && want < need * SEGMENT_SLICE_SIZE { + (*seg).purged_any = true; + LAZY_LARGE + } else { + 0 + }; + (*page).free_is_zero = false; + debug_validate_segment(seg, "span_grow:exit"); + true + } +} + /// Return a page's span to the segment, coalescing with free neighbors. /// Freed spans NEVER rejoin the bump frontier: `[next_free_slice, …)` is the /// virgin-zero region and bump allocations report `fresh = true` — giving @@ -1153,6 +1559,33 @@ pub unsafe fn span_alloc(seg: *mut Segment, slices: usize) -> (*mut Page, bool) /// `page` must be a live span-start of `seg` with no live blocks, under the /// heap lock. pub unsafe fn span_free(seg: *mut Segment, page: *mut Page) -> usize { + // SAFETY: forwarded contract. + unsafe { span_free_impl::(seg, page) } +} + +/// [`span_free`] for a heap that is being torn down: a freed span is not +/// stamped or scheduled for a delayed purge (`purge_delay = 0` still purges +/// at once). The dying thread's segment is next either freed whole, its +/// chunk going back to the arena on a delay of its own, or abandoned, and an +/// abandoned segment's free spans are all purged as it is published +/// ([`purge_free_spans`]). The schedule bought nothing in either case, and +/// cost a clock read per coalesced span plus a forced pass that purged them +/// one by one (the short-lived-threads probe: four clock reads and two +/// `madvise` a thread). +/// +/// # Safety +/// As [`span_free`]. +pub unsafe fn span_free_unscheduled(seg: *mut Segment, page: *mut Page) -> usize { + // SAFETY: forwarded contract. + unsafe { span_free_impl::(seg, page) } +} + +/// The body of [`span_free`] and [`span_free_unscheduled`]. +/// +/// # Safety +/// As [`span_free`]. +#[inline(always)] +unsafe fn span_free_impl(seg: *mut Segment, page: *mut Page) -> usize { // SAFETY: caller contract — seg is live under the owner. unsafe { debug_validate_segment(seg, "span_free:enter") }; // SAFETY: heap lock held; boundary reads follow the span invariants. @@ -1162,6 +1595,10 @@ pub unsafe fn span_free(seg: *mut Segment, page: *mut Page) -> usize { // Where the freed span sat before any merge: its interiors already // point back to `freed_idx` (see `span_mark`). let (freed_idx, freed_len) = (idx, len); + // A page freed before it was committed whole: its span is not backed + // throughout, which is what the `purged` flag says of a free span. + let freed_short = PAGE_LAZY_COMMIT && (*page).lazy_end != 0; + (*page).lazy_end = 0; (*seg).used_pages -= 1; // Scrub page state so a stale slot can't masquerade as live. (*page).block_size = 0; @@ -1188,7 +1625,7 @@ pub unsafe fn span_free(seg: *mut Segment, page: *mut Page) -> usize { // up behind a clear flag and is reused unbacked: the write fault of // `docs/plans/recommit-failure-ignored.md`, mechanism B. A spurious // flag costs only a re-commit of committed memory. - let mut merged_purged = false; + let mut merged_purged = freed_short; // The merged span's first slot: ours, unless a left neighbour takes // us in. let mut head = page; @@ -1221,6 +1658,11 @@ pub unsafe fn span_free(seg: *mut Segment, page: *mut Page) -> usize { idx = lstart_idx; head = lstart; merged_purged |= (*lstart).purged; + // The merged span holds the one just freed, which held + // blocks: not zero, whatever the left one was. (Without a + // left merge the head is the freed page, scrubbed above, and + // a right neighbour's slot becomes an interior one.) + (*lstart).free_is_zero = false; } } // Re-mark only what does not already point to `idx`: with no left @@ -1249,7 +1691,7 @@ pub unsafe fn span_free(seg: *mut Segment, page: *mut Page) -> usize { // Purging at once turned a loop that frees and re-allocates a 1 MiB // buffer from 0.7 to 207 us per iteration, every page refaulted // (`docs/plans/free-slot-purge.md`). - let delay = if len >= crate::types::MEDIUM_PAGE_SLICES { + let delay = if len >= PURGE_MIN_SLICES { crate::options::get(15) } else { -1 @@ -1260,6 +1702,8 @@ pub unsafe fn span_free(seg: *mut Segment, page: *mut Page) -> usize { let decommits = crate::options::is_enabled(5); // purge_decommits if os::purge(area, bytes, decommits).is_ok() { (*head).purged = true; + (*head).partly = false; + (*head).free_is_zero = purge_zeroes(decommits); (*seg).purged_any = true; return 1; } @@ -1267,12 +1711,17 @@ pub unsafe fn span_free(seg: *mut Segment, page: *mut Page) -> usize { // Not re-purged as a whole (purging off by now, the span too small, // the purge failed or is only scheduled): the merged span is backed // only if every part was. Never cleared here: the start may already - // be flagged. + // be flagged. It is `partly` backed at least: the span just freed + // held live blocks, so it stays a purge candidate. (Before 2.6.1 a + // resident span that merged with a purged neighbour was flagged + // purged and never purged again until it was reused.) if merged_purged { (*head).purged = true; + (*head).partly = true; + (*seg).purged_any = true; } - if crate::OS_PAGES && delay > 0 { - return schedule_purge(seg, idx, delay as u64); + if SCHEDULE && crate::OS_PAGES && delay > 0 { + return schedule_purge(seg, head, delay as u64); } 0 } @@ -1293,11 +1742,11 @@ fn now_ms(now_ns: u64) -> u32 { /// The `purge_delay` option as a millisecond count the wrapping age compare /// can use. -fn delay_ms() -> u32 { +pub fn delay_ms() -> u32 { crate::options::get(15).clamp(0, i64::from(u32::MAX / 2)) as u32 } -/// The purge candidate starting at slot `idx` was just freed under a positive +/// The purge candidate whose first slot is `head` was just freed under a positive /// `purge_delay` of `delay_ms`: stamp when, then start the segment's deadline /// if none is running, or, if it has passed, purge the candidates that are /// due. Returns how many spans were purged. @@ -1307,13 +1756,13 @@ fn delay_ms() -> u32 { /// delay never refaults it, however long the loop runs. /// /// # Safety -/// `seg` is a live Normal segment under its owner; `idx` a free span start. +/// `seg` is a live Normal segment under its owner; `head` a free span start in it. #[cold] -unsafe fn schedule_purge(seg: *mut Segment, idx: usize, delay_ms: u64) -> usize { +unsafe fn schedule_purge(seg: *mut Segment, head: *mut Page, delay_ms: u64) -> usize { let now = crate::prim::clock_now(); // SAFETY: caller contract. unsafe { - (*seg).pages[idx].capacity = now_ms(now); + (*head).capacity = now_ms(now); let exp = (*seg).purge_expire; if exp == 0 { (*seg).purge_expire = now @@ -1345,8 +1794,53 @@ pub unsafe fn purge_scheduled(seg: *mut Segment, now: Option) -> usize { } } +/// Purge the candidates of `seg` that have been free for more than +/// `min_age_ms` at `now`, whatever the segment's own deadline says, and clear +/// that deadline if none is left. For [`crate::heap::Heap::purge_tick`], whose +/// `min_age_ms` is the time since it last looked: a span is given back only +/// if it was already free then and has not been taken since, so a heap that +/// frees its spans, idles past the delay and takes them back (a frame, a +/// request) never purges what it is about to reuse. Returns how many spans +/// were purged. +/// +/// # Safety +/// `seg` is a live Normal segment under its owner. +pub unsafe fn purge_aged(seg: *mut Segment, now: u64, min_age_ms: u32) -> usize { + // SAFETY: caller contract; free spans hold no live blocks. + unsafe { + let decommits = crate::options::is_enabled(5); // purge_decommits + let now = now_ms(now); + let (mut n, mut left) = (0, false); + let mut s = (*seg).free_spans; + while !s.is_null() { + let len = (*s).slice_count as usize; + if (!(*s).purged || (*s).partly) && len >= PURGE_MIN_SLICES { + let area = page_area(seg, page_index(seg, s)); + // Strictly older: stamps are whole milliseconds, and a span + // freed in the millisecond of the last look was freed after it. + if now.wrapping_sub((*s).capacity) > min_age_ms + && os::purge(area, len * SEGMENT_SLICE_SIZE, decommits).is_ok() + { + (*s).purged = true; + (*s).partly = false; + (*s).free_is_zero = purge_zeroes(decommits); + (*seg).purged_any = true; + n += 1; + } else { + left = true; + } + } + s = (*s).next; + } + if !left { + (*seg).purge_expire = 0; + } + n + } +} + /// Purge the candidates of `seg` (free, unpurged spans of at least -/// `MEDIUM_PAGE_SLICES` slices, the spans `purge_delay = 0` purges as they +/// [`PURGE_MIN_SLICES`] slices, the spans `purge_delay = 0` purges as they /// are freed) that have been free for the whole delay at `now`, or all of /// them when `now` is `None`; then set the deadline to when the next one left /// falls due, or clear it. Each purged span is marked so reuse re-commits it. @@ -1364,7 +1858,7 @@ unsafe fn purge_candidates(seg: *mut Segment, now: Option) -> usize { let mut s = (*seg).free_spans; while !s.is_null() { let len = (*s).slice_count as usize; - if !(*s).purged && len >= crate::types::MEDIUM_PAGE_SLICES { + if (!(*s).purged || (*s).partly) && len >= PURGE_MIN_SLICES { // Milliseconds this span must still wait; none when forced. let wait = now.map_or(0, |t| { delay.saturating_sub(now_ms(t).wrapping_sub((*s).capacity)) @@ -1375,6 +1869,8 @@ unsafe fn purge_candidates(seg: *mut Segment, now: Option) -> usize { let area = page_area(seg, page_index(seg, s)); if os::purge(area, len * SEGMENT_SLICE_SIZE, decommits).is_ok() { (*s).purged = true; + (*s).partly = false; + (*s).free_is_zero = purge_zeroes(decommits); (*seg).purged_any = true; n += 1; } @@ -1415,7 +1911,7 @@ pub unsafe fn purge_free_spans(seg: *mut Segment) { let mut s = (*seg).free_spans; while !s.is_null() { let next = (*s).next; - if !(*s).purged { + if !(*s).purged || (*s).partly { let idx = page_index(seg, s); let len = (*s).slice_count as usize; if len > 0 { @@ -1423,6 +1919,8 @@ pub unsafe fn purge_free_spans(seg: *mut Segment) { let bytes = len * SEGMENT_SLICE_SIZE; if os::purge(area, bytes, decommits).is_ok() { (*s).purged = true; + (*s).partly = false; + (*s).free_is_zero = purge_zeroes(decommits); (*seg).purged_any = true; } } @@ -1432,49 +1930,75 @@ pub unsafe fn purge_free_spans(seg: *mut Segment) { } } -/// Re-commit a span that was purged while free (no-op otherwise). Returns -/// whether the span is backed. On failure the span stays marked purged, so -/// nothing forgets that its memory is not there. +/// Commit a live, lazily committed page far enough to hold `bytes` of +/// blocks from its area's start ([`PAGE_LAZY_COMMIT`]). Returns whether that +/// much is backed; on refusal, counted in [`crate::stats::commit_failures`], +/// the page is unchanged. /// /// # Safety -/// `[idx, idx+len)` is a span of `seg` about to be handed to a caller. -unsafe fn span_recommit(seg: *mut Segment, idx: usize, len: usize) -> bool { - // SAFETY: caller contract; range lies inside the segment reservation. +/// `page` is a live span start under its owner, with `lazy_end != 0` and +/// `bytes` no more than its span. +#[cold] +pub unsafe fn page_commit_to(page: *mut Page, bytes: usize) -> bool { + // SAFETY: caller contract; the range lies inside the page's span. unsafe { - if !(*seg).pages[idx].purged { + // In `LAZY_UNIT`s from the span's start. + let have = (*page).lazy_end as usize; + let slices = (*page).slice_count as usize; + let all = slices * (SEGMENT_SLICE_SIZE / LAZY_UNIT); + debug_assert!(have != 0 && have < all); + let need = bytes.div_ceil(LAZY_UNIT).min(all); + if need <= have { return true; } - let area = page_area(seg, idx); - if os::commit(area, len * SEGMENT_SLICE_SIZE).is_err() { + // A medium page commits whole slices. A small page doubles what it + // has, so one that fills pays two calls after its first unit. + let want = if slices == 1 { + need.max(2 * have).min(all) + } else { + need.next_multiple_of(SEGMENT_SLICE_SIZE / LAZY_UNIT) + }; + let base = (*page).area.add(have * LAZY_UNIT); + if os::commit(base, (want - have) * LAZY_UNIT).is_err() { crate::stats::commit_failed(); return false; } - (*seg).pages[idx].purged = false; + (*page).lazy_end = if want == all { 0 } else { want as u8 }; true } } -/// Commit `seg` up to at least slice `need` (`need > commit_end`): doubling -/// the committed prefix, by at most [`COMMIT_STEP_MAX_SLICES`] beyond `need`, -/// and falling back to exactly `need` if the OS refuses the larger range. -/// Returns false, counted in [`crate::stats::commit_failures`], when even -/// that is refused; `commit_end` is then unchanged. +/// Commit `seg` from the cursor `idx` up to at least slice `need` +/// (`need > commit_end`). With `ahead`, the committed range doubles, by at +/// most [`COMMIT_STEP_MAX_SLICES`] beyond `need`, falling back to exactly +/// `need` if the OS refuses the larger range. Returns false, counted in +/// [`crate::stats::commit_failures`], when even that is refused; `commit_end` +/// is then unchanged. +/// +/// The range starts at the cursor when that is above `commit_end`: the +/// slices between are the uncommitted tail of a lazily committed page, and +/// stay that page's to commit. /// /// # Safety -/// `seg` is a live Normal segment under its owner; `need <= SLICES_PER_SEGMENT`. +/// `seg` is a live Normal segment under its owner; `idx` is its bump cursor +/// and `idx < need <= SLICES_PER_SEGMENT`. #[cold] -unsafe fn commit_frontier(seg: *mut Segment, need: usize) -> bool { +unsafe fn commit_frontier(seg: *mut Segment, idx: usize, need: usize, ahead: bool) -> bool { // SAFETY: caller contract; every range lies inside the reservation. unsafe { let have = (*seg).commit_end as usize; - debug_assert!(need > have && need <= SLICES_PER_SEGMENT); - let want = need - .max(have + have.min(COMMIT_STEP_MAX_SLICES)) - .min(SLICES_PER_SEGMENT); - let base = seg.cast::().add(have * SEGMENT_SLICE_SIZE); - let end = if os::commit(base, (want - have) * SEGMENT_SLICE_SIZE).is_ok() { + let from = have.max(idx); + debug_assert!(need > from && need <= SLICES_PER_SEGMENT); + let want = if ahead { + need.max(from + have.min(COMMIT_STEP_MAX_SLICES)) + .min(SLICES_PER_SEGMENT) + } else { + need + }; + let base = seg.cast::().add(from * SEGMENT_SLICE_SIZE); + let end = if os::commit(base, (want - from) * SEGMENT_SLICE_SIZE).is_ok() { want - } else if want > need && os::commit(base, (need - have) * SEGMENT_SLICE_SIZE).is_ok() { + } else if want > need && os::commit(base, (need - from) * SEGMENT_SLICE_SIZE).is_ok() { need } else { crate::stats::commit_failed(); @@ -1545,16 +2069,30 @@ pub fn huge_alloc( let Some(chunk_bytes) = chunks.checked_mul(SEGMENT_SIZE) else { return Err(0); }; - let (bptr, total, mem_zero) = match crate::arena::chunk_alloc_n(arena_id, chunks) { - Some((p, zero)) => (p, chunk_bytes, zero), - None => { - if arena_id >= 0 { - return Err(0); // exclusive-arena heap and its arena is full - } - let (p, sz, zero) = reserve_backing(want, true)?; - (p, sz, zero) - } + // Where committed memory is charged untouched (`PAGE_LAZY_COMMIT`), ask + // the arena to commit what the block can reach, not the whole run: a + // huge block takes whole 32 MiB chunks, so a 33 MiB block committed 64. + // The block ends at most `extra` past the header plus its size rounded up + // to a slice (its `block_size`, below). + let reach = if PAGE_LAZY_COMMIT { + header + .saturating_add(extra) + .saturating_add(crate::prim::align_up(size.max(1), SEGMENT_SLICE_SIZE)) + .min(chunk_bytes) + } else { + chunk_bytes }; + let (bptr, total, mem_zero, committed) = + match crate::arena::chunk_alloc_n_part(arena_id, chunks, reach) { + Some((p, zero, got)) => (p, chunk_bytes, zero, got), + None => { + if arena_id >= 0 { + return Err(0); // exclusive-arena heap and its arena is full + } + let (p, sz, zero) = reserve_backing(want, true)?; + (p, sz, zero, sz) + } + }; let seg: *mut Segment = bptr.cast(); // SAFETY: header scalars fully written below; a recycled chunk's owner // table and the two slots a huge segment uses (0, and 1 for its page) are @@ -1583,6 +2121,7 @@ pub fn huge_alloc( (*seg).thread_id = AtomicUsize::new(crate::init::thread_id()); (*seg).mem_is_zero = b.is_zero; (*seg).purged_any = false; + (*seg).huge_trim = 0; (*seg).purge_expire = 0; (*seg).guarded = false; (*seg).next = ptr::null_mut(); @@ -1623,6 +2162,25 @@ pub fn huge_alloc( // `block_size`; `usable_size` now agrees with `mi_usable_size` here. let capacity = b.size - (block.addr() - seg.addr()); (*page).block_size = crate::prim::align_up(size.max(1), SEGMENT_SLICE_SIZE).min(capacity); + // The tail the block does not reach (`PAGE_LAZY_COMMIT`). Either the + // arena committed only `committed` bytes of the run, or the run came + // committed whole (recycled chunks) and the tail is given back here. + // `purged_any` and `huge_trim` make `huge_free` commit that tail + // again, and only it, before the chunks are recycled. A refused + // decommit changes nothing: the tail stays committed. + if PAGE_LAZY_COMMIT { + let used = os::page_align_up(block.addr() - seg.addr() + (*page).block_size); + debug_assert!(used <= committed, "a huge block reaches past its commit"); + if committed < b.size { + (*seg).purged_any = true; + (*seg).huge_trim = committed; + } else if used < b.size + && os::decommit(seg.cast::().add(used), b.size - used).is_ok() + { + (*seg).purged_any = true; + (*seg).huge_trim = used; + } + } (*page).used = 1; (*page).capacity = 1; (*page).reserved = 1; @@ -1704,11 +2262,16 @@ pub unsafe fn huge_free(seg: *mut Segment) -> Result<(), PrimError> { // they have stayed free that long (`arena::purge_due`): a loop that // frees and re-allocates a huge buffer then refaults nothing. let delay = crate::options::get(15); + // Part of the run was never committed, so the arena has it marked + // uncommitted; the restore below commits it, and the release says so. + let was_short = (*seg).huge_trim != 0; if chunked && delay == 0 && crate::arena::owns(seg.cast()) { let base = seg.cast::().add(HEADER_SLICES * SEGMENT_SLICE_SIZE); let bytes = (*seg).total_size - HEADER_SLICES * SEGMENT_SLICE_SIZE; if os::purge(base, bytes, crate::options::is_enabled(5)).is_ok() { (*seg).purged_any = true; + // Nothing is committed now: restore all of it. + (*seg).huge_trim = 0; } } let usable = !chunked || restore_for_reuse(seg); @@ -1720,7 +2283,7 @@ pub unsafe fn huge_free(seg: *mut Segment) -> Result<(), PrimError> { } else if crate::arena::chunk_release( seg.cast(), (*seg).total_size / SEGMENT_SIZE, - None, + if was_short { Some(true) } else { None }, crate::OS_PAGES && delay > 0, ) { return Ok(()); @@ -2061,6 +2624,10 @@ mod lazy_commit_tests { // SAFETY: segments from our own exclusive arena, used by this thread // alone, freed empty. unsafe { + // Start from a chunk with nothing committed, whatever an earlier + // test left in it. + let (p, _, _) = crate::arena::chunk_claim(id).expect("the arena's chunk"); + assert!(crate::arena::chunk_free_marked(p, false)); let seg = segment_alloc(id).expect("segment from the arena"); assert_eq!( (*seg).commit_end as usize, @@ -2079,11 +2646,39 @@ mod lazy_commit_tests { span_free(seg, pg2); segment_free(seg).expect("free"); - let (p, _, committed) = crate::arena::chunk_claim(id).expect("the chunk came back"); + // The chunk remembers the committed prefix, and only that. + let (p, _, got) = crate::arena::chunk_claim_part(id).expect("the chunk came back"); assert_eq!(p, seg.cast(), "the arena has one chunk"); - assert!( - !committed, - "a partly committed chunk came back marked committed" + assert_eq!( + got, + 8 * SEGMENT_SLICE_SIZE, + "the chunk did not keep its tenant's committed prefix" + ); + assert!(crate::arena::chunk_release_part(p, got, false)); + // And the next tenant takes it as committed: no commit to carve + // inside it, every byte of it writable. + let before = crate::os::test_hooks::committed_bytes(); + let seg = segment_alloc(id).expect("a tenant of the prefix"); + assert_eq!((*seg).commit_end, 8, "the prefix was not taken over"); + let pg = carve_and_touch(seg, 7); + assert_eq!( + crate::os::test_hooks::committed_bytes(), + before, + "the committed prefix was committed again" + ); + span_free(seg, pg); + segment_free(seg).expect("free"); + // A segment with a purged span in it hands its chunk back with + // nothing recorded (its holes are not tracked on the chunk). + let seg = segment_alloc(id).expect("a tenant with a hole"); + let pg = carve_and_touch(seg, 2); + (*seg).purged_any = true; + span_free(seg, pg); + segment_free(seg).expect("free"); + let (p, _, got) = crate::arena::chunk_claim_part(id).expect("the chunk came back"); + assert_eq!( + got, 0, + "a chunk with a hole came back with a committed prefix" ); assert!(crate::arena::chunk_free_marked(p, false)); @@ -2543,3 +3138,1160 @@ mod free_slot_tests { unsafe { free(blocks[0]) }; } } + +/// Issue 63: what a segment commits, and when it gives memory back. +#[cfg(all(test, feature = "std"))] +mod commit_footprint_tests { + use super::*; + use crate::os::test_hooks::{committed_bytes, fail_next_commits}; + use crate::types::MEDIUM_PAGE_SLICES; + + /// One exclusive reserve-only arena of one chunk (see `lazy_commit_tests`). + fn arena() -> i32 { + static ID: std::sync::OnceLock = std::sync::OnceLock::new(); + *ID.get_or_init(|| { + crate::arena::reserve_os_memory_ex(SEGMENT_SIZE, false, false, true) + .expect("reserve-only arena") + }) + } + + /// Mark `pg` live the way the page layer would (`span_free` reads a zero + /// `block_size` on a neighbour as a free span to merge) and write every + /// byte of its first `slices` slices: an unbacked slice faults here. + /// + /// # Safety + /// `pg` is a span this test owns, with at least `slices` slices backed. + unsafe fn live_and_touch(pg: *mut Page, slices: usize, fill: u8) { + // SAFETY: caller contract. + unsafe { + (*pg).block_size = SEGMENT_SLICE_SIZE; + ptr::write_bytes((*pg).area, fill, slices * SEGMENT_SLICE_SIZE); + } + } + + /// A pinned span, a span of `n` slices purged while free, and a second + /// pin, in that order from the segment's start. + /// + /// # Safety + /// The caller holds the options lock and frees what it is given. + unsafe fn purged_between_pins(n: usize) -> (*mut Segment, usize, [*mut Page; 2]) { + // SAFETY: a segment of our own exclusive arena, this thread only. + unsafe { + let seg = segment_alloc(arena()).expect("segment"); + let (a, _) = span_alloc(seg, 1); + let (v, _) = span_alloc(seg, n); + let (b, _) = span_alloc(seg, 1); + assert!(!a.is_null() && !v.is_null() && !b.is_null()); + live_and_touch(a, 1, 1); + live_and_touch(v, n, 2); + live_and_touch(b, 1, 3); + let idx = page_index(seg, v); + crate::options::set(15, 0); // purge at once + assert_eq!(span_free(seg, v), 1, "setup: the span was not purged"); + assert!((*seg).pages[idx].purged && !(*seg).pages[idx].partly); + (seg, idx, [a, b]) + } + } + + /// # Safety + /// As [`purged_between_pins`]'s results, with every other span freed. + unsafe fn release(seg: *mut Segment, pins: [*mut Page; 2]) { + crate::options::set(15, -1); + // SAFETY: the pins are live spans of `seg`, freed once; then empty. + unsafe { + for p in pins { + span_free(seg, p); + } + segment_free(seg).expect("free"); + } + } + + /// Taking two slices from a purged 40-slice span commits two slices. It + /// used to re-commit all forty. The remainder stays purged, and is + /// committed when it is taken in its turn. + #[test] + fn taking_part_of_a_purged_span_commits_only_what_is_taken() { + if !LAZY_COMMIT { + return; + } + let _g = crate::arena::adopt_tests::lock(); + // SAFETY: as documented on the helpers. + unsafe { + let (seg, idx, pins) = purged_between_pins(40); + crate::options::set(15, -1); // nothing below purges by itself + let before = committed_bytes(); + let (p, fresh) = span_alloc(seg, 2); + assert_eq!(page_index(seg, p), idx, "first fit took another span"); + // Decommitted whole, so it reads as zero once committed again. + assert_eq!( + fresh, + purge_zeroes(crate::options::is_enabled(5)), + "a decommitted span's zero state was misreported" + ); + assert_eq!( + committed_bytes() - before, + 2 * SEGMENT_SLICE_SIZE, + "the commit was not the two slices taken" + ); + live_and_touch(p, 2, 4); + let rest = &raw mut (*seg).pages[idx + 2]; + assert_eq!((*rest).slice_count, 38); + assert!( + (*rest).purged && !(*rest).partly, + "the remainder lost its purged flag: it would be reused unbacked" + ); + // The remainder, taken whole: committed now, and writable. + let before = committed_bytes(); + let (q, _) = span_alloc(seg, 38); + assert_eq!(page_index(seg, q), idx + 2); + assert_eq!(committed_bytes() - before, 38 * SEGMENT_SLICE_SIZE); + live_and_touch(q, 38, 5); + span_free(seg, p); + span_free(seg, q); + release(seg, pins); + } + } + + /// A refused commit of the part taken is a failed span: null, and the + /// span is still free and still flagged. + #[test] + fn a_refused_partial_recommit_is_a_failed_span() { + if !LAZY_COMMIT { + return; + } + let _g = crate::arena::adopt_tests::lock(); + // SAFETY: as documented on the helpers. + unsafe { + let (seg, idx, pins) = purged_between_pins(40); + crate::options::set(15, -1); + let used = (*seg).used_pages; + // The free-list take, then the bump the heap would fall back to. + fail_next_commits(1); + let (p, _) = span_alloc(seg, 2); + assert!( + p.is_null() || page_index(seg, p) != idx, + "took an unbacked span" + ); + if !p.is_null() { + // The first fit failed and the walk ended at the cursor. + live_and_touch(p, 2, 6); + span_free(seg, p); + } + assert_eq!((*seg).used_pages, used); + let v = &raw mut (*seg).pages[idx]; + assert!((*v).purged, "a failed commit cleared the purged flag"); + assert_eq!((*v).block_size, 0, "the span is not free any more"); + assert_eq!((*v).slice_count, 40); + fail_next_commits(0); + let (p, _) = span_alloc(seg, 40); + assert_eq!(page_index(seg, p), idx); + live_and_touch(p, 40, 7); + span_free(seg, p); + release(seg, pins); + } + } + + /// A resident span that merges with a purged neighbour is flagged purged + /// (reuse must re-commit) and `partly` (it is still a purge candidate). + /// Without `partly` its memory stayed resident until the span was reused. + #[test] + fn a_resident_span_merged_with_a_purged_one_is_purged_later() { + if !crate::OS_PAGES || USABLE_SLICES < 64 { + return; + } + let _g = crate::arena::adopt_tests::lock(); + // SAFETY: as documented on the helpers. + unsafe { + let (seg, idx, pins) = purged_between_pins(40); + crate::options::set(15, -1); + let (p, _) = span_alloc(seg, MEDIUM_PAGE_SLICES); + assert_eq!(page_index(seg, p), idx); + live_and_touch(p, MEDIUM_PAGE_SLICES, 8); + // Freed under a long delay: scheduled, and merged with the purged + // remainder to its right. + crate::options::set(15, 60_000); + assert_eq!(span_free(seg, p), 0, "a delayed purge ran at once"); + let v = &raw mut (*seg).pages[idx]; + assert_eq!((*v).slice_count, 40, "the spans did not merge"); + assert!((*v).purged, "the merge is not flagged for re-commit"); + assert!((*v).partly, "the merge is not a purge candidate"); + assert_ne!((*seg).purge_expire, 0, "no deadline was started"); + // Not due: nothing happens. Forced: the whole span goes. + assert_eq!(purge_scheduled(seg, Some(crate::prim::clock_now())), 0); + assert!((*v).partly); + assert_eq!(purge_scheduled(seg, None), 1, "the candidate was skipped"); + assert!((*v).purged && !(*v).partly); + assert_eq!((*seg).purge_expire, 0); + // And it is usable: all forty slices, written. + crate::options::set(15, -1); + let (q, _) = span_alloc(seg, 40); + assert_eq!(page_index(seg, q), idx); + live_and_touch(q, 40, 9); + span_free(seg, q); + release(seg, pins); + } + } + + /// A lazily carved span has its first slice, says how many it has, and + /// is committed further on request; what follows it in the segment is + /// committed from the cursor, not from the old frontier. + #[test] + fn a_lazy_span_commits_as_it_is_asked_to() { + if !PAGE_LAZY_COMMIT { + return; + } + let _g = crate::arena::adopt_tests::lock(); + let n = MEDIUM_PAGE_SLICES; + // SAFETY: a segment of our own exclusive arena, this thread only. + unsafe { + crate::options::set(15, -1); + let seg = segment_alloc(arena()).expect("segment"); + let before = committed_bytes(); + let (p, _) = span_alloc_lazy(seg, n); + assert!(!p.is_null()); + assert_eq!( + (*p).lazy_end as usize * LAZY_UNIT, + SEGMENT_SLICE_SIZE, + "a fresh lazy span is one slice" + ); + assert_eq!(committed_bytes() - before, SEGMENT_SLICE_SIZE); + assert!((*seg).purged_any, "the hole is not recorded on the segment"); + live_and_touch(p, 1, 1); + // Within what it has: nothing to do. + let before = committed_bytes(); + assert!(page_commit_to(p, SEGMENT_SLICE_SIZE)); + assert_eq!(committed_bytes(), before); + // One byte into the third slice: three slices. + assert!(page_commit_to(p, 2 * SEGMENT_SLICE_SIZE + 1)); + assert_eq!((*p).lazy_end as usize * LAZY_UNIT, 3 * SEGMENT_SLICE_SIZE); + assert_eq!(committed_bytes() - before, 2 * SEGMENT_SLICE_SIZE); + live_and_touch(p, 3, 2); + // A refusal changes nothing. + fail_next_commits(1); + assert!(!page_commit_to(p, n * SEGMENT_SLICE_SIZE)); + assert_eq!((*p).lazy_end as usize * LAZY_UNIT, 3 * SEGMENT_SLICE_SIZE); + // The next span starts past the uncommitted tail and is backed. + let before = committed_bytes(); + let (q, _) = span_alloc(seg, 2); + assert_eq!(page_index(seg, q), page_index(seg, p) + n); + assert!( + committed_bytes() - before <= (2 + COMMIT_STEP_MAX_SLICES) * SEGMENT_SLICE_SIZE, + "the bump committed the lazy span's tail with its own slices" + ); + live_and_touch(q, 2, 3); + // All of it. + assert!(page_commit_to(p, n * SEGMENT_SLICE_SIZE)); + assert_eq!((*p).lazy_end, 0, "a whole span still reads as short"); + live_and_touch(p, n, 4); + span_free(seg, p); + span_free(seg, q); + segment_free(seg).expect("free"); + } + } + + /// A small page carved lazily has a quarter of its slice, doubles as it + /// is asked for more, and leaves the next span its own commit. + #[test] + fn a_lazy_small_span_commits_a_unit_then_doubles() { + if !PAGE_LAZY_COMMIT { + return; + } + let _g = crate::arena::adopt_tests::lock(); + // SAFETY: a segment of our own exclusive arena, this thread only. + unsafe { + crate::options::set(15, -1); + let seg = segment_alloc(arena()).expect("segment"); + let before = committed_bytes(); + let (p, _) = span_alloc_lazy(seg, 1); + assert!(!p.is_null()); + assert_eq!((*p).lazy_end, 1, "a fresh lazy small span is one unit"); + assert_eq!(committed_bytes() - before, LAZY_UNIT); + assert!((*seg).purged_any, "the hole is not recorded on the segment"); + (*p).block_size = 64; + ptr::write_bytes((*p).area, 1, LAZY_UNIT); + // The next span is not this one's tail: it commits its own. + let (q, _) = span_alloc(seg, 2); + assert_eq!(page_index(seg, q), page_index(seg, p) + 1); + live_and_touch(q, 2, 2); + // One byte past the unit: doubled, not all. + let before = committed_bytes(); + assert!(page_commit_to(p, LAZY_UNIT + 1)); + assert_eq!((*p).lazy_end, 2); + assert_eq!(committed_bytes() - before, LAZY_UNIT); + ptr::write_bytes((*p).area, 3, 2 * LAZY_UNIT); + // A refusal changes nothing. + fail_next_commits(1); + assert!(!page_commit_to(p, 2 * LAZY_UNIT + 1)); + assert_eq!((*p).lazy_end, 2); + // One byte more: the rest of the slice. + assert!(page_commit_to(p, 2 * LAZY_UNIT + 1)); + assert_eq!((*p).lazy_end, 0, "a whole small span still reads as short"); + ptr::write_bytes((*p).area, 4, SEGMENT_SLICE_SIZE); + // Freed whole, it is a backed span; freed short, it is not, and + // taking it whole commits it. + span_free(seg, p); + let idx = page_index(seg, p); + assert!(!(*seg).pages[idx].purged); + let (p, _) = span_alloc(seg, 1); + assert_eq!(page_index(seg, p), idx); + live_and_touch(p, 1, 5); + span_free(seg, p); + span_free(seg, q); + // A lazy small span over slices already committed is whole. + let (r, _) = span_alloc_lazy(seg, 1); + assert_eq!((*r).lazy_end, 0, "a committed slice was taken as short"); + live_and_touch(r, 1, 6); + span_free(seg, r); + segment_free(seg).expect("free"); + } + } + + /// Through the heap: the first page of a small class commits as it + /// fills, every block is writable to its last byte, and the class's + /// later pages are whole from the start. + #[test] + #[cfg_attr(miri, ignore)] // megabytes of writes + fn a_small_class_fills_without_touching_unbacked_memory() { + use crate::alloc::{free, malloc}; + let _g = crate::arena::adopt_tests::lock(); + crate::options::set(15, -1); + // The largest small class, a middle one and a tiny one: sizes no + // other test on this thread has used. + for size in [crate::types::SMALL_OBJ_SIZE_MAX, 1_100, 48] { + // Three pages' worth. + let count = 3 * SEGMENT_SLICE_SIZE / size + 3; + let mut blocks = Vec::with_capacity(count); + for i in 0..count { + let p = malloc(size); + assert!(!p.is_null(), "size {size}: allocation {i} failed"); + // SAFETY: a live block of `size` bytes; its page is ours. + unsafe { + p.write_bytes(i as u8, size); + let pg = page_of(segment_of(p), p); + let backed = match (*pg).lazy_end { + 0 => (*pg).slice_count as usize * SEGMENT_SLICE_SIZE, + n => n as usize * LAZY_UNIT, + }; + assert!( + (*pg).capacity as usize * (*pg).block_size <= backed, + "size {size}: block {i}: carved past {backed} committed bytes" + ); + if i == 0 && (*pg).lazy_end != 0 { + assert!( + (*pg).capacity as usize * (*pg).block_size <= LAZY_UNIT, + "size {size}: the first trip carved past the first unit" + ); + } + } + blocks.push(p); + } + if PAGE_LAZY_COMMIT { + // SAFETY: live blocks; their page slots are this thread's. + let (first, last) = unsafe { + ( + (*page_of(segment_of(blocks[0]), blocks[0])).lazy_end, + (*page_of(segment_of(blocks[count - 1]), blocks[count - 1])).lazy_end, + ) + }; + assert_eq!(first, 0, "size {size}: a full page is still short"); + assert_eq!(last, 0, "size {size}: a later page of the class is lazy"); + } + for (i, p) in blocks.iter().enumerate() { + // SAFETY: live, `size` bytes, freed once. + unsafe { + assert_eq!(p.read(), i as u8, "size {size}: block {i} was overwritten"); + assert_eq!(p.add(size - 1).read(), i as u8); + free(*p); + } + } + } + } + + /// A large block is usable to the last byte of the size it reports, when + /// it is carved, when it comes back from the one-span cache for a larger + /// request of the same slice count, and when it grows in place. + #[test] + #[cfg_attr(miri, ignore)] // megabytes of writes + fn a_large_block_is_backed_to_its_reported_size() { + use crate::alloc::{free, malloc, realloc, usable_size}; + let _g = crate::arena::adopt_tests::lock(); + crate::options::set(15, 10_000); // keep the one-span cache in play + for size in [70_000usize, 200_001, (1 << 20) + 5, 3 * SEGMENT_SLICE_SIZE] { + if size > crate::types::LARGE_OBJ_SIZE_MAX { + continue; + } + let slices = size.div_ceil(SEGMENT_SLICE_SIZE); + let p = malloc(size); + assert!(!p.is_null()); + // SAFETY: live blocks, written within the size the allocator + // reports for them, freed once. + unsafe { + let u = usable_size(p); + assert!(u >= size && u <= slices * SEGMENT_SLICE_SIZE); + p.write_bytes(1, u); + if PAGE_LAZY_COMMIT && !size.is_multiple_of(SEGMENT_SLICE_SIZE) { + let pg = page_of(segment_of(p), p); + // Short only when carved fresh; a recycled span is whole. + if (*pg).lazy_end != 0 { + assert_eq!(u, crate::os::page_align_up(size)); + } + } + // The cache: a lone large free, then a request for the last + // byte of the same slice count. + free(p); + let bigger = slices * SEGMENT_SLICE_SIZE; + let q = malloc(bigger); + assert!(!q.is_null()); + assert!(usable_size(q) >= bigger); + q.write_bytes(2, usable_size(q)); + // Growing by one byte at a time never lands on unbacked + // memory, in place or moved. + let mut r = malloc(size); + assert!(!r.is_null()); + for extra in 1..=3 { + r = realloc(r, usable_size(r) + extra); + assert!(!r.is_null()); + r.write_bytes(3, usable_size(r)); + } + free(r); + free(q); + } + } + crate::options::set(15, -1); + } + + /// A free span of two slices is purged when its delay runs out; one slice + /// is not a candidate. + #[test] + fn a_two_slice_span_is_purged_and_one_slice_is_not() { + if !crate::OS_PAGES || USABLE_SLICES < 64 || MEDIUM_PAGE_SLICES <= 2 { + return; + } + let _g = crate::arena::adopt_tests::lock(); + // SAFETY: a segment of our own exclusive arena, this thread only. + unsafe { + crate::options::set(15, -1); + let seg = segment_alloc(arena()).expect("segment"); + let mut spans = [ptr::null_mut(); 5]; + for (i, n) in [1usize, 2, 1, 1, 1].into_iter().enumerate() { + let (p, _) = span_alloc(seg, n); + assert!(!p.is_null()); + live_and_touch(p, n, i as u8); + spans[i] = p; + } + let (two, one) = (page_index(seg, spans[1]), page_index(seg, spans[3])); + crate::options::set(15, 60_000); + assert_eq!(span_free(seg, spans[1]), 0); + assert_ne!((*seg).purge_expire, 0, "two slices started no deadline"); + assert_eq!(span_free(seg, spans[3]), 0); + assert_eq!( + purge_scheduled(seg, None), + 1, + "not exactly the two-slice span" + ); + assert!((*seg).pages[two].purged); + assert!(!(*seg).pages[one].purged, "a single slice was purged"); + crate::options::set(15, -1); + for i in [0, 2, 4] { + span_free(seg, spans[i]); + } + segment_free(seg).expect("free"); + } + } + + /// A page freed while short is a free span that must be re-committed and + /// can still be purged; taken again lazily it is short again, and taken + /// whole it is backed whole. + #[test] + fn a_short_page_freed_is_recommitted_before_reuse() { + if !PAGE_LAZY_COMMIT { + return; + } + let _g = crate::arena::adopt_tests::lock(); + let n = MEDIUM_PAGE_SLICES; + // SAFETY: a segment of our own exclusive arena, this thread only. + unsafe { + crate::options::set(15, -1); + let seg = segment_alloc(arena()).expect("segment"); + let (a, _) = span_alloc(seg, 1); + live_and_touch(a, 1, 1); + let (p, _) = span_alloc_lazy(seg, n); + let idx = page_index(seg, p); + live_and_touch(p, 1, 2); + let (b, _) = span_alloc(seg, 1); + live_and_touch(b, 1, 3); + assert_ne!((*p).lazy_end, 0); + span_free(seg, p); + let v = &raw mut (*seg).pages[idx]; + assert!( + (*v).purged && (*v).partly, + "a short span was freed as backed" + ); + assert_eq!((*v).lazy_end, 0); + // Lazily again: one slice, the rest for later. + let (p, _) = span_alloc_lazy(seg, n); + assert_eq!(page_index(seg, p), idx); + assert_eq!((*p).lazy_end as usize * LAZY_UNIT, SEGMENT_SLICE_SIZE); + assert!(!(*p).purged && !(*p).partly); + live_and_touch(p, 1, 4); + span_free(seg, p); + // Whole: every slice written. + let (p, _) = span_alloc(seg, n); + assert_eq!(page_index(seg, p), idx); + assert_eq!((*p).lazy_end, 0); + live_and_touch(p, n, 5); + span_free(seg, p); + assert!(!(*v).purged, "a fully backed span was freed as short"); + // A forced purge takes a short span too. + let (p, _) = span_alloc_lazy(seg, n); + live_and_touch(p, 1, 6); + crate::options::set(15, 60_000); + span_free(seg, p); + if crate::OS_PAGES { + assert_eq!(purge_scheduled(seg, None), 1); + assert!((*v).purged && !(*v).partly); + } + release(seg, [a, b]); + } + } + + /// Through the heap: a medium page commits as it fills, every block it + /// hands out is writable to its last byte, and a refused commit along the + /// way costs nothing but the page it was for. + #[test] + #[cfg_attr(miri, ignore)] // megabytes of writes + fn a_medium_page_fills_without_touching_unbacked_memory() { + use crate::alloc::{free, malloc}; + let _g = crate::arena::adopt_tests::lock(); + crate::options::set(15, -1); + // Every medium class boundary, and one in the middle. + for size in [ + crate::types::SMALL_OBJ_SIZE_MAX + 1, + 20_000, + 40_000, + crate::types::MEDIUM_OBJ_SIZE_MAX, + ] { + // Three pages' worth, so pages are carved, filled and left full. + let count = 3 * MEDIUM_PAGE_SLICES * SEGMENT_SLICE_SIZE / size + 3; + let mut blocks = Vec::with_capacity(count); + for i in 0..count { + if i == count / 2 { + fail_next_commits(1); + } + let p = malloc(size); + assert!(!p.is_null(), "size {size}: allocation {i} failed"); + // SAFETY: a live block of `size` bytes. + unsafe { p.write_bytes(i as u8, size) }; + blocks.push(p); + } + fail_next_commits(0); + if PAGE_LAZY_COMMIT { + // SAFETY: a live block; its page slot is this thread's. + let short = unsafe { (*page_of(segment_of(blocks[0]), blocks[0])).lazy_end }; + assert_eq!(short, 0, "size {size}: a full page is still short"); + } + for (i, p) in blocks.iter().enumerate() { + // SAFETY: live, `size` bytes, freed once below. + unsafe { + assert_eq!(p.read(), i as u8, "size {size}: block {i} was overwritten"); + assert_eq!(p.add(size - 1).read(), i as u8); + free(*p); + } + } + } + } + + /// A medium page never has blocks carved past what it has committed, and + /// its first trip carves no more than a slice. + #[test] + fn a_short_medium_page_carves_only_what_is_backed() { + use crate::alloc::{free, malloc}; + if !PAGE_LAZY_COMMIT { + return; + } + let _g = crate::arena::adopt_tests::lock(); + crate::options::set(15, -1); + let size = 23_000; + let mut blocks = Vec::new(); + for i in 0..12u8 { + let p = malloc(size); + assert!(!p.is_null()); + // SAFETY: a live block of `size` bytes; its page is this thread's. + unsafe { + p.write_bytes(i, size); + let pg = page_of(segment_of(p), p); + assert_eq!((*pg).slice_count as usize, MEDIUM_PAGE_SLICES); + let backed = match (*pg).lazy_end { + 0 => MEDIUM_PAGE_SLICES * SEGMENT_SLICE_SIZE, + n => n as usize * LAZY_UNIT, + }; + assert!( + (*pg).capacity as usize * size <= backed, + "block {i}: {} blocks carved over {backed} committed bytes", + (*pg).capacity + ); + if i == 0 && (*pg).lazy_end != 0 { + assert!( + (*pg).capacity as usize * size <= SEGMENT_SLICE_SIZE, + "the first trip carved past the first slice" + ); + } + } + blocks.push(p); + } + for p in blocks { + // SAFETY: live, freed once. + unsafe { free(p) }; + } + } + + /// The heap's look (`purge_aged`) takes a span that is only partly + /// backed, as the scheduled purge does, and spares a span younger than + /// the age it is asked for. + #[test] + #[cfg_attr(miri, ignore)] // ages a span by sleeping: the mock clock does not move + fn the_heaps_look_takes_a_partly_backed_span_and_spares_a_young_one() { + if !crate::OS_PAGES || USABLE_SLICES < 64 { + return; + } + let _g = crate::arena::adopt_tests::lock(); + // SAFETY: as documented on the helpers. + unsafe { + let (seg, idx, pins) = purged_between_pins(40); + crate::options::set(15, -1); + let (p, _) = span_alloc(seg, MEDIUM_PAGE_SLICES); + assert_eq!(page_index(seg, p), idx); + live_and_touch(p, MEDIUM_PAGE_SLICES, 8); + crate::options::set(15, 60_000); + assert_eq!(span_free(seg, p), 0); + let v = &raw mut (*seg).pages[idx]; + assert!( + (*v).purged && (*v).partly, + "setup: not a partly backed span" + ); + std::thread::sleep(std::time::Duration::from_millis(5)); + let now = crate::prim::clock_now(); + assert_eq!( + purge_aged(seg, now, 1_000), + 0, + "a span 5 ms old was taken as 1 s old" + ); + assert!((*v).partly); + assert_ne!( + (*seg).purge_expire, + 0, + "a candidate is left and the deadline is gone" + ); + assert_eq!( + purge_aged(seg, now, 1), + 1, + "a partly backed span was skipped" + ); + assert!((*v).purged && !(*v).partly); + assert_eq!( + (*seg).purge_expire, + 0, + "nothing is left and the deadline still runs" + ); + crate::options::set(15, -1); + let (q, _) = span_alloc(seg, 40); + assert_eq!(page_index(seg, q), idx); + live_and_touch(q, 40, 9); + span_free(seg, q); + release(seg, pins); + } + } + + /// A second exclusive arena of one chunk, for the tests that put a heap + /// of their own in it and destroy the heap when they are done. + fn heap_arena() -> i32 { + static ID: std::sync::OnceLock = std::sync::OnceLock::new(); + *ID.get_or_init(|| { + crate::arena::reserve_os_memory_ex(SEGMENT_SIZE, false, false, true) + .expect("reserve-only arena") + }) + } + + /// A span purged by a decommit is reported zero when it is taken, and + /// every byte of it is zero; its remainder keeps the state; a span that + /// merged a written neighbour, or was purged by a reset, is not zero. + #[test] + fn a_decommitted_span_is_reported_zero_and_is() { + if !DECOMMIT_ZEROES || USABLE_SLICES < 64 { + return; + } + let _g = crate::arena::adopt_tests::lock(); + // SAFETY: as documented on the helpers; spans are read within their + // committed extent. + unsafe { + let (seg, idx, pins) = purged_between_pins(8); + crate::options::set(15, -1); + assert!( + (*seg).pages[idx].free_is_zero, + "a decommitted span is not marked zero" + ); + let (p, fresh) = span_alloc(seg, 3); + assert_eq!(page_index(seg, p), idx); + assert!(fresh, "a decommitted span was reported recycled"); + for off in (0..3 * SEGMENT_SLICE_SIZE).step_by(509) { + assert_eq!( + (*p).area.add(off).read(), + 0, + "byte {off} of a zero span is not zero" + ); + } + let rest = &raw mut (*seg).pages[idx + 3]; + assert!((*rest).free_is_zero, "the remainder lost the zero state"); + live_and_touch(p, 3, 0x77); + // Take the zero remainder too and write it; then free the first + // span with an immediate decommit (zero again), and free the + // written one, which merges into it from the RIGHT: the merged + // span holds written memory and must not read as zero. + let (r2, fresh) = span_alloc(seg, 5); + assert_eq!(page_index(seg, r2), idx + 3); + assert!(fresh, "the zero remainder was reported recycled"); + live_and_touch(r2, 5, 0x66); + crate::options::set(15, 0); + assert_eq!(span_free(seg, p), 1); + crate::options::set(15, -1); + assert!( + (*seg).pages[idx].free_is_zero, + "setup: the left span is not zero" + ); + assert_eq!(span_free(seg, r2), 0); + assert_eq!( + (*seg).pages[idx].slice_count, + 8, + "setup: the spans did not merge" + ); + assert!( + !(*seg).pages[idx].free_is_zero, + "a written span came back zero" + ); + let (q, fresh) = span_alloc(seg, 8); + assert_eq!(page_index(seg, q), idx); + assert!(!fresh, "a span holding written memory was reported zero"); + live_and_touch(q, 8, 1); + // Purged by a reset (`purge_decommits` off): contents undefined. + crate::options::set(5, 0); + crate::options::set(15, 0); + assert_eq!(span_free(seg, q), 1); + assert!( + !(*seg).pages[idx].free_is_zero, + "a reset span was marked zero" + ); + crate::options::set(5, 1); + crate::options::set(15, -1); + let (r, fresh) = span_alloc(seg, 8); + assert!(!fresh, "a reset span was reported zero"); + live_and_touch(r, 8, 2); + span_free(seg, r); + release(seg, pins); + } + } + + /// A span carved as a large block of `bytes` bytes would be: short where + /// spans commit short, whole elsewhere, live, and filled with `fill`. + /// + /// # Safety + /// `seg` is a live segment this test owns. + unsafe fn large(seg: *mut Segment, bytes: usize, fill: u8) -> *mut Page { + let slices = bytes.div_ceil(SEGMENT_SLICE_SIZE); + // SAFETY: caller contract. + unsafe { + let (p, _) = span_alloc_first(seg, slices, crate::os::page_align_up(bytes)); + assert!(!p.is_null()); + (*p).block_size = if (*p).lazy_end != 0 { + crate::os::page_align_up(bytes) + } else { + slices * SEGMENT_SLICE_SIZE + }; + (*p).reserved = 1; + (*p).capacity = 1; + (*p).used = 1; + ptr::write_bytes((*p).area, fill, (*p).block_size); + p + } + } + + /// The first `n` bytes of `p`'s block are all `fill`, and all of the + /// block can be written. + /// + /// # Safety + /// `p` is a live span this test owns, backed for its `block_size`. + unsafe fn kept_and_writable(p: *mut Page, n: usize, fill: u8, refill: u8) { + // SAFETY: caller contract. + unsafe { + let a = (*p).area; + assert!((*p).block_size >= n); + for off in [0, n / 2, n - 1] { + assert_eq!(a.add(off).read(), fill, "byte {off} of the block was lost"); + } + ptr::write_bytes(a, refill, (*p).block_size); + } + } + + /// A large block followed by the cursor grows where it is: the same + /// page, more slices, its bytes kept, and the next span after it. + #[test] + fn a_large_block_grows_into_the_cursor() { + if USABLE_SLICES < 64 { + return; + } + let _g = crate::arena::adopt_tests::lock(); + // SAFETY: a segment of our own exclusive arena, this thread only. + unsafe { + crate::options::set(15, -1); + let seg = segment_alloc(arena()).expect("segment"); + let (a, _) = span_alloc(seg, 1); + live_and_touch(a, 1, 1); + let size = 3 * SEGMENT_SLICE_SIZE - 5_000; + let p = large(seg, size, 2); + let idx = page_index(seg, p); + let area = (*p).area; + let grown = 6 * SEGMENT_SLICE_SIZE + 9_000; + assert!( + span_grow(seg, p, grown), + "the cursor follows and it did not grow" + ); + assert_eq!((*p).area, area); + assert_eq!((*p).slice_count, 7); + assert_eq!((*seg).next_free_slice as usize, idx + 7); + assert!((*p).block_size >= grown); + assert_eq!( + slice_owner(seg, idx + 6), + p, + "a grown slice does not name its page" + ); + kept_and_writable(p, size, 2, 3); + // The span carved next starts after the grown one, and is backed. + let (b, _) = span_alloc(seg, 2); + assert_eq!(page_index(seg, b), idx + 7); + live_and_touch(b, 2, 4); + // Now a live span follows: no room, nothing changed. + let before = ((*p).slice_count, (*p).block_size); + assert!(!span_grow(seg, p, 9 * SEGMENT_SLICE_SIZE)); + assert_eq!(((*p).slice_count, (*p).block_size), before); + kept_and_writable(p, grown, 3, 5); + span_free(seg, b); + span_free(seg, p); + span_free(seg, a); + segment_free(seg).expect("free"); + } + } + + /// A refused commit is a block that did not grow, and is as it was. + #[test] + fn a_refused_commit_leaves_a_growing_block_as_it_was() { + if !LAZY_COMMIT || USABLE_SLICES < 64 { + return; + } + let _g = crate::arena::adopt_tests::lock(); + // SAFETY: a segment of our own exclusive arena, this thread only. + unsafe { + crate::options::set(15, -1); + let seg = segment_alloc(arena()).expect("segment"); + let size = 3 * SEGMENT_SLICE_SIZE - 5_000; + let p = large(seg, size, 2); + let before = ((*p).slice_count, (*p).block_size, (*seg).next_free_slice); + fail_next_commits(1); + assert!( + !span_grow(seg, p, 40 * SEGMENT_SLICE_SIZE), + "grew over a refused commit" + ); + fail_next_commits(0); + assert_eq!( + ((*p).slice_count, (*p).block_size, (*seg).next_free_slice), + before + ); + kept_and_writable(p, size, 2, 3); + assert!(span_grow(seg, p, 40 * SEGMENT_SLICE_SIZE)); + kept_and_writable(p, size, 3, 4); + span_free(seg, p); + segment_free(seg).expect("free"); + } + } + + /// A large block followed by a free span grows into it: a backed one is + /// taken as it is, a purged one is committed for what is taken, and what + /// is left stays a free span in the state it was in. + #[test] + fn a_large_block_grows_into_a_free_span() { + if !LAZY_COMMIT || USABLE_SLICES < 64 { + return; + } + let _g = crate::arena::adopt_tests::lock(); + for purged in [false, true] { + // SAFETY: a segment of our own exclusive arena, this thread only. + unsafe { + crate::options::set(15, -1); + let seg = segment_alloc(arena()).expect("segment"); + let size = 3 * SEGMENT_SLICE_SIZE; + let p = large(seg, size, 2); + let idx = page_index(seg, p); + let (x, _) = span_alloc(seg, 10); + live_and_touch(x, 10, 9); + let (pin, _) = span_alloc(seg, 1); + live_and_touch(pin, 1, 9); + crate::options::set(15, if purged { 0 } else { -1 }); + assert_eq!(span_free(seg, x), usize::from(purged)); + crate::options::set(15, -1); + // More than it and the block together hold: no growth, and + // the free span is as it was. + assert!( + !span_grow(seg, p, 14 * SEGMENT_SLICE_SIZE), + "grew into a free span too short for it" + ); + assert_eq!((*p).slice_count, 3); + let free = &raw mut (*seg).pages[idx + 3]; + assert_eq!(((*free).block_size, (*free).slice_count), (0, 10)); + // Into part of it. + let before = committed_bytes(); + let grown = 5 * SEGMENT_SLICE_SIZE + 100; + assert!( + span_grow(seg, p, grown), + "a free span follows and it did not grow" + ); + assert_eq!((*p).slice_count, 6); + let got = committed_bytes() - before; + if purged { + assert!( + got >= grown - size && got <= 3 * SEGMENT_SLICE_SIZE, + "committed {got} bytes to take three slices of a purged span" + ); + } else { + assert_eq!(got, 0, "a backed neighbour was committed again"); + } + let rest = &raw mut (*seg).pages[idx + 6]; + assert_eq!((*rest).block_size, 0, "the remainder is not a free span"); + assert_eq!((*rest).slice_count, 7); + assert_eq!((*rest).purged, purged, "the remainder changed state"); + assert_eq!(slice_owner(seg, idx + 5), p); + kept_and_writable(p, size, 2, 3); + // Into all of the rest: no remainder, and the pin is next. + assert!(span_grow(seg, p, 13 * SEGMENT_SLICE_SIZE)); + assert_eq!((*p).slice_count, 13); + assert_eq!(page_index(seg, pin), idx + 13); + kept_and_writable(p, grown, 3, 4); + // And no further. + assert!(!span_grow(seg, p, 14 * SEGMENT_SLICE_SIZE)); + kept_and_writable(p, 13 * SEGMENT_SLICE_SIZE, 4, 5); + span_free(seg, p); + span_free(seg, pin); + segment_free(seg).expect("free"); + } + } + } + + /// A block carved short grows inside its own last slice by committing + /// more of it. + #[test] + fn a_short_large_block_grows_inside_its_last_slice() { + if !PAGE_LAZY_COMMIT { + return; + } + let _g = crate::arena::adopt_tests::lock(); + // SAFETY: a segment of our own exclusive arena, this thread only. + unsafe { + crate::options::set(15, -1); + let seg = segment_alloc(arena()).expect("segment"); + let p = large(seg, 70_000, 2); + assert_ne!((*p).lazy_end, 0, "setup: the block is not short"); + let (pin, _) = span_alloc(seg, 1); + live_and_touch(pin, 1, 9); + let before = committed_bytes(); + assert!(span_grow(seg, p, 100_000)); + assert_eq!((*p).slice_count, 2); + assert_eq!((*p).block_size, crate::os::page_align_up(100_000)); + assert_eq!( + committed_bytes() - before, + crate::os::page_align_up(100_000) - crate::os::page_align_up(70_000) + ); + assert_ne!((*p).lazy_end, 0); + kept_and_writable(p, 70_000, 2, 3); + assert!(span_grow(seg, p, 2 * SEGMENT_SLICE_SIZE)); + assert_eq!((*p).lazy_end, 0, "a whole span still reads as short"); + kept_and_writable(p, 100_000, 3, 4); + assert!( + !span_grow(seg, p, 2 * SEGMENT_SLICE_SIZE + 1), + "grew into a live span" + ); + span_free(seg, p); + span_free(seg, pin); + segment_free(seg).expect("free"); + } + } + + /// Through `realloc`: a large block at the cursor of its heap's segment + /// keeps its address as it grows, and every byte. + #[test] + #[cfg_attr(miri, ignore)] // megabytes of writes + fn realloc_grows_a_large_block_where_it_is() { + use crate::alloc::{heap_malloc, realloc, usable_size}; + if USABLE_SLICES < 64 { + return; + } + let _g = crate::arena::adopt_tests::lock(); + crate::options::set(15, -1); + // A heap of its own in an arena of its own: its first large block is + // carved at the cursor of a fresh segment. + let h = crate::init::create_heap(0, true, heap_arena()); + // SAFETY: the heap is this thread's; blocks are written within their + // sizes and die with the heap. + unsafe { + let mut size = 100_000; + let p = heap_malloc(h, size); + assert!(!p.is_null()); + p.write_bytes(7, size); + let mut q = p; + for round in 0..6u8 { + let bigger = size * 2 + 123; + q = realloc(q, bigger); + assert_eq!(q, p, "round {round}: a block at the cursor moved to grow"); + assert!(usable_size(q) >= bigger); + assert_eq!(q.read(), 7 + round); + assert_eq!(q.add(size - 1).read(), 7 + round); + q.write_bytes(8 + round, bigger); + size = bigger; + } + crate::init::heap_destroy(h); + } + } + + /// Only the thread that owns a block's segment may reshape its span: a + /// `realloc` from another thread moves the block, as it always did. + #[test] + #[cfg_attr(miri, ignore)] // megabytes of writes, and a second thread + fn realloc_from_another_thread_moves_a_large_block() { + use crate::alloc::{free, heap_malloc, realloc}; + if USABLE_SLICES < 64 { + return; + } + let _g = crate::arena::adopt_tests::lock(); + crate::options::set(15, -1); + let h = crate::init::create_heap(0, true, heap_arena()); + let size = 100_000; + // SAFETY: the heap is this thread's; the block is live until the + // other thread's `realloc` takes it over, and that thread frees what + // it gets back. + unsafe { + let p = heap_malloc(h, size); + assert!(!p.is_null()); + p.write_bytes(7, size); + let addr = p.addr(); + let moved = std::thread::spawn(move || { + let p = core::ptr::with_exposed_provenance_mut::(addr); + let q = realloc(p, 3 * size); + assert!(!q.is_null()); + assert_eq!(q.read(), 7); + assert_eq!(q.add(size - 1).read(), 7); + let moved = q.addr() != addr; + free(q); + moved + }) + .join() + .expect("the other thread"); + let _ = p.expose_provenance(); + assert!( + moved, + "another thread grew a block in a segment it does not own" + ); + crate::init::heap_destroy(h); + } + } + + /// Two large blocks freed in a row, so the second is not kept as the + /// one-span cache and its span is retired and scheduled. + fn retire_a_large_span(size: usize) { + use crate::alloc::{free, malloc}; + let a = malloc(size); + let b = malloc(size); + assert!(!a.is_null() && !b.is_null()); + // SAFETY: live blocks of `size` bytes, freed once. + unsafe { + a.write_bytes(1, size); + b.write_bytes(2, size); + free(a); + free(b); + } + } + + /// A heap that freed large spans and went on to other work gives them + /// back when it carves a span, once it has seen them free for a whole + /// delay. Before, that took another large free in the same segment or + /// 10,000 generic trips. + #[test] + #[cfg_attr(miri, ignore)] // megabytes of writes, and sleeps + fn a_heap_purges_what_it_has_seen_free_for_a_delay() { + use crate::alloc::{free, malloc, stats}; + if !crate::OS_PAGES { + return; + } + let _g = crate::arena::adopt_tests::lock(); + let size = 24 * SEGMENT_SLICE_SIZE; + if size > crate::types::LARGE_OBJ_SIZE_MAX { + return; + } + crate::options::set(15, 1); + retire_a_large_span(size); + let before = stats().purges; + std::thread::sleep(std::time::Duration::from_millis(20)); + // A fresh page of a class this thread has not touched: one span + // carve, no large free, no collect. The heap sees the span free. + let p = malloc(3_333); + assert!(!p.is_null()); + assert_eq!( + stats().purges, + before, + "purged at first sight: a span freed before a pause is the one a loop takes back" + ); + std::thread::sleep(std::time::Duration::from_millis(20)); + // Another class, another carve: free then, free now, a delay apart. + let q = malloc(5_555); + assert!(!q.is_null()); + assert!( + stats().purges > before, + "a span left free across two looks a delay apart was not purged" + ); + crate::options::set(15, -1); + // SAFETY: live, freed once. + unsafe { + free(p); + free(q); + } + } + + /// The loop the observation rule exists for: free, pause longer than the + /// delay, take the same memory back. Nothing is purged, so nothing is + /// refaulted, however many rounds it runs. + #[test] + #[cfg_attr(miri, ignore)] // megabytes of writes, and sleeps + fn a_loop_that_pauses_and_reuses_purges_nothing() { + use crate::alloc::{free, malloc, stats}; + if !crate::OS_PAGES { + return; + } + let _g = crate::arena::adopt_tests::lock(); + let size = 24 * SEGMENT_SLICE_SIZE; + if size > crate::types::LARGE_OBJ_SIZE_MAX { + return; + } + crate::options::set(15, 2); + let pin = malloc(64); + // The first round carves; the rest reuse what it freed. + retire_a_large_span(size); + let before = stats().purges; + for round in 0..8 { + std::thread::sleep(std::time::Duration::from_millis(12)); + retire_a_large_span(size); + assert_eq!( + stats().purges, + before, + "round {round}: memory about to be reused was purged" + ); + } + crate::options::set(15, -1); + // SAFETY: live, freed once. + unsafe { free(pin) }; + } +} diff --git a/crates/rusty_alloc/tests/abandon_purge.rs b/crates/rusty_alloc/tests/abandon_purge.rs new file mode 100644 index 0000000..0b08ac2 --- /dev/null +++ b/crates/rusty_alloc/tests/abandon_purge.rs @@ -0,0 +1,79 @@ +//! A dying thread's segment that still holds a live block is abandoned with +//! its free spans purged (`abandoned_page_purge`, documented as always on). +//! +//! From 0.3.0 until 2.6.1 the purge was gated on the wrong option index +//! (`guarded_min`), so it never ran by default; the spans were purged instead +//! by a forced pass in the teardown collect, which scheduled and purged them +//! one by one. That pass is gone (`Heap::collect_for_thread_exit`), so this +//! test is what keeps an abandoned segment from holding its pages. + +use rusty_alloc::alloc::{free, malloc}; +use rusty_alloc::{init, segment}; + +#[test] +#[cfg_attr(miri, ignore = "the miri mock's thread-exit destructors never fire")] +fn an_abandoned_segment_has_its_free_spans_purged() { + use rusty_alloc::types::{ + LARGE_OBJ_SIZE_MAX, MEDIUM_OBJ_SIZE_MAX, SEGMENT_SLICE_SIZE, SLICES_PER_SEGMENT, + }; + if !cfg!(any(unix, windows)) { + return; + } + // Large blocks (a span each), three of them and the small block's page + // in ONE segment; a geometry whose segments cannot hold that (the small + // profiles) has nothing to show here. + let big = (MEDIUM_OBJ_SIZE_MAX + 1).max(2 * SEGMENT_SLICE_SIZE); + if big > LARGE_OBJ_SIZE_MAX || 3 * big.div_ceil(SEGMENT_SLICE_SIZE) + 2 > SLICES_PER_SEGMENT { + return; + } + // No delayed purge, so no span is purged on the way: what is purged at + // the end was purged by the abandon, which ignores `purge_delay`. + rusty_alloc::options::set(15, -1); + // A subprocess of its own: only threads in it pop its abandoned list, so + // nothing else in this process can adopt the segment before we look. + let sp = init::subproc_new(); + assert!(sp < 64, "no subprocess id left"); + let keep = std::thread::spawn(move || { + init::subproc_add_current_thread(sp); + let keep = malloc(100); + assert!(!keep.is_null()); + // Three large blocks freed in a row: spans that coalesce into a free + // span of the thread's segment. + let blocks: Vec<*mut u8> = (0..3).map(|_| malloc(big)).collect(); + for &p in &blocks { + assert!(!p.is_null()); + // SAFETY: a live block of `big` bytes, written and freed once. + unsafe { + p.write_bytes(0x5A, big); + free(p); + } + } + keep.expose_provenance() + }) + .join() + .expect("the worker"); + let keep = core::ptr::with_exposed_provenance_mut::(keep); + let seg = segment::segment_of(keep); + // SAFETY: `keep` is live, so its segment is mapped; it is abandoned in a + // subprocess no running thread belongs to, so nothing mutates it. + unsafe { + assert_eq!( + (*seg).thread_id.load(core::sync::atomic::Ordering::Acquire), + 0, + "setup: the segment was not abandoned" + ); + let mut spans = 0; + let mut s = (*seg).free_spans; + while !s.is_null() { + spans += 1; + assert!( + (*s).purged && !(*s).partly, + "an abandoned segment kept a free span of {} slices resident", + (*s).slice_count + ); + s = (*s).next; + } + assert!(spans > 0, "setup: the segment has no free span"); + free(keep); + } +} diff --git a/crates/rusty_alloc/tests/alloc_core.rs b/crates/rusty_alloc/tests/alloc_core.rs index f4b4645..8b62b70 100644 --- a/crates/rusty_alloc/tests/alloc_core.rs +++ b/crates/rusty_alloc/tests/alloc_core.rs @@ -469,3 +469,79 @@ fn realloc_storm() { } } } + +/// Every copy length a moving `realloc` makes in line (up to 128 bytes, the +/// leaf's ladder and its 65..=128 arm) and the first lengths past it keep +/// every byte, growing and shrinking, with a pattern that differs per byte so +/// a copy that overlaps wrongly or stops short is seen. +#[test] +fn realloc_keeps_every_byte_for_every_short_copy_length() { + for len in 1..=160usize { + // SAFETY: each block is written within the size it was allocated + // with, read within the size realloc kept, and freed once. + unsafe { + let p = malloc(len); + assert!(!p.is_null()); + for i in 0..len { + p.add(i) + .write((i as u8).wrapping_mul(31).wrapping_add(len as u8)); + } + // Growth: the whole old block is the copy. + let q = realloc(p, 2 * len + 200); + assert!(!q.is_null()); + for i in 0..len { + assert_eq!( + q.add(i).read(), + (i as u8).wrapping_mul(31).wrapping_add(len as u8), + "grow from {len}: byte {i}" + ); + } + // Shrink below half: the new size is the copy. + let keep = len.div_ceil(4); + let r = realloc(q, keep); + assert!(!r.is_null()); + for i in 0..keep { + assert_eq!( + r.add(i).read(), + (i as u8).wrapping_mul(31).wrapping_add(len as u8), + "shrink from {len} to {keep}: byte {i}" + ); + } + free(r); + } + } +} + +/// The same through a first-class heap's realloc (`heap_realloc_fast`, the +/// route `Vec::new_in(&heap)` grows through), which has a leaf of its own. +#[test] +fn heap_realloc_keeps_every_byte_for_every_short_copy_length() { + let h = rusty_alloc::init::create_heap(0, true, -1); + for len in 1..=160usize { + // SAFETY: the heap is this thread's; blocks are written and read + // within their sizes and die with the heap. + unsafe { + let p = rusty_alloc::alloc::heap_malloc(h, len); + assert!(!p.is_null()); + for i in 0..len { + p.add(i) + .write((i as u8).wrapping_mul(37).wrapping_add(len as u8)); + } + let q = rusty_alloc::alloc::heap_realloc_fast( + h, + core::ptr::NonNull::new(p).expect("live"), + 2 * len + 200, + ); + assert!(!q.is_null()); + for i in 0..len { + assert_eq!( + q.add(i).read(), + (i as u8).wrapping_mul(37).wrapping_add(len as u8), + "heap grow from {len}: byte {i}" + ); + } + } + } + // SAFETY: nothing of the heap is used after this. + unsafe { rusty_alloc::init::heap_destroy(h) }; +} diff --git a/crates/rusty_alloc/tests/heaps.rs b/crates/rusty_alloc/tests/heaps.rs index 8a4dab3..3bfb36a 100644 --- a/crates/rusty_alloc/tests/heaps.rs +++ b/crates/rusty_alloc/tests/heaps.rs @@ -37,6 +37,47 @@ fn heaps_arenas_subprocs_options() { }); assert!(ok); assert_eq!(seen, 400, "visitor missed blocks"); + // A huge block is visited where it is. Its reservation is whole + // 32 MiB chunks, so a 33 MiB block ends 31 MiB short of it, and the + // visitor used to derive the start from the reservation's end. + let refused = rusty_alloc::stats::commit_failures(); + let huge_size = 33 << 20; + let huge = hmalloc(h1, huge_size); + assert!(!huge.is_null()); + // First and last byte: the block is backed to its end. + huge.write(0x11); + huge.add(huge_size - 1).write(0x22); + let mut huge_seen = false; + let ok = (*(*h1).heap.get()).visit_blocks(true, &mut |_area, block, sz| { + if sz >= huge_size { + assert_eq!(block, huge, "a huge block was visited somewhere else"); + huge_seen = true; + } + true + }); + assert!(ok && huge_seen, "the visitor missed the huge block"); + assert_eq!(huge.read(), 0x11); + assert_eq!(huge.add(huge_size - 1).read(), 0x22); + alloc::free(huge); + // The chunks go back usable: the next huge block is written whole. + let again = hmalloc(h1, 60 << 20); + assert!(!again.is_null()); + core::ptr::write_bytes(again, 0x33, 60 << 20); + alloc::free(again); + // That block took the chunks committed whole and gave back the tail + // past its end. The tail is committed again when it is freed: a + // longer block in the same chunks is written to its last byte. + let longer = hmalloc(h1, 62 << 20); + assert!(!longer.is_null()); + core::ptr::write_bytes(longer, 0x44, 62 << 20); + alloc::free(longer); + // And none of those frees had to retire its chunks: a tail restored + // short leaves the range unusable, which the free notices and counts. + assert_eq!( + rusty_alloc::stats::commit_failures(), + refused, + "a freed huge block's chunks could not be made whole again" + ); // contains/check_owned let (probe, _) = blocks[200]; assert!(alloc::heap_contains_block(h1, probe)); diff --git a/crates/rusty_alloc/tests/queue_live.rs b/crates/rusty_alloc/tests/queue_live.rs new file mode 100644 index 0000000..1a4b5ac --- /dev/null +++ b/crates/rusty_alloc/tests/queue_live.rs @@ -0,0 +1,75 @@ +//! `Heap::queues_live`: a collect sweeps only the bin queues marked as +//! possibly holding a page. A queue that holds a page while unmarked is +//! skipped, so a dead page in it is never retired. This drives the one +//! marking site the rest of the suite does not reach: a FULL page returning +//! to a bin queue that a collect has already emptied and unmarked. +//! +//! Own test binary: the assertions read this thread's heap counters, and +//! this thread must be the only user of the size class. +//! +//! Not under `secure`: page detection below relies on a fresh page handing +//! out its blocks in address order, which the secure build randomizes. +#![cfg(not(feature = "secure"))] + +use rusty_alloc::alloc::{collect, free, malloc, stats, usable_size}; + +/// A size class nothing else in this process allocates, small enough that a +/// page holds several blocks: three quarters of the largest small object, an +/// eighth of a small page, so about ten blocks to a page in every geometry +/// (6,144 by default). It was a fixed 6,000, which the small profiles round +/// to a block that is a page of its own: each free then retired its page on +/// the spot and the FULL page this test needs never formed. +const SIZE: usize = rusty_alloc::types::SMALL_OBJ_SIZE_MAX * 3 / 4; + +#[test] +fn a_full_page_returning_to_an_emptied_queue_is_still_collected() { + // Fill page A: allocate until a block is not contiguous with the one + // before it. That block is on page B, and finding A full on the way + // parked A in the FULL queue. + let first = malloc(SIZE); + assert!(!first.is_null()); + // SAFETY: live block. + let bsize = unsafe { usable_size(first) }; + let mut page_a = vec![first]; + let on_b = loop { + let p = malloc(SIZE); + assert!(!p.is_null()); + let prev = *page_a.last().unwrap(); + if p as usize != prev as usize + bsize { + break p; + } + page_a.push(p); + assert!(page_a.len() < 4096, "no page boundary found"); + }; + assert!( + page_a.len() > 1, + "page A held a single block; pick a smaller SIZE" + ); + + // Empty the bin queue: B's only block freed (B stays queued as its bin's + // only page), then a collect retires B and leaves the queue empty, so the + // sweep unmarks it. + // SAFETY: each block is live and freed exactly once. + unsafe { free(on_b) }; + let before_b = stats().pages_retired; + collect(false); + assert!( + stats().pages_retired > before_b, + "the collect did not retire the all-free page B" + ); + + // A's first free moves A from FULL back into the EMPTY bin queue. The rest + // leave A all-free and its bin's only page, so the free path keeps it. + for &p in &page_a { + // SAFETY: live, freed exactly once. + unsafe { free(p) }; + } + let before_a = stats().pages_retired; + // The sweep must visit A's queue. Unmarked, it is skipped: A is never + // retired (and a debug build's invariant check fires first). + collect(false); + assert!( + stats().pages_retired > before_a, + "a page that returned from FULL to an emptied queue was not collected" + ); +} diff --git a/crates/rusty_alloc_api/CHANGELOG.md b/crates/rusty_alloc_api/CHANGELOG.md index d58db00..0b4e8c4 100644 --- a/crates/rusty_alloc_api/CHANGELOG.md +++ b/crates/rusty_alloc_api/CHANGELOG.md @@ -7,6 +7,23 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +## [2.7.0](https://github.com/Remade-With-Rust/rusty_alloc/compare/rusty_alloc-api-v2.6.0...rusty_alloc-api-v2.7.0) - 2026-12-02 + +### Changed + +- **`Allocator` methods run without the abort-on-unwind guard where the + build is proven unable to panic** (`rusty_alloc::NO_UNWIND_PROVEN`: x86-64 + Linux, no debug assertions, `opt-level` 2 or 3, default features). The + core now has no panic reachable from an allocation in that shape, counted + in the machine code under fat LTO and under Cargo's default release + profile. `Vec::new_in(RustyAlloc)` costs 27.6 fewer instructions a step + (−1.09 %), about 1 % below the same work through `#[global_allocator]`, + and a collection in a `Heap` 28.5 fewer (−1.13 %). Everywhere else the + guard stays, so an unwind still aborts. +- Requires `rusty_alloc` 2.7.0, which also brings the Windows commit + reductions, in-place growth of large blocks and cheaper thread start-up + listed in its changelog. + ## [2.6.0](https://github.com/Remade-With-Rust/rusty_alloc/compare/rusty_alloc-api-v2.5.0...rusty_alloc-api-v2.6.0) - 2026-11-13 ### Added diff --git a/crates/rusty_alloc_api/Cargo.toml b/crates/rusty_alloc_api/Cargo.toml index b886e63..6f589e9 100644 --- a/crates/rusty_alloc_api/Cargo.toml +++ b/crates/rusty_alloc_api/Cargo.toml @@ -16,7 +16,7 @@ readme = "README.md" [dependencies] # A published crate needs a VERSION alongside the path: the path is what the # workspace builds against, the version is what crates.io resolves. -rusty_alloc = { path = "../rusty_alloc", version = "2.6.0", default-features = false } +rusty_alloc = { path = "../rusty_alloc", version = "2.7.0", default-features = false } [features] # Mirrors the core's (P3, docs/plans/small-metal.md). Default-on, so every diff --git a/crates/rusty_alloc_api/README.md b/crates/rusty_alloc_api/README.md index de58d1d..28d3c6c 100644 --- a/crates/rusty_alloc_api/README.md +++ b/crates/rusty_alloc_api/README.md @@ -1,19 +1,19 @@ # rusty_alloc-api The safe Rust surface over [`rusty_alloc`](https://crates.io/crates/rusty_alloc), -a pure-Rust remake of mimalloc that measures at-or-below mimalloc on -instructions retired for real programs (lua 0.96x, perl 0.99x, sqlite 0.995x) and -below jemalloc across the board (lua 0.83x, perl 0.89x, sqlite 0.98x), while -detecting double frees that upstream silently accepts and carrying no data race -on its free path. +a pure-Rust remake of mimalloc that measures at or below mimalloc on +instructions retired for real programs (lua 0.96×, perl 0.99×, sqlite 0.995×) +and below jemalloc across the board (lua 0.83×, perl 0.89×, sqlite 0.98×), +while detecting double frees that upstream silently accepts and carrying no +data race on its free path. -**Status: `1.0.0` — the API is frozen.** See the +**Current release: `2.7.0`.** The API is stable and follows semver. See the [`rusty_alloc`](https://crates.io/crates/rusty_alloc) crate page for the performance evidence and its scope (instruction counts, not wall-clock). -> **Upgrade from 0.3.x or earlier — mandatory.** 0.4.0 fixed three -> platform-independent use-after-frees; treat 0.3.2 and earlier as unsound on -> every target. +> **Upgrade from 2.5.0 or earlier.** 2.6.0 fixed two soundness bugs: a +> destroyable heap could unmap a dead thread's live blocks, and `Heap::alloc` +> could return misaligned blocks on 32-bit targets. ## What it gives you @@ -61,6 +61,14 @@ have not been stabilised with one yet. A collection in a heap stays on the heap's thread (`Vec` is not `Send`), and it is a different type from a plain `Vec`. +Both trait routes cost less than the global one. On a `Vec`-growth workload +(whole-program instructions per 20,000 steps, Rust 1.100), the same work +measures 50,365,884 through `#[global_allocator]`, **49,856,136** through +`Vec::new_in(RustyAlloc)` and **49,687,570** in a `Heap`. On x86-64 Linux +release builds, where no panic is reachable from an allocation, the trait +methods run without an abort-on-unwind guard; everywhere else the guard keeps +the trait's no-unwind contract. + ## Features `debug_checks`, `secure`, `profile` — each forwards to the identically-named diff --git a/crates/rusty_alloc_api/src/allocator.rs b/crates/rusty_alloc_api/src/allocator.rs index 0548091..04a2a44 100644 --- a/crates/rusty_alloc_api/src/allocator.rs +++ b/crates/rusty_alloc_api/src/allocator.rs @@ -66,13 +66,18 @@ //! paths these methods reach (`tools/no-unwind-scan.sh` counts them from //! the machine code and holds the count to a baseline). None can fire //! while the allocator's state is intact, but "cannot fire" is not what -//! the contract asks, so every method runs under a guard that turns an -//! unwind into an abort, in every build. Measured, callgrind, the -//! collection work of `bench/rust-globalalloc/src/alloc_work.rs`: the guard -//! costs 27.6 instructions per step on `Vec::new_in(RustyAlloc)` (2,507.89 -//! to 2,535.48, where the same work through `#[global_allocator]` is -//! 2,533.37) and 6.7 inside a `Heap`: a call that was a jump before. It -//! goes when the scan reads zero. +//! the contract asks, so a method runs under a guard that turns an unwind +//! into an abort, except in the one build shape the scan proves has no +//! panic left to guard: x86-64 Linux, release, the default features +//! (`rusty_alloc::NO_UNWIND_PROVEN`). There the count is zero under fat LTO +//! and under Cargo's default release profile, CI holds it there, and the +//! methods run bare. Measured, callgrind, the collection work of +//! `bench/rust-globalalloc/src/alloc_work.rs`: the guard costs 27.6 +//! instructions per step on `Vec::new_in(RustyAlloc)` (2,507.89 to +//! 2,535.48, where the same work through `#[global_allocator]` is +//! 2,533.37) and 6.7 inside a `Heap`: a call that was a jump before. +//! Everywhere else (debug builds, where a `debug_assert!` can fire, other +//! targets, other features) the guard stays. //! * **`grow` and `shrink` may change the alignment**, which //! `GlobalAlloc::realloc` cannot: an equal alignment goes to the in-place //! reallocation, a different one is an allocate, copy and free. @@ -102,9 +107,20 @@ impl Drop for AbortOnUnwind { /// bounds check on one of the allocator's own tables (see the module docs). /// Either firing is a bug in the allocator or its state already destroyed, /// and it must stop the process, not unwind through a half-updated `Vec`. -/// With `panic = "abort"` nothing unwinds and this is the body alone. +/// With `panic = "abort"` nothing unwinds and this is the body alone, and so +/// it is where `rusty_alloc::NO_UNWIND_PROVEN` says the scan found nothing +/// that could panic. #[inline(always)] fn no_unwind(body: impl FnOnce() -> R) -> R { + if rusty_alloc::NO_UNWIND_PROVEN { + return body(); + } + guarded(body) +} + +/// `body` under the guard, in every build. +#[inline(always)] +fn guarded(body: impl FnOnce() -> R) -> R { let guard = AbortOnUnwind; let out = body(); core::mem::forget(guard); @@ -466,7 +482,7 @@ unsafe impl Allocator for Heap { #[cfg(test)] mod tests { - use super::no_unwind; + use super::guarded; /// A panic inside a guarded body ends the process; it does not unwind to /// the caller. Run in a child, since the point is that it does not return. @@ -475,7 +491,7 @@ mod tests { fn an_unwind_out_of_a_method_aborts() { const CHILD: &str = "RA_NO_UNWIND_CHILD"; if std::env::var_os(CHILD).is_some() { - no_unwind(|| panic!("deliberate: the guard must abort on this")); + guarded(|| panic!("deliberate: the guard must abort on this")); } let exe = std::env::current_exe().expect("the test binary's own path"); let out = std::process::Command::new(exe) @@ -497,4 +513,8 @@ mod tests { "the panic unwound to the harness instead of aborting" ); } + + /// A debug build keeps the guard: there a `debug_assert!` can panic, and + /// the scan proves only release builds. Checked when the tests compile. + const _: () = assert!(!(cfg!(debug_assertions) && rusty_alloc::NO_UNWIND_PROVEN)); } diff --git a/deny.toml b/deny.toml index 8251fc9..b1a1f31 100644 --- a/deny.toml +++ b/deny.toml @@ -10,7 +10,15 @@ all-features = true # until triaged; ignores must carry a dated reason here. version = 2 yanked = "deny" -ignore = [] +ignore = [ + # 2026-12-03: upstream yanked every pin-project-lite 0.2.x before 0.2.19 + # (published 2026-12-02), which `global-min-publish-age = "3 days"` in + # .cargo/config.toml refuses until 2026-12-05. It reaches the graph only + # through loom -> tracing, a dev-dependency, so no shipped artifact links + # it. Remove this entry and `cargo update -p pin-project-lite` once 0.2.19 + # is three days old. + { crate = "pin-project-lite@0.2.17", reason = "yanked; dev-only via loom; 0.2.19 under the 3-day publish-age floor until 2026-12-05" }, +] [licenses] version = 2 diff --git a/docs/opps.md b/docs/opps.md index 6a294a4..c3b2e1f 100644 --- a/docs/opps.md +++ b/docs/opps.md @@ -883,6 +883,126 @@ the global one does. Elsewhere `heap_realloc_fast` is the old `heap_realloc`, so Windows and macOS get the allocate and free halves and not the realloc half. +## Optimization round, 2026-12-02 (five veins, two wins each) + +On top of the issue 63 work (`docs/plans/windows-commit-footprint.md`), before +release. Method as before, with three instruments added in +`bench/issue63/`: `mine.sh` (paired trees in one invocation: opscan Ir/op by +the two-point estimator, allocator-object self Ir on perl, sqlite, lua and +python with an output hash as the work anchor, and `thr`, a C program that +starts and joins short threads, in Ir per thread), `mine-rs.sh` (the +`bench/rust-globalalloc` workloads, whole-program Ir per n steps, checksum as +anchor) and a system-call count by `valgrind --tool=none --trace-syscalls=yes`. +Null arm: identical trees read 0 on every opscan op, and perl moves by up to +about 2,600 between builds of identical source. + +| vein | win | measured | +|---|---|---| +| 4, thread exit | a collect sweeps only bin queues that may hold a page (vein 10's `6fc177d`, merged) | thr **-343.75** Ir per thread | +| 4 | a heap's CSPRNG seeds itself at its first draw, not at creation | thr **-501** per thread; `open`/`read`/`close` of `/dev/urandom` gone (600 system calls for 200 threads) | +| 5, span-path system calls | a dying thread's freed spans are not scheduled for a delayed purge (`span_free_unscheduled`) | thr **-307.5** per thread; clock reads 1,199 -> 399, `madvise` 401 -> 201 (200 threads) | +| 5 | a returned chunk records its committed prefix; the next segment takes it as committed | thr **-209.75** per thread; `mprotect` 609 -> 12 (200 threads) | +| 1, realloc | the realloc leaf copies 65..=128 bytes in line, on an arm of its own | opscan realloc 203.92 -> **191.11**; `Vec` through the global handle **-14.1** Ir per step | +| 1 | the same arm in a first-class heap's realloc (`heap_realloc_fast`) | `Vec` in a heap **-10.4** per step | +| 3, calloc | a medium or large `calloc` goes straight to the generic path (`zalloc_generic_from`; `zalloc_slow` re-asked the direct table) | calloc_big **-2.00** per op | +| 3 | a free span purged by a decommit reads as zero, and `calloc` of it zeroes nothing | calloc_large under `purge_delay = 0`: 262,674 -> **483** per op (the `memset` of 256 KiB) | +| 2, panic sites | the bin formula and the small-bin table masked to a bound LLVM can see | panic sites **28 -> 27**; lua -2,966, perl -3,182, sqlite -104 allocator Ir | +| 2 | an arena's live chunk count bounded once where it is loaded (`Arena::live_chunks`) | panic sites **27 -> 15**; thr -20.5 per thread | + +Found and fixed on the way: the purge of an abandoned segment's free spans was +gated on `options::is_enabled(30)` (`guarded_min`) instead of +`abandoned_page_purge` from 0.3.0 to 2.6.1, so it never ran by default; it is +unconditional now, as `options` documents, and `tests/abandon_purge.rs` holds +it. + +Totals against the tree before the round, in one paired run, outputs +identical (sqlite +40 and perl +166 are inside their between-build spread): + +| instrument | before | after | +|---|---:|---:| +| thr, Ir per short thread | 9,927.55 | 8,509.69 (**-14.3 %**) | +| rust-threads (200 threads), whole program | 2,658,387 | 2,411,397 (**-9.3 %**) | +| vec_global / vec_direct, per 20,000 steps | 50,668,795 | 50,365,901 (-0.60 %) | +| vec_heap | 50,488,134 | 50,257,909 (-0.46 %) | +| opscan realloc / huge / aligned | 204.24 / 145.00 / 79.76 | 190.79 / 138.00 / 79.50 | +| lua / python, allocator Ir | 19,874,551 / 138,942 | 19,871,345 / 138,649 | +| panic sites reachable from an `Allocator` method | 28 | 15 | + +Gates: the Linux CI jobs locally (38 steps, every clippy configuration and +geometry), miri on the core crate (70 passed), the Windows test matrix (six +configurations), and three new permanent cases in `tools/gate-selftest.sh` +(the abandon purge, the zero-span merge, the realloc leaf's 128-byte arm), +each seen to fire. + +### Refuted in this round + +- **Zeroing a recycled block of up to 128 bytes in line** instead of + `memset`: calloc_batch (64 bytes) -0.99, calloc (256 bytes) +2.82 for the + size compare in front of the `memset`. glibc's `memset` is already about as + short as the ladder at 64 bytes. +- **The calloc miss's zeroing out of line in tail position**, to drop + `zalloc_generic`'s frame: +5. LLVM kept `b` in a callee-saved register + around the call anyway, and the helper took a frame of its own. +- **The 65..=128 rung at the top of the copy ladder**: realloc -10.25 and + every shorter copy +2 (lua +119,645). Inside the 33..=64 rung: the 64-byte + copy still +1 compare. Only an arm of its own in the leaf was free. +- **Masking the bin formula's bit index** (`b & 15`): nothing, since the + `- 3` still wraps for `b = 0`; masking the result works. + +### Left + +- ~~15 panic sites~~: zero since the same day; see the next section. +- Each short thread still reads the clock twice (the chunk's pending stamp + and the arena's purge check) and commits nothing, purges once. +- `calloc`'s own share over `malloc` is now the multiply and the zero test; + the rest is `memset`. + +## Panic sites to zero, and the `Allocator` guard off, 2026-12-02 + +Every fix measured against the same frozen tree in one invocation (opscan, +perl, sqlite, lua, python, `thr`, the seven Rust workloads), outputs +identical; a fix that moved an instrument was reshaped until none did. + +| site(s) | fix | instrument | +|---|---|---| +| `try_guarded` 2, `init_thread_heap` 2 | `Random::next_u32` indexes with `used` or, after a refill, 0 | 15 -> 11, all flat | +| `Random::refill` | `/dev/urandom` read by a loop that stops on a bad count through `get_mut`, not `read_exact`'s reslice | -> 10 | +| `schedule_purge` | takes the span's slot pointer, which its caller holds, not the index | -> 9 | +| `free_local_at` 2, `malloc_aligned_at_slow`, `retire_or_abort`; `update_direct` | `Heap::queue_at`: a bin past `BIN_FULL` aborts (a corrupted page), then indexes | -> 5 -> 0 with the next three; flat | +| `adopt_segment` | its second slice walk by pointer, like the first | | +| `commit_claimed_part` | `set_bits` through `get` | | +| `ensure_init_slow`; `out_fmt` | `val.get(..len)`; `try_with` on its thread-local, and fd 2 written directly on unix (std's stderr lock has a count `expect` and a `RefCell`) | | +| `page_purge_free_slots` | page-size round-up by mask, not `next_multiple_of` (a `%`) | | +| default profile: `ABANDONED_HEADS[sp]` twice | `my_subproc` aborts on an id past the table (only valid ids are stored) | 2 -> 0 | + +**REFUTED: clamping with `min`.** `bin.min(BIN_FULL)` removes the panic but +is a `cmov`, which takes no immediate: a `mov` more than the bounds check's +compare and branch. `aligned` +0.07 Ir/op, `aligned_alloc` +0.06, exactly +one per `malloc_aligned_at_slow`. Compare-and-abort is the bounds check's own +two instructions with an abort for its target: 0.00. + +**The scan was blind outside fat LTO, twice.** Cargo's default release +profile is what most users build, and fat LTO had proven two indexes by +inlining across crates. A first default-profile scan read zero because, +without LTO, a call into std goes through the GOT (`call *x(%rip)`), so the +panic's name is not on the line; the new pass's self-test (an export that +indexes a slice must register) failed, which is what it is for. Resolving the +GOT slots (their `RELATIVE` addends, named by `nm`) found the two real sites. +`tools/no-unwind-scan.sh` now runs both passes and fails the default one at +any count above zero on x86-64 Linux. + +**Opt-level matters, so a build script reads it.** Zero at `opt-level` 2 and +3; `s` 2 sites (`chunk_release_ex`), `z` 5, 1 sixteen. There is no `cfg` for +the level, so `build.rs` reads `OPT_LEVEL` and `rusty_alloc::NO_UNWIND_PROVEN` +requires 2 or 3, x86-64 Linux, no debug assertions, default features and no +`ra_*` cfg. Verified: the probe built at 3 has no `AbortOnUnwind` symbol, at +`s` it has one. Unseeable: a release profile with `overflow-checks` on. + +**The guard, off where proven:** `vec_direct` (`Vec::new_in(RustyAlloc)`) +50,408,014 -> 49,856,134 (**-27.6 Ir a step, -1.09 %**; the global handle on +the same work is 50,365,808), `vec_heap` 50,257,789 -> 49,687,662 (**-28.5, +-1.13 %**). Nothing else moved. + ## Banked ### 8. Collect-loop double `block_next` — LANDED 2026-08-20 diff --git a/docs/plans/windows-commit-footprint.md b/docs/plans/windows-commit-footprint.md new file mode 100644 index 0000000..2213360 --- /dev/null +++ b/docs/plans/windows-commit-footprint.md @@ -0,0 +1,342 @@ +# Windows commit footprint (issue #63) + +Status: diagnosed and built 2026-12-02 (see Outcome); not merged. +Branch `fix/commit-footprint`, worktree `E:/coding/rusty_alloc-i63`. Kit: `bench/issue63/`. + +## The report + +fast-decomp (`b64727a`, Rust 1.100, release profile) with `rusty_alloc-api` 2.6.0 as the +global allocator is faster than the Windows heap and commits far more memory. +Reproduced here, same binaries and corpus as the issue: + +| case | Windows heap commit | 2.6.0 commit | Windows heap working set | 2.6.0 working set | +|---|---:|---:|---:|---:| +| ninja, 1 thread | 17.7 MiB | 34.1 MiB | 29.9 MiB | 34.1 MiB | +| ninja, 6 threads | 34.0 MiB | 90.6 MiB | 44.1 MiB | 52.7 MiB | +| OpenTTD, 6 threads | 355 MiB | 490 MiB | 359 MiB | 440 MiB | + +Work parity: `output_bytes` is identical in every run (5,736,577 and 178,016,411), and a +counting wrapper under both allocators sees the same 121,896 calls and the same peak of +requested bytes on ninja (14.35 MiB on one thread). + +The gap is real. Most of it is commit charge for memory that is never touched, which +Windows counts and Linux (default overcommit) does not. This is a Windows problem first. + +## Decomposition (ninja, reconciled to the byte) + +Instrument: a `GlobalAlloc` wrapper in fast-decomp that counts requested bytes and walks +the address space with `VirtualQuery`, plus a temporary span/extend trace inside the +allocator. The walk finds exactly one 1 GiB arena with 32.00 MiB committed on one thread. + +| line | 1 thread | 6 threads | class | +|---|---:|---:|---| +| spans holding large blocks (over 64 KiB) | 8.81 | 10.94 | data | +| medium pages (512 KiB), carved into blocks | 6.27 | 16.77 | data + block slack | +| medium pages, committed and never touched | **6.23** | **23.23** | granularity | +| small pages (64 KiB), carved into blocks | 4.47 | 10.77 | data + block slack | +| small pages, committed and never touched | **2.09** | **7.17** | granularity | +| committed ahead of the carve frontier | **3.75** | **14.31** | policy | +| free spans under the frontier | 0.25 | 0.38 | policy | +| segment headers | 0.13 | 0.44 | structure | +| **sum = committed in the arena** | **32.00** | **84.01** | | + +The address-space walk reads 32.00 and 84.95 MiB (six-thread runs differ by a segment). +Segments: 2 on one thread (main plus one worker), 7 on six. + +Never-touched commit is 12.1 of 32 MiB on one thread and 44.7 of 84 MiB on six. + +OpenTTD, six threads, is less exact (purges move commit under the frontier and huge +segments were not traced): 129 medium pages with 33.5 MiB never touched, 910 small pages +with 4.7 MiB never touched, and 69 MiB of free spans under the frontier at the span peak. +At exit the process still has 314 MiB committed with 1.4 MiB live; the Windows heap has 11. + +## Levers, ranked + +1. **Commit step (policy). Measured.** `COMMIT_STEP_MAX_SLICES` commits up to 4 MiB past + what a carve needs, per segment, and a thread's segment is rarely full. With the step at + 256 KiB: ninja 36.2 -> 32.5 MiB (the 3.75 predicted), ninja six threads 88.6-96.6 -> + 75.5-77.7, OpenTTD 493-496 -> 481. No time change visible in two runs per arm; that is + not a timing result. Cost is more `VirtualAlloc` calls; count them before choosing a step. +2. **Freed spans that stay committed (policy). Measured as a knob, not as a fix.** + `purge_delay=0` on OpenTTD: commit 490 -> 436 MiB, working set 440 -> 382, same time in + single runs. `purge_delay=1`: 458. The default 10 ms delay is only acted on when the same + segment frees another span or a collect runs, so a span freed last stays resident. The + fix is to make the delay fire (a deadline another path checks), not to ship delay 0, + which has a known 300x pathology on a free/re-allocate loop. +3. **Commit a page as it fills (granularity). Arithmetic, not yet measured.** A page's + whole span is committed when carved; blocks are linked in 4 KiB steps. Committing with + the extend instead removes up to the never-touched lines above: 8.3, 30.4 and 38 MiB, + less rounding to the commit step chosen. Medium pages are the bulk and the easy half + (512 KiB page, 64 KiB steps: at most 8 commits a page). This changes the invariant that + everything under `commit_end` is backed unless flagged `purged`, which is the invariant + behind the two access-violation bugs of October. It needs its own gates. +4. **Retention at exit and at idle (policy).** Not a peak cost. Matters for a long-running + process: 314 MiB held for 1.4 MiB live. + +Projection, not measurement: levers 1 to 3 together put OpenTTD near 385 MiB against 355, +and ninja on one thread near 20 MiB against 17.7. + +## What does not close + +After the levers, carved blocks still exceed requested bytes (ninja: 10.7 MiB carved in +small and medium pages for about 6.4 MiB requested there). That is size-class rounding and +free blocks inside live pages, per thread heap. It is the price of the free-list design +and of the speed result, and it is also the remaining working-set gap. Expect to land +within about 10 to 20 % of the Windows heap on commit, not under it. + +## Dead hypotheses + +- Arena reservation: the 1 GiB arena is reserved, not committed. Changing `arena_reserve` + or `disallow_arena_alloc` moves nothing. +- Span-level fragmentation on ninja: frontier 28.25 MiB against 27.88 MiB of live spans. +- `generic_collect` cadence: no effect on the peak. +- The 1,078 MiB in the original post was 2.2.6. It does not reproduce on 2.6.0. + +## Outcome (2026-12-02, two passes) + +Built on `fix/commit-footprint`. Same binaries, corpus and harness as the +report; `timing.py` interleaves the Windows heap, 2.6.0, this branch and the +Windows heap again, pinned, 7 / 7 / 5 rounds; Godot is three interleaved +rounds of `multi.py`. + +| case | Windows heap | 2.6.0 | this branch | ratio to the heap, before -> now | +|---|---:|---:|---:|---| +| ninja, 1 thread, commit | 17.6 MiB | 34.0 | 22.0 | 1.93 -> 1.25 | +| ninja, 6 threads, commit | 32.3 MiB | 90.6 | 43.7 | 2.80 -> 1.35 | +| OpenTTD, 6 threads, commit | 364 MiB | 495 | 410 | 1.36 -> 1.13 | +| Godot, 6 threads, commit | 1,024 MiB | 1,488 | 1,125 | 1.45 -> 1.10 | +| OpenTTD, working set | 368 MiB | 437 | 412 | 1.19 -> 1.12 | +| Godot, working set | 1,045 MiB | 1,416 | 1,136 | 1.35 -> 1.09 | + +Time, paired ratio to the Windows heap in the same round (below 1 is faster): + +| case | 2.6.0 | this branch | noise arm (heap again) | +|---|---:|---:|---:| +| ninja, 1 thread | 0.964 (6/7) | 0.986 (5/7) | 0.993 | +| ninja, 6 threads | 0.926 (7/7) | 0.948 (5/7) | 1.000 | +| OpenTTD, 6 threads | 0.946 (5/5) | 0.963 (5/5) | 0.994 | + +This branch reads about two points slower than 2.6.0 in each row, which is +twice the noise arm's spread: likely real, small, and not resolved further +here. It is faster than the Windows heap in every OpenTTD round. + +Five synthetic shapes (`E:/coding/fd-i63/microbench`, medians of five): + +| shape | Windows heap | 2.6.0 | this branch | +|---|---|---|---| +| 8 M small blocks kept | 0.89 s, 570 MiB | 0.24 s, 435 MiB | 0.24 s, 431 MiB | +| 64 threads, every class once | 66 MiB | 518 MiB | 134 MiB | +| 50 MiB allocated and freed, 40 rounds | 1.85 s | 0.46 s | 0.47 s | +| the same with a 25 ms pause a round | 3.10 s | 1.62 s | 1.70 s | +| a 3 MB buffer grown by doubling, 300 times | 1.70 s | 1.02 s | 1.05 s | + +What landed: + +1. Commit step 256 KiB on Windows (`COMMIT_STEP_MAX_SLICES`). +2. One purge trigger besides the two that existed: `Heap::purge_tick`, run + when the heap carves a span. It looks at most once a delay and purges only + spans already free at its last look (`segment::purge_aged`). A first cut + purged everything due at the first carve after a pause, and at every + commit: the pause-and-reuse shape above ran 2.43 s against 1.62. The + observation rule brought it back and kept the peaks (OpenTTD 393 against + 398, Godot 1,134 against 1,138, medians of interleaved runs). +3. Medium pages commit as they fill; the first small page of a class commits + 16, 32, then 64 KiB (`PAGE_LAZY_COMMIT`, `Page::lazy_end` in 16 KiB units, + `segment::page_commit_to`, `Heap::bins_seen`). A short page carves one + slice or unit of blocks a trip, so a page's first trip never commits. +4. A large block commits to its last OS page and reports that as its size + (`segment::span_alloc_first`); the one-span large cache checks it. +5. A huge block has the arena commit what it reaches + (`arena::chunk_alloc_n_part`), or gives back its tail when the chunks came + committed; `Segment::huge_trim` lets the free commit only that tail back. + Committing the whole range again was charged in full while the call ran: + a freed 61 MiB block took the peak from 66 to 127 MiB. +6. Purge candidates from two slices up (`PURGE_MIN_SLICES`), was eight. +7. Found on the way and fixed: + - Taking part of a purged free span re-committed the whole span. + - A resident span merged with a purged neighbour was flagged purged and + skipped by every later purge. New flag `Page::partly`. At exit OpenTTD + held 314 MiB committed with 1.4 MiB live; it now holds 86. + - `Heap::visit_blocks` reported a huge block at the wrong address. + +Gates: `segment::commit_footprint_tests` (16 tests) and an addition to +`tests/heaps.rs`. Twenty-five mutations of the new rules were each caught by +at least one test (`bench/issue63/poison.py`); five are permanent in +`tools/gate-selftest.sh`. (After the third pass: 23 tests, 34 mutations, +seven gates; the fourth pass landed nothing.) + +What is left of the gap: + +- Commit now sits at or below the working set on the large programs, so + what remains there is touched memory: size-class rounding and free blocks + inside live pages, per thread. OpenTTD 1.12 and Godot 1.09 by working set. +- ninja (1.25, 1.35) is the per-thread floor: 6 threads times a first page + for each class touched, in 16 KiB units, plus one slice a medium class. +- Small pages after a class's first still commit whole; a segment still + commits 256 KiB ahead. +- Linux gets the purge changes and the partial re-commit only. Its + footprint and wall clock under them were not measured. + +## Third pass (2026-12-02): where the rest is, and what it took + +A fresh trace of the built tree (`trace_on.py`, `tr3.py`: span, extend and OS +commit events, decomposed at the moment of peak commit) instead of guessing. + +OpenTTD, six threads, at its peak (403 MiB committed): + +| line | committed | carved into blocks | +|---|---:|---:| +| small pages (973) | 60.0 | 56.3 | +| medium pages (89) | 28.0 | 25.3 | +| large blocks (114) | 128.9 | 128.9 | +| huge blocks (2) | 61.8 | 61.8 | +| **free spans, still committed** | **122.8** | | +| headers, ahead of the cursor | 1.5 | | + +Of the free spans, 117 MiB was in runs of half a megabyte and more, while an +8 MiB block was being committed fresh. They are not the committing thread's: +they belong to the other five heaps, freed inside the purge delay. + +What that led to: + +- **Large blocks grow in place** (`segment::span_grow`, called from + `realloc`): into the bump cursor, into the front of a free span that + follows, or inside a short block's own last slice. By bytes of large span + freed on OpenTTD, the cursor followed 12 %, a free span at least as long + 23 %, a shorter free span 24 % (`adj.py`). No fresh span, no copy, no old + span left behind. The growth shape runs 0.97 s -> 0.87 s; Godot's peak fell + about 23 MiB in the runs that isolated it; OpenTTD's did not move. +- **The purge delay is the remaining lever, and it is a trade.** OpenTTD's + peak by `purge_delay`: 10 ms (default) 401 to 414 MiB, 1 ms 368 to 377, + 0 ms 366 to 376; the Windows heap is 358 to 364. The same settings on a + loop that allocates and frees 50 MiB of small blocks back to back: 0.52 s + at 10 ms, 0.83 at 3, 1.21 at 1, 1.83 at 0. The default stays 10 ms. + `RUSTY_ALLOC_PURGE_DELAY` is the knob for a program that would rather have + the memory. + +Final numbers, same harness (the machine was busier in this round: the noise +arm reads 1.08, 1.05 and 0.98, so the ninja time rows say nothing): + +| case | Windows heap | 2.6.0 | this branch | ratio to the heap, before -> now | +|---|---:|---:|---:|---| +| ninja, 1 thread, commit | 17.6 MiB | 34.0 | 21.9 | 1.93 -> 1.24 | +| ninja, 6 threads, commit | 33.4 MiB | 86.6 | 42.7 | 2.59 -> 1.28 | +| OpenTTD, 6 threads, commit | 358 MiB | 485 | 403 | 1.35 -> 1.13 | +| Godot, 6 threads, commit | 1,073 MiB | 1,458 | 1,096 | 1.36 -> 1.02 | + +OpenTTD's time, paired to the Windows heap: 2.6.0 0.925, this branch 0.945, +both faster in 5 of 5 rounds. + +Dead in this pass, with how each died: + +- **Giving back a heap's own free spans when it must commit a long span** + (largest first, as much as it takes). OpenTTD 396 against 397, Godot no + better: the free memory at the peak is in other heaps. Removed. +- **Carving fewer blocks ahead a trip** (no doubling, or half). ninja 43.6, + 43.6 and 43.3 MiB; one thread 21.9 in all three. The gap between carved and + requested bytes in small and medium pages is not carve-ahead: it is blocks + freed inside live pages and each class's own peak. Not changed. +- **A shorter default delay**: see the trade above. + +What is left on ninja (1.24, 1.28) is that last line: 13.0 MiB of small pages +and 16.5 of medium for 5.8 and 8.8 MiB requested at the peak, six heaps each +with a page for every class it touched. + +The wasm module grew 650 bytes gzipped (21,432 -> 22,082, 3 %), most of it +in-place growth, which serves wasm too; the size baseline was updated +deliberately. + +## Fourth pass (2026-12-02): the purge delay's memory, without its price + +A shorter `purge_delay` closes OpenTTD's gap and makes a free-and-reallocate +loop 1.6 to 3.5 times slower, which is not acceptable. Five other routes to +the same memory were prototyped and measured against the peaks AND against +the reuse shapes (`E:/coding/fd-i63/microbench`: small-block churn with and +without a pause, a buffer grown by doubling, three large buffers a round on +one thread and on six, six threads growing buffers, 8 M small blocks, 64 +threads touching every class). **None was landed.** The tree is the third +pass's. + +The instrument that decided it is a count, not a clock: page faults of the +whole run (`faults.py`). On a machine at 70 to 100 % CPU the timings moved by +tens of per cent between rounds; the fault count of a shape is the same to a +few units run after run when the machine is free, and it is exactly the cost +at issue (a purge that is taken back is a re-commit and a fault a page). + +| route | OpenTTD peak | faults on the reuse shapes | verdict | +|---|---|---|---| +| pressure: a fresh commit of 1 MiB or more makes every other heap purge at its next span event | 390 -> 387 MiB | not counted; times unchanged | too weak | +| a freed large span of 1 MiB or more, not cached, is purged at once | 390 -> 373 | three large buffers a round 0.26 s -> 1.85 s; six threads 0.58 -> 3.46; small churn 0.42 -> 1.42 | rejected | +| blocks of 1 MiB and up in an arena chunk of their own, the committed prefix tracked and reused across threads | 389 -> 379 (ws 388 -> 371); Godot commit unchanged | times at parity, but six threads of mixed large sizes commit 136 to 154 MiB for 123 | set aside: `route3-big-blocks-in-chunks.patch` | +| each segment learns whether its purged memory is taken back (ratio of slices purged to slices taken back) | 405 -> 390, 397 -> 389, 404 -> 389, 408 -> 387 | small churn 17,700 -> 23,000 to 40,000 | rejected | +| the same with stricter evidence: only spans a heap look found idle count | 408 -> 403 | small churn 17,700 -> 17,700 to 23,000 | no gain | +| the same as a ledger: purge at once only on credit earned by idle spans, spent by each purge, doubled back if it stays unused, charged double if taken back | 408 -> 413 (no gain); with aged-out spans earning too: churn 30,000 to 36,000 | | no gain, or the cost back | +| purge at once only the span a large block leaves when `realloc` has to move it | 406 -> 405 | identical | no gain: growth in place already removed those spans | + +What the learning routes showed is the shape of the problem. A segment's +history does not say which of its spans is coming back: a loop that reuses +most of what it frees still has a few megabytes that sit idle, those earn +the right to purge at once, and the right is spent on the spans that ARE +coming back. Evidence strict enough never to be wrong is too rare to move +the peak. So at the default delay the remaining gap on OpenTTD (about 8 %, +30 MiB) is what a 10 ms reuse cache holds across six heaps, and every way of +giving it back sooner is paid for by some program that wanted it back. +`RUSTY_ALLOC_PURGE_DELAY` remains the knob for a program that knows it does +not. + +The third pass's tree on the same counter, against 2.6.0 (minimum / median +of five runs each): + +| shape | 2.6.0 | this branch | +|---|---:|---:| +| small-block churn | 17,674 / 17,678 | 17,669 / 17,760 | +| the same with a 25 ms pause | 110,448 / 110,457 | 110,669 / 112,657 | +| three large buffers a round | 6,400 / 6,404 | 6,408 / 6,410 | +| the same on six threads | 32,173 / 32,175 | 32,178 / 32,181 | +| six threads growing buffers | 238,461 / 266,258 | 26,611 / 26,613 | +| a buffer grown by doubling | 3,215 / 3,218 | 2,977 / 2,979 | + +Final numbers for the tree as it stands (the machine at about 37 % CPU): + +| case | Windows heap | 2.6.0 | this branch | ratio to the heap, before -> now | +|---|---:|---:|---:|---| +| ninja, 1 thread, commit | 17.6 MiB | 34.0 | 21.9 | 1.93 -> 1.24 | +| ninja, 6 threads, commit | 33.4 MiB | 90.6 | 43.0 | 2.71 -> 1.29 | +| OpenTTD, 6 threads, commit | 361 MiB | 493 | 405 | 1.36 -> 1.12 | +| Godot, 6 threads, commit | 1,024 MiB | 1,435 | 1,097 | 1.40 -> 1.07 | + +| time, paired to the Windows heap | 2.6.0 | this branch | noise arm | +|---|---:|---:|---:| +| ninja, 1 thread | 1.011 (3/7) | 0.986 (4/7) | 0.997 | +| ninja, 6 threads | 0.968 (7/7) | 0.986 (4/7) | 0.996 | +| OpenTTD, 6 threads | 0.966 (4/5) | 0.950 (5/5) | 0.994 | + +## Checks run on the final tree (2026-12-02) + +- Windows: workspace in debug (218 tests), `--all-features` (263), the core + and API crates in release (243), `debug_checks` and `secure` (192 each); + fmt and clippy. `--features secure` failed once in 23 runs across the + passes, not reproduced and not identified (that run's log was not kept). +- Linux (WSL), the CI jobs locally (`bench/issue63/ci-linux.sh`): every clippy + configuration, tests in debug and release, shared-light-heap and the three + small-profile geometries, bare-metal riscv, wasm, Rust 1.88, the unsafe + census (1223 -> 1278, recorded in `UNSAFE.md`), the no-unwind scan, the wasm + size ratchet (baseline raised, see above) and the whole gate self-test + (27 gates). +- miri on the core crate's unit tests: 69 passed, 0 failed, 14 ignored. +- Linux instructions per operation, base against this tree (`ir-ab.sh`): + small, med, big, large, huge, calloc, batch_lifo and batch_fifo identical; + realloc 203.92 -> 204.24, aligned 79.63 -> 79.76, mixed 85.80 -> 85.81. + +Not run: macOS, the full miri matrix (three hours in CI), Kani, fuzz, and +any Linux footprint or wall-clock measurement of the purge change. + +## Reproduce + +`bench/issue63/`: `fast-decomp-probe.patch` and `probe.rs` (fast-decomp side, features +`probe`, `trace`), `allocator-trace-and-step.patch` (temporary trace, do not land), +`probe.py` (launch pinned, read peak counters), `tr2.py` (decompose a trace), +`timing.py` (interleaved rounds), `poison.py` (the mutation run), `ci-linux.sh` +(the Linux CI jobs, locally), `ir-ab.sh` (Linux instructions per operation), +`trace_on.py` / `tr3.py` / `adj.py` (the third pass's trace: apply, build, +restore; decompose at the peak; growth-in-place census). diff --git a/tools/gate-selftest.sh b/tools/gate-selftest.sh index f56ce85..55a6f79 100644 --- a/tools/gate-selftest.sh +++ b/tools/gate-selftest.sh @@ -230,6 +230,62 @@ run_case "a destroyable heap does not adopt in a collect" \ 's/if reclaim && !self\.no_reclaim \{/if reclaim {/' \ "--test destroy_no_adopt -- --test-threads=1" +# --- what a segment commits, and when it gives memory back (issue 63) -------- +# Taking part of a purged free span commits the part taken; the remainder must +# go on saying it is purged, or it is handed out unbacked later. +run_case "the remainder of a purged span stays purged" \ + "crates/rusty_alloc/src/segment.rs" \ + 's/\(\*rest\)\.purged = was_purged;/(*rest).purged = false;/' \ + "--lib commit_footprint_tests::taking_part_of_a_purged_span_commits_only_what_is_taken" + +# A resident span that merges with a purged neighbour is flagged for re-commit +# and must still be purged when its delay runs out. +run_case "a resident span merged with a purged one is still a purge candidate" \ + "crates/rusty_alloc/src/segment.rs" \ + 's/if \(!\(\*s\)\.purged \|\| \(\*s\)\.partly\) && len >= PURGE_MIN_SLICES \{(\n\s*\/\/ Milliseconds)/if !(*s).purged && len >= PURGE_MIN_SLICES {$1/' \ + "--lib commit_footprint_tests::a_resident_span_merged_with_a_purged_one_is_purged_later" + +# A due purge runs when the heap next carves a span, not only on another large +# free in the same segment; and only on what it has seen free for a delay. +run_case "a heap purges what it has seen free for a delay when it carves a span" \ + "crates/rusty_alloc/src/heap.rs" \ + 's/if self\.purge_next != 0 \{\n self\.purge_tick\(\);\n \}//' \ + "--lib commit_footprint_tests::a_heap_purges_what_it_has_seen_free_for_a_delay" + +run_case "a heap does not purge what it first sees free" \ + "crates/rusty_alloc/src/heap.rs" \ + 's/self\.stats\.purges \+= segment::purge_aged\(s, now, since\) as u64;/self.stats.purges += segment::purge_aged(s, now, 0) as u64;/' \ + "--lib commit_footprint_tests::a_loop_that_pauses_and_reuses_purges_nothing" + +# A large block grows where it is when the cursor or a free span follows it, +# and only at the hands of the thread that owns its segment. +run_case "realloc grows a large block in place" "crates/rusty_alloc/src/alloc.rs" 's/&& crate::segment::span_grow\(seg, pg, newsize\)/\&\& false/' "--lib commit_footprint_tests::realloc_grows_a_large_block_where_it_is" + +run_case "only the owning thread grows a large block in place" "crates/rusty_alloc/src/alloc.rs" 's/&& \(\*seg\)\.thread_id\.load\(Ordering::Relaxed\) == init::thread_id\(\) +\s*&& crate::segment::span_grow/\&\& crate::segment::span_grow/' "--lib commit_footprint_tests::realloc_from_another_thread_moves_a_large_block" + +# --- the optimization round after issue 63 ---------------------------------- +# An abandoned segment's free spans are purged unconditionally (the gate read +# the wrong option index from 0.3.0 to 2.6.1, and never ran by default). +run_case "an abandoned segment has its free spans purged" \ + "crates/rusty_alloc/src/init.rs" \ + 's/ unsafe \{ crate::segment::purge_free_spans\(seg\) \};/ if crate::options::is_enabled(30) {\n unsafe { crate::segment::purge_free_spans(seg) };\n }/' \ + "--test abandon_purge" + +# A span purged by a decommit reads as zero; one that merges a written span +# from the right into it must not. +run_case "a written span merged into a zero one is not zero" \ + "crates/rusty_alloc/src/segment.rs" \ + 's/ \(\*lstart\)\.free_is_zero = false;\n//' \ + "--lib commit_footprint_tests::a_decommitted_span_is_reported_zero_and_is" + +# The realloc leaf's 65..=128-byte arm copies the whole block (x86-64 Linux, +# where the leaf exists; the same test passes trivially elsewhere). +run_case "the realloc leaf's 128-byte arm keeps every byte" \ + "crates/rusty_alloc/src/alloc.rs" \ + 's/core::ptr::copy_nonoverlapping\(p\.add\(copy - 64\), np\.add\(copy - 64\), 64\);\n \} else \{\n copy_small\(p, np, copy\);\n \}\n stat_realloc\(false\);\n return free_moved\(p, pg, np\);\n \}\n \}\n realloc_move_out/core::ptr::copy_nonoverlapping(p.add(copy - 65), np.add(copy - 65), 64);\n } else {\n copy_small(p, np, copy);\n }\n stat_realloc(false);\n return free_moved(p, pg, np);\n }\n }\n realloc_move_out/' \ + "--release --test alloc_core realloc_keeps_every_byte" + echo if ((fail > 0)); then echo "GATE SELFTEST FAILED: $fail of $((pass + fail)) gates did not fire." diff --git a/tools/no-unwind-baseline.txt b/tools/no-unwind-baseline.txt index 15ae453..e69de29 100644 --- a/tools/no-unwind-baseline.txt +++ b/tools/no-unwind-baseline.txt @@ -1,18 +0,0 @@ - 2 _RNvMs0_Nt11rusty_alloc4heapNtB5_4Heap11try_guarded -> _RNvNt4core9panicking18panic_bounds_check - 1 _RNvMs0_Nt11rusty_alloc4heapNtB5_4Heap13adopt_segment -> _RNvNt4core9panicking18panic_bounds_check - 1 _RNvMs0_Nt11rusty_alloc4heapNtB5_4Heap13collect_inner -> _RNvNt4core9panicking18panic_bounds_check - 2 _RNvMs0_Nt11rusty_alloc4heapNtB5_4Heap13free_local_at -> _RNvNt4core9panicking18panic_bounds_check - 1 _RNvMs0_Nt11rusty_alloc4heapNtB5_4Heap19malloc_generic_once -> _RNvNt4core9panicking18panic_bounds_check - 1 _RNvMs0_Nt11rusty_alloc4heapNtB5_4Heap22malloc_aligned_at_slow -> _RNvNt4core9panicking18panic_bounds_check - 2 _RNvNt11rusty_alloc4init16init_thread_heap -> _RNvNt4core9panicking18panic_bounds_check - 1 _RNvNt11rusty_alloc4init16init_thread_heap -> _RNvNtNt4core5slice5index16slice_index_fail - 1 _RNvNt11rusty_alloc4page21page_purge_free_slots -> _RNvNtNt4core9panicking11panic_const23panic_const_rem_by_zero - 1 _RNvNt11rusty_alloc5alloc15retire_or_abort -> _RNvNt4core9panicking18panic_bounds_check - 3 _RNvNt11rusty_alloc5arena13chunk_release -> _RNvNt4core9panicking18panic_bounds_check - 3 _RNvNt11rusty_alloc5arena14commit_claimed -> _RNvNt4core9panicking18panic_bounds_check - 1 _RNvNt11rusty_alloc5arena17chunk_alloc_inner -> _RNvNt4core9panicking18panic_bounds_check - 4 _RNvNt11rusty_alloc5arena19chunk_alloc_n_inner -> _RNvNt4core9panicking18panic_bounds_check - 1 _RNvNt11rusty_alloc7options16ensure_init_slow -> _RNvNtNt4core5slice5index16slice_index_fail - 1 _RNvNt11rusty_alloc7options7out_fmt -> _RNvNt4core6option13expect_failed - 1 _RNvNt11rusty_alloc7segment10span_alloc -> _RNvNt4core9panicking18panic_bounds_check - 1 _RNvNt11rusty_alloc7segment14schedule_purge -> _RNvNt4core9panicking18panic_bounds_check diff --git a/tools/no-unwind-scan.sh b/tools/no-unwind-scan.sh index 36dcc92..827e335 100644 --- a/tools/no-unwind-scan.sh +++ b/tools/no-unwind-scan.sh @@ -12,9 +12,12 @@ # None can fire while the allocator's state is intact. Each is still a path # the guard has to cover, and an instruction or two on the way past it. # -# So the count may only go down. At zero the guard has nothing left to guard -# and can be removed, which is worth 27.6 instructions per step of collection -# work on `Vec::new_in(RustyAlloc)` (`docs/opps.md`). +# The count reached zero on 2026-12-02, and the guard is now OFF where this +# scan proves the build (`rusty_alloc::NO_UNWIND_PROVEN`: x86-64 Linux, no +# debug assertions, opt-level 2 or 3, default features), worth 27.6 +# instructions per step on `Vec::new_in(RustyAlloc)` (`docs/opps.md`). So on +# that host zero is a hard gate, in both passes below: a site that comes back +# is a path on which an `Allocator` method would unwind with no guard. # # How it is measured: `tools/unwind-probe` exports one function per method of # both impls and links them with fat LTO into a single module. What is in that @@ -113,6 +116,58 @@ cur_total=$(awk '{s+=$1} END{print s+0}' "$cur") echo " panic sites in the allocator's own functions: $cur_total, in $(wc -l < "$cur") places" echo +# The same count in the shape most users ship: Cargo's DEFAULT release +# profile, no LTO, sixteen codegen units. A bound the optimiser proved only by +# inlining across crates under fat LTO would come back here. Read from the +# linked object (`objdump`), where `--gc-sections` has dropped what the +# exports cannot reach. `rusty_alloc::NO_UNWIND_PROVEN` drops the guard on +# x86-64 Linux, so on that host this count must be zero, not just no worse. +default_scan() { # extra cargo args... -> census of the linked .so + local dir="$CARGO_TARGET_DIR-default" + ( cd "$probe" && CARGO_TARGET_DIR="$dir" CARGO_PROFILE_RELEASE_LTO=false \ + CARGO_PROFILE_RELEASE_CODEGEN_UNITS=16 cargo build -q --release "$@" ) >&2 || return 1 + local so="$dir/release/libunwind_probe.so" + # Without LTO a call into std goes through the GOT (`call *0x..(%rip) # slot`), + # so the callee is named only by the slot's dynamic relocation. Each such + # call line gets the relocation's symbol appended before matching; the + # self-test above is what caught a pattern that looked only at the line. + # A slot holds either a symbol (`GLOB_DAT`) or, for a function defined in + # the object itself, a `RELATIVE` addend that is its address (named by `nm`). + { nm --defined-only "$so" | awk 'NF == 3 { a = $1; sub(/^0+/, "", a); print "SYM", a, $3 }' + objdump -R "$so" | awk '$2 ~ /GLOB_DAT|JUMP_SLOT/ { print "GOT", $1, $3 } + $2 ~ /RELATIVE/ { v = $3; sub(/^\*ABS\*\+0x/, "", v); print "REL", $1, v }' + objdump -d --no-show-raw-insn "$so"; } | awk -v pat="$PAT" -v not="$NOT" ' + $1 == "SYM" { name[$2] = $3; next } + $1 == "GOT" { a = $2; sub(/^0+/, "", a); got[a] = $3; next } + $1 == "REL" { a = $2; sub(/^0+/, "", a); v = $3; sub(/^0+/, "", v); if (v in name) got[a] = name[v]; next } + /\(%rip\)/ && /# [0-9a-f]+ :$/ { sym = $2; gsub(/[<>:]/, "", sym) } + /call|jmp/ && $0 ~ pat && $0 !~ not && + (sym ~ /rusty_alloc/ || sym ~ /^probe_(global|heap|selftest)_/) && sym !~ /AbortOnUnwind/ { + t = $NF; gsub(/[<>]/, "", t); sub(/@.*$/, "", t); c[sym " -> " t]++ + } + END { for (k in c) printf "%4d %s\n", c[k], k } + ' | sed -E 's/Cs[0-9A-Za-z]+_//g' | sort -k2 +} +if [ "$(uname -s)" = Linux ] && [ "$(uname -m)" = x86_64 ] && command -v objdump >/dev/null; then + echo "=== the same methods, Cargo's default release profile (no LTO, 16 units) ===" + st=$(default_scan --features selftest) || { echo "DEFAULT-PROFILE BUILD FAILED"; exit 1; } + if ! grep -q 'probe_selftest_can_panic' <<<"$st"; then + echo " *** the default-profile pattern is blind: no site in the self-test export ***" + exit 1 + fi + dflt=$(default_scan) || { echo "DEFAULT-PROFILE BUILD FAILED"; exit 1; } + dflt_total=$(awk '{s+=$1} END{print s+0}' <<<"$dflt") + echo " self-test fires; panic sites in the allocator's own functions: $dflt_total" + if [ "$mode" != "--update" ] && [ "$dflt_total" -gt 0 ]; then + echo "$dflt" + echo "NO-UNWIND DEFAULT PROFILE FAILED: $dflt_total sites, and the guard is off on this target" + echo "(rusty_alloc::NO_UNWIND_PROVEN). Make each index provable without LTO, as above." + exit 1 + fi + echo +fi + host="$(rustc -vV | awk '/^host:/ {print $2}')" if [ "$mode" = "--update" ]; then cp "$cur" "$baseline"; rm -f "$cur" diff --git a/tools/unsafe-baseline.txt b/tools/unsafe-baseline.txt index 43d5512..6573605 100644 --- a/tools/unsafe-baseline.txt +++ b/tools/unsafe-baseline.txt @@ -1,9 +1,9 @@ - 194 crates/rusty_alloc/src/alloc.rs - 24 crates/rusty_alloc/src/arena.rs - 82 crates/rusty_alloc/src/heap.rs + 201 crates/rusty_alloc/src/alloc.rs + 26 crates/rusty_alloc/src/arena.rs + 88 crates/rusty_alloc/src/heap.rs 44 crates/rusty_alloc/src/init.rs 2 crates/rusty_alloc/src/lib.rs - 17 crates/rusty_alloc/src/options.rs + 18 crates/rusty_alloc/src/options.rs 16 crates/rusty_alloc/src/os.rs 57 crates/rusty_alloc/src/page.rs 37 crates/rusty_alloc/src/prim/fixed.rs @@ -13,7 +13,7 @@ 6 crates/rusty_alloc/src/prim/wasm.rs 36 crates/rusty_alloc/src/prim/windows.rs 2 crates/rusty_alloc/src/random.rs - 105 crates/rusty_alloc/src/segment.rs + 156 crates/rusty_alloc/src/segment.rs 8 crates/rusty_alloc/src/shared_light.rs 3 crates/rusty_alloc/src/stats.rs 38 crates/rusty_alloc_api/src/allocator.rs diff --git a/tools/unwind-probe/Cargo.lock b/tools/unwind-probe/Cargo.lock index df2fd39..650d98f 100644 --- a/tools/unwind-probe/Cargo.lock +++ b/tools/unwind-probe/Cargo.lock @@ -16,7 +16,7 @@ checksum = "05c8b63e8d9609db387f0324918f81d68fe27748f084ef092fb35954d0539a85" [[package]] name = "rusty_alloc" -version = "2.6.0" +version = "2.7.0" dependencies = [ "libc", "portable-atomic", @@ -25,7 +25,7 @@ dependencies = [ [[package]] name = "rusty_alloc-api" -version = "2.6.0" +version = "2.7.0" dependencies = [ "rusty_alloc", ] diff --git a/tools/wasm-size-baseline.txt b/tools/wasm-size-baseline.txt index e4c2941..463c418 100644 --- a/tools/wasm-size-baseline.txt +++ b/tools/wasm-size-baseline.txt @@ -1 +1 @@ -21432 +22239