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
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
use crate::cfg::trace;
use crate::tls::ThreadLocal;
use crate::utils::CachePadded;
use crate::{Link, Linked};
use std::cell::UnsafeCell;
use std::mem::ManuallyDrop;
use std::num::NonZeroU64;
use std::ptr;
use std::sync::atomic::{AtomicPtr, AtomicU64, AtomicUsize, Ordering};
pub struct Collector {
pub(crate) epoch: AtomicU64,
reservations: ThreadLocal<CachePadded<Reservation>>,
batches: ThreadLocal<UnsafeCell<CachePadded<Batch>>>,
node_count: ThreadLocal<UnsafeCell<u64>>,
pub(crate) epoch_frequency: Option<NonZeroU64>,
pub(crate) batch_size: usize,
}
impl Collector {
pub fn with_threads(threads: usize, epoch_frequency: NonZeroU64, batch_size: usize) -> Self {
Self {
epoch: AtomicU64::new(1),
reservations: ThreadLocal::with_capacity(threads),
batches: ThreadLocal::with_capacity(threads),
node_count: ThreadLocal::with_capacity(threads),
epoch_frequency: Some(epoch_frequency),
batch_size,
}
}
pub fn node(&self) -> Node {
let count = self.node_count.get_or(Default::default).get();
unsafe {
*count += 1;
trace!("allocated new value, values: {}", *count);
if let Some(ref epoch_frequency) = self.epoch_frequency {
if *count % epoch_frequency.get() == 0 {
let _epoch = self.epoch.fetch_add(1, Ordering::Relaxed);
trace!("advancing global epoch to {}", _epoch + 1);
}
}
}
Node {
reclaim: |_| {},
batch_link: ptr::null_mut(),
reservation: ReservationNode {
birth_epoch: self.epoch.load(Ordering::Relaxed),
},
batch: BatchNode {
ref_count: ManuallyDrop::new(AtomicUsize::new(0)),
},
}
}
pub fn enter(&self) {
self.reservations
.get_or(Default::default)
.head
.swap(ptr::null_mut(), Ordering::Acquire);
}
pub fn protect<T>(&self, ptr: &AtomicPtr<T>, ordering: Ordering) -> *mut T {
trace!("protecting pointer");
if self.epoch_frequency.is_none() {
return ptr.load(ordering);
}
let reservation = self.reservations.get_or(Default::default);
let mut prev_epoch = reservation.epoch.load(Ordering::Relaxed);
loop {
let ptr = ptr.load(ordering);
let current_epoch = self.epoch.load(Ordering::Relaxed);
if prev_epoch == current_epoch {
return ptr;
} else {
trace!(
"updating epoch for from {} to {}",
prev_epoch,
current_epoch
);
reservation.epoch.swap(current_epoch, Ordering::Acquire);
prev_epoch = current_epoch;
}
}
}
pub unsafe fn delayed_retire<T>(
&self,
ptr: *mut Linked<T>,
reclaim: unsafe fn(Link),
) -> (bool, &mut Batch) {
trace!("retiring pointer");
let batch = &mut *self.batches.get_or(Default::default).get();
let node = UnsafeCell::raw_get(ptr::addr_of_mut!((*ptr).node));
(*node).reclaim = reclaim;
if batch.head.is_null() {
batch.tail = node;
if self.epoch_frequency.is_none() {
(*batch.tail).reservation.min_epoch = 0;
}
} else {
if (*batch.tail).reservation.min_epoch > (*node).reservation.birth_epoch {
(*batch.tail).reservation.min_epoch = (*node).reservation.birth_epoch;
}
(*node).batch_link = batch.tail;
(*node).batch.next = batch.head;
}
batch.head = node;
batch.size += 1;
(batch.size % self.batch_size == 0, batch)
}
pub unsafe fn retire_batch(&self) {
self.retire(&mut *self.batches.get_or(Default::default).get());
}
pub unsafe fn retire(&self, batch: &mut Batch) {
trace!("attempting to retire batch");
(*batch.tail).batch_link = batch.head;
let mut last = batch.head;
for reservation in self.reservations.iter() {
let head = &reservation.head as *const AtomicPtr<_> as *const AtomicUsize;
if (*head).fetch_add(0, Ordering::Acquire) as *mut Node == Node::INACTIVE {
continue;
}
if reservation.epoch.fetch_add(0, Ordering::Acquire)
< (*batch.tail).reservation.min_epoch
{
continue;
}
if last == batch.tail {
return;
}
(*last).reservation.head = &reservation.head;
last = (*last).batch.next;
}
let mut active = 0;
let mut curr = batch.head;
while curr != last {
let list = (*curr).reservation.head;
loop {
let prev = (*list).load(Ordering::Acquire);
(*curr).reservation.next.store(prev, Ordering::Relaxed);
if (*list)
.compare_exchange_weak(prev, curr, Ordering::AcqRel, Ordering::Relaxed)
.is_ok()
{
active += 1;
break;
}
}
curr = (*curr).batch.next;
}
if (*batch.tail)
.batch
.ref_count
.fetch_add(active, Ordering::AcqRel)
.wrapping_add(active)
== 0
{
Collector::free_list(batch.tail);
}
batch.head = ptr::null_mut();
batch.size = 0;
}
pub fn leave(&self) {
trace!("marking thread as inactive");
let reservation = self.reservations.get_or(Default::default);
let head = reservation.head.swap(Node::INACTIVE, Ordering::AcqRel);
if head != Node::INACTIVE {
unsafe { Collector::traverse(head) }
}
}
pub unsafe fn flush(&self) {
trace!("flushing guard");
let reservation = self.reservations.get_or(Default::default);
let head = reservation.head.swap(ptr::null_mut(), Ordering::AcqRel);
if head != Node::INACTIVE {
Collector::traverse(head)
}
}
unsafe fn traverse(mut list: *mut Node) {
trace!("decrementing batch reference counts");
loop {
let curr = list;
if curr.is_null() {
break;
}
list = (*curr).reservation.next.load(Ordering::Relaxed);
let tail = (*curr).batch_link;
if (*tail).batch.ref_count.fetch_sub(1, Ordering::AcqRel) == 1 {
Collector::free_list(tail);
}
}
}
unsafe fn free_list(list: *mut Node) {
trace!("freeing reservation list");
let mut list = (*list).batch_link;
loop {
let node = list;
list = (*node).batch.next;
((*node).reclaim)(Link { node });
if list.is_null() {
break;
}
}
}
}
impl Drop for Collector {
fn drop(&mut self) {
trace!("dropping collector");
for batch in self.batches.iter() {
unsafe {
let batch = &mut *batch.get();
if !batch.head.is_null() {
(*batch.tail).batch_link = batch.head;
(*batch.tail).batch.next = ptr::null_mut();
Collector::free_list(batch.tail);
}
}
}
}
}
pub struct Node {
batch_link: *mut Node,
batch: BatchNode,
reservation: ReservationNode,
reclaim: unsafe fn(Link),
}
#[repr(C)]
union ReservationNode {
birth_epoch: u64,
next: ManuallyDrop<AtomicPtr<Node>>,
head: *const AtomicPtr<Node>,
min_epoch: u64,
}
#[repr(C)]
union BatchNode {
ref_count: ManuallyDrop<AtomicUsize>,
next: *mut Node,
}
impl Node {
pub const INACTIVE: *mut Node = -1_isize as usize as _;
}
#[repr(C)]
struct Reservation {
head: AtomicPtr<Node>,
epoch: AtomicU64,
}
impl Default for Reservation {
fn default() -> Self {
Reservation {
head: AtomicPtr::new(Node::INACTIVE),
epoch: AtomicU64::new(0),
}
}
}
pub struct Batch {
head: *mut Node,
tail: *mut Node,
size: usize,
}
impl Default for Batch {
fn default() -> Self {
Batch {
head: ptr::null_mut(),
tail: ptr::null_mut(),
size: 0,
}
}
}
unsafe impl Send for Batch {}
unsafe impl Sync for Batch {}