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
use std::alloc::{Layout, alloc, dealloc};
use std::mem::forget;
use std::panic::catch_unwind;
use std::ptr::{null, null_mut};
use std::sync::atomic::AtomicPtr;
use std::sync::atomic::Ordering::{AcqRel, Acquire, Relaxed, Release};
use super::collector::Collector;
use super::link::Link;
use super::ref_counted::RefCounted;
use super::{Guard, Owned, Shared};
/// Private garbage collector to limit the lifetime of allocated memory chunks.
///
/// When the [`PrivateCollector`] is dropped, it performs an aggressive reclamation; it deallocates
/// all remaining memory chunks that it has collected in its lifetime without ensuring that there
/// are no active [`Ptr`](super::Ptr) or [`RawPtr`](super::RawPtr) pointing to any of the memory
/// chunks.
///
/// # Safety
///
/// Using [`PrivateCollector`] for types that do not implement [`Send`] is unsafe, as their
/// instances may be dropped on an arbitrary thread. See [`collect_owned`](Self::collect_owned) and
/// [`collect_shared`](Self::collect_shared) for more safety notes.
pub struct PrivateCollector {
/// [`SharedGarbageBag`] that is shared among multiple threads.
///
/// While the thread-local [`Collector`] handles most retirements, the [`SharedGarbageBag`] acts
/// as a secondary storage for memory chunks that failed to be collected locally, e.g., due to
/// memory allocation failure.
shared_garbage_bag: AtomicPtr<SharedGarbageBag>,
/// Backup garbage bag in case heap allocation fails.
backup_garbage_bag: AtomicPtr<Link>,
}
/// A lock-free, singly-linked list of [`Link`] used to temporarily hold retired memory chunks.
pub(super) struct SharedGarbageBag(AtomicPtr<Link>);
impl PrivateCollector {
/// Creates a new [`PrivateCollector`].
///
/// # Examples
///
/// ```
/// use sdd::PrivateCollector;
///
/// let private_collector = PrivateCollector::new();
/// ```
#[inline]
#[must_use]
pub const fn new() -> Self {
Self {
shared_garbage_bag: AtomicPtr::new(null_mut()),
backup_garbage_bag: AtomicPtr::new(null_mut()),
}
}
/// Collects the memory owned by the supplied [`Owned`].
///
/// # Safety
///
/// This method is unsafe because it manually manages the lifetime of the underlying memory. The
/// caller must ensure that the [`PrivateCollector`] is not dropped while any
/// [`Ptr`](super::Ptr) or [`RawPtr`](super::RawPtr) still point to the memory held by the
/// [`Owned`].
///
/// Additionally, `T` must implement [`Send`] because its instances may be dropped on an
/// arbitrary thread: for example, when the [`PrivateCollector`] is moved across threads or
/// shared among multiple threads. The [`Send`] constraint is intentionally not enforced at
/// compile time for more flexibility.
///
///
/// # Examples
///
/// ```
/// use sdd::{Guard, Owned, PrivateCollector};
///
/// let private_collector = PrivateCollector::new();
/// let owned = Owned::new(10);
///
/// unsafe { private_collector.collect_owned(owned, &Guard::new()); }
/// ```
#[inline]
pub unsafe fn collect_owned<T>(&self, owned: Owned<T>, guard: &Guard) {
let ptr = RefCounted::link_ptr(owned.underlying_ptr()).cast_mut();
forget(owned);
self.push(ptr, guard);
}
/// Collects the supplied [`Shared`].
///
/// Returns `true` if the last reference was dropped and the memory was successfully collected.
///
/// # Safety
///
/// This method is unsafe because it manually manages the lifetime of the underlying memory. The
/// caller must ensure that the [`PrivateCollector`] is not dropped while any
/// [`Ptr`](super::Ptr) or [`RawPtr`](super::RawPtr) still point to the memory held by the
/// [`Shared`].
///
/// Additionally, `T` must implement [`Send`] because its instances may be dropped on an
/// arbitrary thread: for example, when the [`PrivateCollector`] is moved across threads or
/// shared among multiple threads. The [`Send`] constraint is intentionally not enforced at
/// compile time for more flexibility.
///
/// # Examples
///
/// ```
/// use sdd::{Guard, PrivateCollector, Shared};
///
/// let private_collector = PrivateCollector::new();
/// let shared = Shared::new(10);
///
/// let collected = unsafe { private_collector.collect_shared(shared, &Guard::new()) };
/// assert!(collected);
/// ```
#[inline]
#[must_use]
pub unsafe fn collect_shared<T>(&self, shared: Shared<T>, guard: &Guard) -> bool {
let ptr = shared.underlying_ptr();
forget(shared);
if unsafe { (*ptr).drop_ref() } {
self.push(RefCounted::link_ptr(ptr).cast_mut(), guard);
true
} else {
false
}
}
/// Pushes a [`Link`] into its [`SharedGarbageBag`].
#[inline]
fn push(&self, ptr: *mut Link, guard: &Guard) {
let mut shared_garbage_bag = self.shared_garbage_bag.load(Acquire).cast_const();
if shared_garbage_bag.is_null() {
shared_garbage_bag = self.alloc();
}
if !shared_garbage_bag.is_null()
&& catch_unwind(|| guard.collect(ptr, shared_garbage_bag)).is_ok()
{
return;
}
self.fallback(ptr);
}
/// Allocates a [`SharedGarbageBag`].
#[inline(never)]
fn alloc(&self) -> *const SharedGarbageBag {
let Ok(allocated) = catch_unwind(|| {
let shared_garbage_bag = self.shared_garbage_bag.load(Acquire);
if !shared_garbage_bag.is_null() {
return shared_garbage_bag;
}
#[allow(clippy::cast_ptr_alignment)]
let allocated =
unsafe { alloc(Layout::new::<SharedGarbageBag>()).cast::<SharedGarbageBag>() };
assert!(!allocated.is_null(), "Memory allocation failed");
unsafe {
allocated.write(SharedGarbageBag(AtomicPtr::new(null_mut())));
}
match self
.shared_garbage_bag
.compare_exchange(null_mut(), allocated, AcqRel, Acquire)
{
Ok(_) => allocated,
Err(actual) => {
unsafe {
dealloc(allocated.cast::<u8>(), Layout::new::<SharedGarbageBag>());
}
actual
}
}
}) else {
return null();
};
// Move any memory chunks stored in the backup garbage bag to the shared bag.
let head = self.backup_garbage_bag.swap(null_mut(), Acquire);
let mut tail = head;
if !tail.is_null() {
loop {
let next = unsafe { (*tail).next_ptr(Relaxed) };
if next.is_null() {
break;
}
tail = next;
}
let result = unsafe {
(*allocated)
.0
.fetch_update(Release, Relaxed, |head_ptr| {
(*tail).set_next_ptr(head_ptr, Relaxed);
Some(head)
})
.is_ok()
};
debug_assert!(result);
}
allocated
}
/// Falls back to using a shared/backup garbage bag.
#[cold]
#[inline(never)]
fn fallback(&self, ptr: *mut Link) {
let shared_garbage_bag = self.shared_garbage_bag.load(Acquire);
let garbage_bag = if shared_garbage_bag.is_null() {
&self.backup_garbage_bag
} else {
unsafe { &(*shared_garbage_bag).0 }
};
let result = garbage_bag
.fetch_update(Release, Relaxed, |head_ptr| unsafe {
(*ptr).set_next_ptr(head_ptr, Relaxed);
Some(ptr)
})
.is_ok();
debug_assert!(result);
// Call `alloc` again in case a `SharedGarbageBag` was allocated right before pushing the
// pointer into the backup bag.
self.alloc();
}
}
impl Default for PrivateCollector {
#[inline]
fn default() -> Self {
Self::new()
}
}
impl Drop for PrivateCollector {
#[inline]
fn drop(&mut self) {
let shared_garbage_bag = self.shared_garbage_bag.swap(null_mut(), Acquire);
if !shared_garbage_bag.is_null() {
let guard = Guard::new();
guard.purge(shared_garbage_bag);
let link = unsafe { (*shared_garbage_bag).0.swap(null_mut(), Acquire) };
Collector::dealloc(link);
unsafe {
shared_garbage_bag.drop_in_place();
dealloc(
shared_garbage_bag.cast::<u8>(),
Layout::new::<SharedGarbageBag>(),
);
}
}
let link = self.backup_garbage_bag.swap(null_mut(), Acquire);
Collector::dealloc(link);
}
}
impl SharedGarbageBag {
/// Exports memory chunks.
///
/// Returns the head, tail pointers and the length of the linked list.
#[inline]
pub(super) fn export(&self) -> (*mut Link, *mut Link, usize) {
let Ok(head) = self.0.fetch_update(Relaxed, Acquire, |ptr| {
if ptr.is_null() {
None
} else {
Some(null_mut())
}
}) else {
return (null_mut(), null_mut(), 0);
};
let mut tail = head;
let mut link_len = 1;
loop {
let next = unsafe { (*tail).next_ptr(Relaxed) };
if next.is_null() {
break;
}
link_len += 1;
tail = next;
}
(head, tail, link_len)
}
}