Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 6 additions & 6 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
260 changes: 132 additions & 128 deletions README.md

Large diffs are not rendered by default.

29 changes: 29 additions & 0 deletions bench/issue63/adj.py
Original file line number Diff line number Diff line change
@@ -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} %")
96 changes: 96 additions & 0 deletions bench/issue63/allocator-trace-and-step.patch
Original file line number Diff line number Diff line change
@@ -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));
+}
32 changes: 32 additions & 0 deletions bench/issue63/cgsum.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
"""cgsum.py <callgrind out> [<second>]: 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,}")
59 changes: 59 additions & 0 deletions bench/issue63/ci-linux.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
#!/usr/bin/env bash
# Local mirror of the Linux CI jobs. usage: ci-linux.sh <tree> <tag>
. /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"
Loading
Loading