1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
//! [`Registry`] — the bootstrap outcome: a process-global, self-hosted slot
//! array plus its dynamic atomics, initialised exactly once via a hand-rolled
//! atomic state-machine (NOT `std::sync::Once`, which may allocate).
//!
//! ## The discipline (reused from `bootstrap::primordial`)
//!
//! The Phase 8 primordial bootstrap (`alloc_core::bootstrap::primordial`)
//! hand-carves the `SegmentTable` from a freshly-reserved segment: one OS
//! reservation, then safe composition over its bytes via the `node` seam. The
//! registry reuses that discipline's SHAPE — allocation-free init guarded by
//! an atomic state-machine — but NOW stores the slot array in a
//! HEAP-ALLOCATED reservation obtained via `aligned_vmem::reserve_aligned`
//! (a direct OS syscall, NOT `std::alloc`) rather than a `static`.
//!
//! ## Why lazy heap-allocation instead of a `static`?
//!
//! The original design used `static REGISTRY: Registry = Registry::new_zeroed()`.
//! `HeapSlot::new_uninit()` initialises `next_free` to `u32::MAX` (NEXT_FREE_TAIL),
//! a non-zero value, which forces the ENTIRE 22 MB slot array into `.data`
//! instead of `.bss`. With `MAX_HEAPS = 4096` and ~5 KiB per `HeapCore` slot,
//! this added ~22 MB to every binary that linked sefer-alloc with the
//! `production` feature.
//!
//! The fix: replace the `static` with an `AtomicPtr<Registry>` (8 bytes of
//! `.data`). On first call to [`ensure`], the winner of a CAS race allocates
//! `size_of::<Registry>()` bytes via `aligned_vmem::reserve_aligned` (a direct
//! OS `VirtualAlloc`/`mmap` syscall — M5-clean, no `std::alloc`) and writes
//! `Registry::new_zeroed()` into it in place, then publishes the pointer with
//! a Release store. The reservation is leaked for the process lifetime (the
//! registry is process-global, never torn down). After that, every call is a
//! single Acquire load + non-null, non-sentinel check — branch-light and
//! allocation-free.
//!
//! ## The pointer state-machine
//!
//! `AtomicPtr<Registry>` drives the `UNINIT → INITIALIZING → READY` transition
//! via pointer values:
//!
//! | Pointer value | Meaning |
//! |---|---|
//! | `null` | `UNINIT` — not yet initialised |
//! | `SENTINEL_INITIALIZING` (`1 as *mut`) | `INITIALIZING` — one thread won the CAS and is allocating |
//! | real `*mut Registry` | `READY` — fully initialised; safe to dereference |
//!
//! 1. The first caller observes `null` and CASes it to `SENTINEL_INITIALIZING`.
//! The CAS winner:
//! a. Calls `aligned_vmem::reserve_aligned(SIZE, ALIGN)` — direct OS syscall,
//! no `std::alloc`, no registry dependency.
//! b. Field-by-field in-place initialisation (OS zeroed-pages + fix-up of
//! non-zero fields: `next_free` per slot and `free_slots`).
//! c. `REGISTRY_PTR.store(base, Release)` — publishes the ready pointer.
//! d. `mem::forget(reservation)` — leaks the reservation intentionally; the
//! registry lives for the process lifetime.
//! 2. Concurrent losers observe `SENTINEL_INITIALIZING` (or `null`, then fail
//! the CAS) and spin until they observe a non-null, non-sentinel pointer
//! under `Acquire`. The spin window is tiny (one OS page allocation).
//! 3. After `READY`, every subsequent call is a single `Acquire` load + two
//! cheap comparisons + return.
//!
//! `Release`/`Acquire` on the pointer transition establishes happens-before
//! from the initialising thread's `ptr::write` (the registry fields) to every
//! reader that observes the real pointer, so readers see a fully constructed
//! registry.
//!
//! ## M5 (reentrancy-free) — CANNOT BE VIOLATED
//!
//! `aligned_vmem::reserve_aligned` is a direct OS syscall (`VirtualAlloc` /
//! `mmap`) — it does NOT call `std::alloc`, `Box`, `Vec`, or any other
//! Rust allocator entry point. Its dependency graph (verified by reading
//! `crates/vmem/src/lib.rs` in full):
//!
//! - Windows: `extern "system" { fn VirtualAlloc(...) }` — no std alloc.
//! - Unix: `extern "C" { fn mmap(...) }` — no std alloc.
//! - Miri: `std::alloc` — but under miri we are NOT the global allocator
//! (the host miri allocator backs the harness), so no reentrancy.
//!
//! No path from `ensure_slow` touches `sefer_alloc::registry::*` — confirmed
//! by inspection. The reservation call chain is a straight line to a kernel
//! syscall boundary.
// This file uses `unsafe` for two operations:
// 1. Field-by-field in-place initialisation of the `Registry` object in
// freshly reserved OS memory (pointer arithmetic + writes through
// `addr_of_mut!`).
// 2. `unsafe { &*p }` — dereferencing the published pointer after observing
// it under `Acquire` (sound because the initialiser's `Release` store
// establishes happens-before).
// Every `unsafe` block carries a `// SAFETY:` proof below.
use spin_loop;
use ;
use ;
use TaggedPtr;
/// Maximum number of heaps the registry can hold. Each live thread claims one
/// slot for its heap; `recycle` returns it. 4096 is generous for realistic
/// thread counts (a process with > 4096 simultaneous threads is pathological
/// for an allocator; the cap can be raised if a measured workload needs it).
/// With lazy allocation this is now a runtime cap (size of the heap-allocated
/// slot array), NOT a `.data`/`.bss` cost — the array is allocated on first
/// use via `aligned_vmem::reserve_aligned`.
pub const MAX_HEAPS: usize = 4096;
/// The segment size used for the abandoned-segment address packing. Mirrors
/// [`crate::alloc_core::os::SEGMENT`] (kept as a literal here to avoid a
/// cross-feature dependency from the registry bootstrap — the value is
/// structural, set in `MALLOC_PLAN.md`, and a `const _: () = assert!` below
/// ties them together so they cannot drift).
const ABANDON_SEG_SHIFT: u32 = 22; // log2(4 MiB)
const ABANDON_SEG_SIZE: u64 = 1u64 << ABANDON_SEG_SHIFT;
/// Number of low bits available for the ABA tag in the abandoned-segment head
/// packing (a segment base is `ABANDON_SEG_SIZE`-aligned, so its low
/// `ABANDON_SEG_SHIFT = 22` bits are always zero — we reuse them for the tag).
const ABANDON_TAG_BITS: u32 = ABANDON_SEG_SHIFT;
pub const ABANDON_TAG_MASK: u64 = - 1;
/// Compile-time tie: if the real `SEGMENT` ever diverges from
/// `ABANDON_SEG_SIZE`, this fails to compile (the abandoned-segment packing
/// would silently corrupt high address bits). `cfg`-gated so it only fires
/// when `alloc-core` (and thus `os::SEGMENT`) is in the build graph.
const _: = assert!;
/// Pack `(base, tag)` into one `AtomicU64` head word for the
/// abandoned-segments intrusive stack. `base` MUST be SEGMENT-aligned (its low
/// `ABANDON_SEG_SHIFT` bits are zero — true for every segment base by
/// construction); the tag occupies those low bits and is bumped on every push
/// (ABA defence). The full 64-bit base is recoverable, so addresses above 4
/// GiB (ASLR) are handled correctly (the bug fixed in Phase 12.4 — FINDINGS №1).
///
/// Not `const` because `*mut u8 as u64` is not stable in `const fn` (it needs
/// `const_raw_ptr_to_int_transmute`, unstable). Runtime-only use.
/// Unpack the abandoned-segment head word back into `(base, tag)`. The base's
/// low `ABANDON_TAG_BITS` are restored to zero.
/// The empty-stack sentinel for the abandoned-segment head: base = null, tag = 0.
/// A null base unambiguously denotes "empty" (no real segment base is null).
pub const ABANDONED_HEAD_EMPTY: u64 = 0;
/// Whether an abandoned-segment head word denotes the empty stack.
/// The bootstrap outcome: the fixed slot array plus the dynamic atomics that
/// drive `claim`/`recycle`/`abandon`. Allocated via `aligned_vmem::reserve_aligned`
/// on first call to [`ensure`] (NOT by `std::alloc` — M5-clean). Lives for
/// the process lifetime (the reservation is leaked after init via `mem::forget`).
///
/// The struct is constructed in-place (via `ptr::write`) inside the OS
/// reservation; this is the same discipline as the primordial segment bootstrap.
// SAFETY (Sync): `Registry` is shared across threads via the `AtomicPtr`. All
// mutable access to its fields goes through atomics (`count`, `free_slots`,
// `abandoned_segs`) or the slot-level single-writer protocol (`slots`). The
// same argument that made the old `static REGISTRY` sound applies here.
unsafe
// -------------------------------------------------------------------------
// Lazy pointer: replaces the 22 MB `static REGISTRY: Registry`.
// -------------------------------------------------------------------------
/// Sentinel: a non-null, non-real address that means "one thread is currently
/// initialising the registry". Aligned to 1 (the raw integer 1 is not a valid
/// `Registry` pointer — `Registry` has alignment ≥ 4). Any real `*mut Registry`
/// will differ from this value and from null.
const SENTINEL_INITIALIZING: usize = 1;
/// The process-global registry pointer. Starts null (`UNINIT`).
/// Transitions: `null → SENTINEL_INITIALIZING → real *mut Registry`.
/// After the final store (Release), every subsequent load (Acquire) sees a
/// valid, fully-constructed `Registry`.
///
/// BINARY SIZE: this is 8 bytes of `.data` (one pointer). The old
/// `static REGISTRY: Registry = Registry::new_zeroed()` was ~22 MB of `.data`
/// because `HeapSlot::new_uninit()` sets `next_free = u32::MAX` (NEXT_FREE_TAIL),
/// a non-zero value that forced the full slot array into `.data` instead of `.bss`.
static REGISTRY_PTR: = new;
/// Size of `Registry` rounded up to a multiple of `aligned_vmem::PAGE` (4 KiB).
/// `reserve_aligned` requires `size` to be a non-zero multiple of `PAGE`.
const REGISTRY_SIZE: usize = ;
/// Alignment for the `reserve_aligned` call. `Registry`'s natural alignment is
/// at most 8 bytes (its largest-aligned field is `AtomicU64`). `reserve_aligned`
/// requires `align >= PAGE` (4 KiB), so we use `PAGE` — the registry occupies
/// whole pages anyway.
const REGISTRY_ALIGN: usize = PAGE;
/// Ensure the registry is initialised, then return a `&'static` reference to
/// it. The first call performs the (M5-clean, `std::alloc`-free) OS-reservation
/// init and publication; concurrent and later calls observe the real pointer
/// under `Acquire` and return immediately.
///
/// ## Fast path (typical: already initialised)
///
/// One `Acquire` load of `REGISTRY_PTR`. If the pointer is non-null AND not the
/// sentinel, return `&*p` immediately (branch-light, allocation-free).
///
/// ## Slow path (first call or race)
///
/// See [`ensure_slow`].
/// Slow path for [`ensure`]: race to initialise the registry via a CAS on
/// `REGISTRY_PTR`. Exactly one caller wins, allocates via
/// `aligned_vmem::reserve_aligned`, constructs the `Registry` in-place, and
/// publishes the pointer. All others spin-wait on a tiny window.
/// The current high-water `count` (test introspection). Each test claims
/// fresh slots; because `count` is monotonic across the suite (we never
/// reset the slot array — that would leak the lazily-materialised
/// `HeapCore`s), a test derives its expected slot indices relative to the
/// count it observed at entry.