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
//! Stable pages, published once and reclaimed only under exclusive access.
use alloc::boxed::Box;
use core::marker::PhantomData;
use core::ptr;
use super::atomic::{AtomicPtr, Ordering};
#[cfg(not(loom))]
const BASE: usize = 32;
#[cfg(loom)]
const BASE: usize = 2;
pub(crate) struct Spine<P, const CHUNKS: usize> {
chunks: [AtomicPtr<AtomicPtr<P>>; CHUNKS],
owner: PhantomData<Box<P>>,
}
// SAFETY: the directory owns its pages; moving it transfers that ownership,
// and no page reference can outlive the borrow of the directory.
unsafe impl<P: Send, const CHUNKS: usize> Send for Spine<P, CHUNKS> {}
// SAFETY: shared operations only publish immutable ownership links; pages
// are shared as &P, and a losing installer may drop its own unpublished P.
unsafe impl<P: Send + Sync, const CHUNKS: usize> Sync for Spine<P, CHUNKS> {}
impl<P, const CHUNKS: usize> Spine<P, CHUNKS> {
#[cfg(not(loom))]
pub(crate) const fn new() -> Self {
Self {
chunks: [const { AtomicPtr::new(ptr::null_mut()) }; CHUNKS],
owner: PhantomData,
}
}
#[cfg(loom)]
pub(crate) fn new() -> Self {
Self {
chunks: core::array::from_fn(|_| AtomicPtr::new(ptr::null_mut())),
owner: PhantomData,
}
}
fn location(page: usize) -> Option<(usize, usize)> {
// Equivalent to log2(page + BASE), without overflowing near usize::MAX.
let group = (page / BASE).checked_add(1)?;
let k = group.ilog2() as usize;
if k >= CHUNKS {
return None;
}
let size = BASE.checked_mul(1usize.checked_shl(k as u32)?)?;
Some((k, page - (size - BASE)))
}
pub(crate) fn get(&self, page: usize) -> Option<&P> {
let (k, offset) = Self::location(page)?;
// Acquire pairs with chunk publication, including all initialized cells.
let chunk = self.chunks[k].load(Ordering::Acquire);
if chunk.is_null() {
return None;
}
// SAFETY: an installed chunk has BASE << k initialized cells, offset
// is within it, and chunks cannot be freed during this shared borrow.
let cell = unsafe { &*chunk.wrapping_add(offset) };
// Acquire pairs with page publication, making its initialization visible.
let page = cell.load(Ordering::Acquire);
// SAFETY: non-null installed pointers own initialized P values which
// remain allocated for the entire shared borrow of this directory.
unsafe { page.as_ref() }
}
pub(crate) fn get_or_insert_with(&self, page: usize, make: impl FnOnce() -> Box<P>) -> &P {
let (k, offset) = Self::location(page).expect("Spine: page exceeds directory capacity");
// Acquire observes the initialization published by another installer.
let mut chunk = self.chunks[k].load(Ordering::Acquire);
if chunk.is_null() {
let cells: Box<[_]> = (0..(BASE << k))
.map(|_| AtomicPtr::<P>::default())
.collect();
let raw = Box::into_raw(cells) as *mut AtomicPtr<P>;
// Release publishes all cells; Acquire on either outcome observes
// the winner's initialized chunk. Only null -> non-null is shared.
chunk = match self.chunks[k].compare_exchange(
ptr::null_mut(),
raw,
Ordering::AcqRel,
Ordering::Acquire,
) {
Ok(_) => raw,
Err(winner) => {
let slice = ptr::slice_from_raw_parts_mut(raw, BASE << k);
// SAFETY: this losing allocation was never published; its
// pointer and length are exactly those of the original Box.
drop(unsafe { Box::from_raw(slice) });
winner
}
};
}
// SAFETY: the initialized chunk is installed, offset is in bounds,
// and shared borrows prevent its reclamation.
let cell = unsafe { &*chunk.wrapping_add(offset) };
// Acquire observes any page already published in this cell.
let mut installed = cell.load(Ordering::Acquire);
if installed.is_null() {
let raw = Box::into_raw(make());
// Release publishes P; Acquire observes the winning P on failure.
installed = match cell.compare_exchange(
ptr::null_mut(),
raw,
Ordering::AcqRel,
Ordering::Acquire,
) {
Ok(_) => raw,
Err(winner) => {
// SAFETY: the losing Box<P> was never published and this
// thread still owns its sole allocation pointer.
drop(unsafe { Box::from_raw(raw) });
winner
}
};
}
// SAFETY: either CAS outcome supplies an initialized, installed P;
// installed pages cannot be reclaimed during this shared borrow.
unsafe { &*installed }
}
/// Installed pages in ascending order, weakly consistent across pages.
pub(crate) fn iter(&self) -> impl Iterator<Item = (usize, &P)> {
self.chunks.iter().enumerate().flat_map(move |(k, cell)| {
// Acquire observes publication; chunks remain installed while shared.
let len = if cell.load(Ordering::Acquire).is_null() {
0
} else {
BASE << k
};
(0..len).filter_map(move |offset| {
let number = (BASE << k) - BASE + offset;
self.get(number).map(|page| (number, page))
})
})
}
/// Installed pages in ascending order, with exclusive access to each.
pub(crate) fn iter_mut(&mut self) -> impl Iterator<Item = (usize, &mut P)> {
// The adapter below only stores atomic pointers, which are `Send`
// and `Sync` whatever `P` is. The marker ties the iterator's auto
// traits to `&mut P`, which it hands out.
ExclusivePages {
inner: self.iter_mut_raw(),
marker: PhantomData,
}
}
fn iter_mut_raw(&mut self) -> impl Iterator<Item = (usize, &mut P)> {
self.chunks.iter_mut().enumerate().flat_map(|(k, cell)| {
// Relaxed suffices: exclusive access rules out publication races.
let chunk = cell.load(Ordering::Relaxed);
let len = if chunk.is_null() { 0 } else { BASE << k };
let cells = if len == 0 {
&mut [][..]
} else {
// SAFETY: this installed allocation contains len cells; &mut
// self excludes every other reference into its pages or cells.
unsafe { core::slice::from_raw_parts_mut(chunk, len) }
};
cells
.iter_mut()
.enumerate()
.filter_map(move |(offset, cell)| {
// Relaxed suffices under the directory's exclusive borrow.
let page = cell.load(Ordering::Relaxed);
// SAFETY: installed pages are distinct owned Boxes; exclusive
// iteration visits each cell once and prevents shared access.
unsafe { page.as_mut() }.map(|page| ((BASE << k) - BASE + offset, page))
})
})
}
/// Takes page `page` out of the directory under exclusive access. Its
/// chunk stays allocated. A later shared `get_or_insert_with` may install
/// a new page there.
pub(crate) fn remove(&mut self, page: usize) -> Option<Box<P>> {
let (k, offset) = Self::location(page)?;
// Relaxed suffices: exclusive access rules out readers/installers.
let chunk = self.chunks[k].load(Ordering::Relaxed);
if chunk.is_null() {
return None;
}
// SAFETY: an installed chunk has BASE << k initialized cells, offset
// is within it, and &mut self excludes every other access.
let cell = unsafe { &*chunk.wrapping_add(offset) };
// Relaxed suffices under the directory's exclusive borrow.
let raw = cell.swap(ptr::null_mut(), Ordering::Relaxed);
if raw.is_null() {
return None;
}
// SAFETY: a non-null cell uniquely owns one Box<P>; the swap above
// unlinked it, and exclusive access ends every borrow of it.
Some(unsafe { Box::from_raw(raw) })
}
/// Frees every page and chunk, including after one page destructor panics.
pub(crate) fn clear(&mut self) {
Reclaim {
chunks: &mut self.chunks,
next_chunk: 0,
cells: None,
next_page: 0,
}
.drain();
}
}
/// Owns the detached chunk and tracks progress before each page drop.
struct Reclaim<'a, P> {
chunks: &'a mut [AtomicPtr<AtomicPtr<P>>],
next_chunk: usize,
cells: Option<Box<[AtomicPtr<P>]>>,
next_page: usize,
}
impl<P> Reclaim<'_, P> {
fn drain(&mut self) {
loop {
if let Some(cells) = &self.cells {
while let Some(cell) = cells.get(self.next_page) {
self.next_page += 1;
// Relaxed suffices under exclusive access.
let page = cell.load(Ordering::Relaxed);
if !page.is_null() {
// SAFETY: this cell owns a distinct Box<P> in the
// detached chunk. Advancing first prevents a second
// drop of this page if its destructor panics.
drop(unsafe { Box::from_raw(page) });
}
}
self.cells = None;
}
let k = self.next_chunk;
let Some(cell) = self.chunks.get_mut(k) else {
break;
};
self.next_chunk += 1;
// Relaxed suffices: exclusive access rules out readers/installers.
let raw = cell.swap(ptr::null_mut(), Ordering::Relaxed);
if !raw.is_null() {
let slice = ptr::slice_from_raw_parts_mut(raw, BASE << k);
// SAFETY: the swap transferred the sole ownership of this
// allocation, which contains exactly BASE << k cells.
self.cells = Some(unsafe { Box::from_raw(slice) });
self.next_page = 0;
}
}
}
}
impl<P> Drop for Reclaim<'_, P> {
fn drop(&mut self) {
self.drain();
}
}
/// Carries `&mut P`'s auto traits for [`Spine::iter_mut`].
struct ExclusivePages<'a, P, I> {
inner: I,
marker: PhantomData<&'a mut P>,
}
impl<'a, P: 'a, I: Iterator<Item = (usize, &'a mut P)>> Iterator for ExclusivePages<'a, P, I> {
type Item = (usize, &'a mut P);
fn next(&mut self) -> Option<Self::Item> {
self.inner.next()
}
}
impl<P, const CHUNKS: usize> Drop for Spine<P, CHUNKS> {
fn drop(&mut self) {
self.clear();
}
}