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
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
//! Dynamic memory management for lock-free data structures.
//!
//! This library implements the [_hazard pointer memory reclamation mechanism_][hazptr],
//! specifically as proposed for the [C++ Concurrency Technical Specification][cts]. It is adapted
//! from the [implementation][folly-hazptr] found in Facebook's [Folly library][folly]. The initial
//! phases of implementation were all [live streamed].
//!
//! At a high level, hazard pointers provide a mechanism that allows readers of shared pointers to
//! prevent concurrent reclamation of the pointed-to objects by concurrent writers for as long as
//! the read operation is ongoing. When a writer removes an object from a data structure, it
//! instructs the hazard pointer library that said object is no longer reachable (that it is
//! _retired_), and that the library should eventually drop said object (_reclaim_ it) once it is
//! safe to do so. Readers, meanwhile, inform the library any time they wish to read through a
//! pointer shared with writers. Internally, the library notes down the address that was read in
//! such a way that it can ensure that if the pointed-to object is retired while the reader still
//! has access to it, it is not reclaimed. Only once the reader no longer has access to the read
//! pointer does the library allow the object to be reclaimed.
//!
//! TODO: Can also help with the ABA problem (ensure object isn't reused until there are no
//! pointers to it, so cannot "see" A again until there are no As left).
//!
//! For an overview of concurrent garbage collection with hazard pointers, see "_[Fearless
//! concurrency with hazard pointers]_". Aaron Turon post on "_[Lock-freedom without garbage
//! collection]_" which discusses the alternate approach of using epoch-based reclamation (see
//! below) is also a good reference.
//!
//! # High-level API structure
//!
//! TODO: Ref section 3 of [the proposal][cts] and [folly's docs][folly-hazptr].
//!
//! # Hazard pointers vs. other deferred reclamation mechanisms
//!
//! TODO: Ref sections 3.4 and 4 of [the proposal][cts] and [section from folly's
//! docs](https://github.com/facebook/folly/blob/594b7e770176003d0f6b4cf725dd02a09cba533c/folly/synchronization/Hazptr.h#L139).
//!
//! Note esp. [memory usage](https://github.com/facebook/folly/blob/594b7e770176003d0f6b4cf725dd02a09cba533c/folly/synchronization/Hazptr.h#L120).
//!
//! # Examples
//!
//! TODO: Ref section 5 of [the proposal][cts] and [example from folly's
//! docs](https://github.com/facebook/folly/blob/594b7e770176003d0f6b4cf725dd02a09cba533c/folly/synchronization/Hazptr.h#L76).
//!
//! ```
//! use haphazard::{AtomicPtr, Domain, HazardPointer};
//!
//! // First, create something that's intended to be concurrently accessed.
//! let x = AtomicPtr::from(Box::new(42));
//!
//! // All reads must happen through a hazard pointer, so make one of those:
//! let mut h = HazardPointer::new();
//!
//! // We can now use the hazard pointer to read from the pointer without
//! // worrying about it being deallocated while we read.
//! let my_x = x.safe_load(&mut h).expect("not null");
//! assert_eq!(*my_x, 42);
//!
//! // We can willingly give up the guard to allow writers to reclaim the Box.
//! h.reset_protection();
//! // Doing so invalidates the reference we got from .load:
//! // let _ = *my_x; // won't compile
//!
//! // Hazard pointers can be re-used across multiple reads.
//! let my_x = x.safe_load(&mut h).expect("not null");
//! assert_eq!(*my_x, 42);
//!
//! // Dropping the hazard pointer releases our guard on the Box.
//! drop(h);
//! // And it also invalidates the reference we got from .load:
//! // let _ = *my_x; // won't compile
//!
//! // Multiple readers can access a value at once:
//!
//! let mut h = HazardPointer::new();
//! let my_x = x.safe_load(&mut h).expect("not null");
//!
//! let mut h_tmp = HazardPointer::new();
//! let _ = x.safe_load(&mut h_tmp).expect("not null");
//! drop(h_tmp);
//!
//! // Writers can replace the value, but doing so won't reclaim the old Box.
//! let old = x.swap(Box::new(9001)).expect("not null");
//!
//! // New readers will see the new value:
//! let mut h2 = HazardPointer::new();
//! let my_x2 = x.safe_load(&mut h2).expect("not null");
//! assert_eq!(*my_x2, 9001);
//!
//! // And old readers can still access the old value:
//! assert_eq!(*my_x, 42);
//!
//! // The writer can retire the value old readers are seeing.
//! //
//! // Safety: this value has not been retired before.
//! unsafe { old.retire() };
//!
//! // Reads will continue to work fine, as they're guarded by the hazard.
//! assert_eq!(*my_x, 42);
//!
//! // Even if the writer actively tries to reclaim retired objects, the hazard makes readers safe.
//! let n = Domain::global().eager_reclaim();
//! assert_eq!(n, 0);
//! assert_eq!(*my_x, 42);
//!
//! // Only once the last hazard guarding the old value goes away will the value be reclaimed.
//! drop(h);
//! let n = Domain::global().eager_reclaim();
//! assert_eq!(n, 1);
//!
//! // Remember to also retire the item stored in the AtomicPtr when it's dropped
//! // (assuming of course that the pointer is not shared elsewhere):
//! unsafe { x.retire(); }
//! ```
//!
//! # Differences from the specification
//!
//! # Differences from the folly
//!
//! TODO: Note differences from spec and from folly. Among other things, see [this note from
//! folly](https://github.com/facebook/folly/blob/594b7e770176003d0f6b4cf725dd02a09cba533c/folly/synchronization/Hazptr.h#L193).
//!
//!
//! [hazptr]: https://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.395.378&rep=rep1&type=pdf
//! [cts]: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2021/p1121r3.pdf
//! [folly-hazptr]: https://github.com/facebook/folly/blob/main/folly/synchronization/Hazptr.h
//! [folly]: https://github.com/facebook/folly
//! [live streamed]: https://www.youtube.com/watch?v=fvcbyCYdR10&list=PLqbS7AVVErFgO7RUIC6lhd0UekFMbjJzb
//! [Fearless concurrency with hazard pointers]: https://web.archive.org/web/20210306120313/https://ticki.github.io/blog/fearless-concurrency-with-hazard-pointers/
//! [Lock-freedom without garbage collection]: https://aturon.github.io/blog/2015/08/27/epoch/
// TODO: Incorporate doc strings around expectations from section 6 of the hazptr TS2 proposal.
extern crate alloc;
/// Raw building blocks for managing hazard pointers.
use PhantomData;
use Deref;
use DerefMut;
use NonNull;
use Ordering;
pub use Domain;
pub use Global;
pub use Singleton;
pub use ;
/// A managed pointer type which can be safely shared between threads.
///
/// This type has the same in-memory representation as a [`std::sync::atomic::AtomicPtr`], but
/// provides additional functionality and stricter guarantees:
///
/// - `haphazard::AtomicPtr` can safely load `&T` directly, and ensure that the referenced `T` is
/// not deallocated until the `&T` is dropped, even in the presence of concurrent writers.
/// - All loads and stores on this type use `Acquire` and `Release` semantics.
///
/// **Note:** This type is only available on platforms that support atomic loads and stores of
/// pointers. Its size depends on the target pointer’s size.
///
/// # Basic usage
///
/// To construct one, use [`AtomicPtr::from`]:
///
/// ```rust
/// # use haphazard::AtomicPtr;
/// let ptr: AtomicPtr<usize> = AtomicPtr::from(Box::new(42));
///
/// // Remember to retire the item stored in the AtomicPtr when it's dropped
/// // (assuming of course that the pointer is not also shared elsewhere):
/// unsafe { ptr.retire(); }
/// ```
///
/// Note the explicit use of `AtomicPtr<usize>`, which is needed to get the default values for the
/// generic arguments `F` and `P`, the domain family and pointer types of the stored values.
/// Families are discussed in the documentation for [`Domain`]. The pointer type `P`, which must
/// implement [`raw::Pointer`], is the type originaly used to produce the stored pointer. This is
/// used to ensure that when writers drop a value, it is dropped using the appropriate `Drop`
/// implementation.
///
/// **Warning:** When this type is dropped, it does _not_ automatically retire the object it is
/// currently pointing to. In order to retire (and eventually reclaim) that object, use
/// [`AtomicPtr::retire`] or [`AtomicPtr::retire_in`].
///
// The unsafe constract enforced throughout this crate is that a given `AtomicPtr<T, F, P>` only
// ever holds the address of a valid `T` allocated through `P` from a domain with family `F`, or
// `null`. This generally means that there are a fair few safety constraints on _writes_ to an
// `AtomicPtr`, but very few safety constraints on _reads_. This is intentional, with the
// assumption being that most consumers will read in more places than they write.
//
// Also, when working with this code, keep in mind that `AtomicPtr<T>` does not _own_ its `T`. It
// is entirely possible for an application to have multiple `AtomicPtr<T>` that all point to the
// _same_ `T`. This is why most of the safety docs refer to "load from any AtomicPtr".
//
// TODO:
// - copy_and_move test.
// - requires double-retire protection?
>,
);
// # Safety
//
// It's safe to give away ownership of an AtomicPtr to a different thread, because it holds no
// state that would be invalidated by giving ownership to another thread. Basically, this type is
// Sync because std::sync::atomic::AtomicPtr is Sync.
unsafe
// # Safety
//
// It's safe to share an AtomicPtr between threads, because it internally ensures that such
// accesses are correctly coordinated by using the atomic instructions of AtomicPtr. Furthermore,
// all the accessors of `AtomicPtr` that yield `&T` ensure that `T: Sync`, and any that retire `T`
// (and thus may take ownership of one) ensure that `T: Send`.
unsafe
/// A `*mut T` that was previously stored in an [`AtomicPtr`].
///
/// This type exists primarily to capture the family and pointer type of the [`AtomicPtr`] the
/// value was previously stored in, so that callers don't need to provide `F` and `P` to
/// [`Replaced::retire`] and [`Replaced::retire_in`].
///
/// This type has the same in-memory representation as a [`std::ptr::NonNull`](core::ptr::NonNull).