-
Notifications
You must be signed in to change notification settings - Fork 6
/
parc.rs
1456 lines (1326 loc) · 43.8 KB
/
parc.rs
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
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use crate::utils::SpinLock;
use std::panic::RefUnwindSafe;
use std::panic::UnwindSafe;
use crate::alloc::{MemPool, PmemUsage};
use crate::cell::VCell;
use crate::clone::*;
use crate::ptr::Ptr;
use crate::stm::*;
use crate::*;
use std::clone::Clone as StdClone;
use std::cmp::Ordering;
use std::hash::Hash;
use std::hash::Hasher;
use std::marker::PhantomData;
use std::mem::MaybeUninit;
use std::ops::Deref;
use std::sync::atomic::{self, AtomicBool, Ordering::*};
use std::*;
const MAX_REFCOUNT: usize = (isize::MAX) as usize;
struct Counter<A: MemPool> {
strong: usize,
weak: usize,
lock: VCell<u8, A>,
}
unsafe impl<A: MemPool> PSafe for Counter<A> {}
/// The [`Parc`] inner data type
///
/// It contains the atomic counters, a list of volatile references, and the
/// actual value.
///
pub struct ParcInner<T: ?Sized, A: MemPool> {
counter: Counter<A>,
#[cfg(not(feature = "no_volatile_pointers"))]
vlist: VCell<VWeakList, A>,
marker: PhantomData<A>,
value: T,
}
unsafe impl<T: PSafe + ?Sized, A: MemPool> PSafe for ParcInner<T, A> {}
impl<T: ?Sized, A: MemPool> !VSafe for ParcInner<T, A> {}
unsafe fn set_data_ptr<T, U>(mut ptr: *mut T, data: *mut U) -> *mut T {
std::ptr::write(&mut ptr as *mut _ as *mut *mut u8, data as *mut u8);
ptr
}
/// A thread-safe reference-counting persistent pointer. 'Parc' stands for
/// 'Persistent Atomically Reference Counted'.
///
/// The main aspect of `Parc<T>` is that its atomic counters are also
/// transactional to provide failure atomicity which means that functions
/// [`pclone`], [`downgrade`], and [`upgrade`] require a [`Journal`] to operate.
/// In other words, you need to wrap them in a [`transaction`]. The counters are
/// atomic, so it is safe to share it in multiple threads.
///
/// Since `Parc` uses reference counting for resource management, it inherits
/// the cyclic references problem. Please visit [`this`] for the information on
/// how [`Weak`] helps to resolve that issue.
///
/// [`this`]: ../prc/index.html#cyclic-references
///
/// Unlike [`Arc`], `Parc` does not implement [`Send`] to prevent memory leak.
/// The reason is that if a `Parc` is created in a transaction without being
/// reachable from the root object, and moves to a thread, due to being RAII,
/// its drop function gets called in the other thread outside the original
/// transaction. Therefore, it destroys allocation consistency and leaves the
/// `Parc` unreachable in the memory if a crash happens between the original
/// transaction is done and the drop function is called.
///
/// To allow sharing, `Parc` provides a safe mechanism to cross the thread
/// boundaries. When you need to share it, you can obtain a [`VWeak`]
/// object by calling [`demote()`] function. The [`VWeak`] object is both
/// [`Sync`] and [`Send`] and acts like a volatile reference. Calling
/// [`VWeak`]`::`[`promote()`] gives access to data by creating a new reference
/// of type `Parc` inside the other thread, if the referent is still available.
/// Calling [`demote()`] is dynamically prohibited to be inside a transaction.
/// Therefore, the `Parc` should be already reachable from the root object and
/// packed outside a transaction.
///
/// # Examples
///
/// ```
/// use corundum::default::*;
/// use std::thread;
///
/// type P = Allocator;
///
/// let p = P::open::<Parc<i32>>("foo.pool", O_CF).unwrap();
/// let v = p.demote();
/// let mut threads = vec![];
///
/// for i in 0..10 {
/// let p = v.clone();
/// threads.push(thread::spawn(move || {
/// transaction(|j| {
/// if let Some(p) = p.promote(j) {
/// println!("access {} from thread {}", *p, i);
/// }
/// }).unwrap();
/// }));
/// }
///
/// for t in threads {
/// t.join().unwrap();
/// }
/// ```
///
/// # Mutability
///
/// `Parc` doesn't provide mutable reference to the inner value. To allow
/// interior mutability, you may use `Parc<`[`PMutex`]`<T,P>,P>` (or in short,
/// `Parc<`[`PMutex`]`<T>>` using aliased types).
///
/// ```
/// use corundum::default::*;
/// use std::thread;
///
/// type P = Allocator;
///
/// let p = P::open::<Parc<PMutex<i32>>>("foo.pool", O_CF).unwrap();
/// let v = p.demote();
/// let mut threads = vec![];
///
/// for i in 0..10 {
/// let p = v.clone();
/// threads.push(thread::spawn(move || {
/// transaction(|j| {
/// if let Some(p) = p.promote(j) {
/// let mut p = p.lock(j);
/// *p += 1;
/// println!("thread {} makes it {}", i, *p);
/// }
/// }).unwrap();
/// }));
/// }
///
/// for t in threads {
/// t.join().unwrap();
/// }
///
/// let res = transaction(|j| {
/// *p.lock(j)
/// }).unwrap();
///
/// assert_eq!(res, 10);
/// ```
///
/// [`downgrade`]: #method.downgrade
/// [`upgrade`]: ./struct.Weak.html#method.upgrade
/// [`Journal`]: ../stm/journal/struct.Journal.html
/// [`transaction`]: ../stm/fn.transaction.html
/// [`Arc`]: std::sync::Arc
/// [`PMutex`]: ./struct.PMutex.html
/// [`PMutex`]: ../alloc/default/type.PMutex.html
/// [`pclone`]: #impl-PClone
/// [`demote()`]: #method.demote
/// [`promote()`]: ./struct.VWeak.html#method.promote
pub struct Parc<T: PSafe + ?Sized, A: MemPool> {
ptr: Ptr<ParcInner<T, A>, A>,
phantom: PhantomData<T>,
}
impl<T: ?Sized, A: MemPool> !TxOutSafe for Parc<T, A> {}
impl<T: ?Sized, A: MemPool> !Send for Parc<T, A> {}
impl<T: ?Sized, A: MemPool> !VSafe for Parc<T, A> {}
impl<T: PSafe + ?Sized, A: MemPool> UnwindSafe for Parc<T, A> {}
impl<T: PSafe + ?Sized, A: MemPool> RefUnwindSafe for Parc<T, A> {}
unsafe impl<T: PSafe + ?Sized, A: MemPool> TxInSafe for Parc<T, A> {}
impl<T: PSafe, A: MemPool> Parc<T, A> {
/// Constructs a new `Parc<T>`.
///
/// # Examples
///
/// ```
/// # use corundum::alloc::heap::*;
/// use corundum::sync::Parc;
///
/// Heap::transaction(|j| {
/// let five = Parc::new(5, j);
/// }).unwrap();
/// ```
pub fn new(value: T, journal: &Journal<A>) -> Parc<T, A> {
unsafe {
let ptr = Ptr::new_unchecked(A::new(
ParcInner::<T, A> {
counter: Counter {
strong: 1,
weak: 1,
lock: VCell::new(0),
},
#[cfg(not(feature = "no_volatile_pointers"))]
vlist: VCell::new(VWeakList::default()),
marker: PhantomData,
value,
},
journal,
));
Self::from_inner(ptr)
}
}
/// Constructs a new `Parc` with uninitialized contents.
///
/// # Examples
///
/// ```
/// use corundum::alloc::heap::*;
/// use corundum::sync::Parc;
///
/// corundum::transaction(|j| {
/// let mut five = Parc::<u32,Heap>::new_uninit(j);
///
/// let five = unsafe {
/// // Deferred initialization:
/// Parc::get_mut_unchecked(&mut five).as_mut_ptr().write(5);
///
/// five.assume_init()
/// };
///
/// assert_eq!(*five, 5)
/// }).unwrap();
/// ```
pub fn new_uninit(journal: &Journal<A>) -> Parc<MaybeUninit<T>, A> {
unsafe {
Parc::from_inner(Ptr::from_mut(A::new(
ParcInner {
counter: Counter {
strong: 1,
weak: 1,
lock: VCell::new(0),
},
#[cfg(not(feature = "no_volatile_pointers"))]
vlist: VCell::new(VWeakList::default()),
marker: PhantomData,
value: MaybeUninit::<T>::uninit(),
},
journal,
)))
}
}
/// Constructs a new `Parc` with uninitialized contents, with the memory
/// being filled with `0` bytes.
///
/// See `MaybeUninit::zeroed` for examples of correct and incorrect usage of
/// this method.
///
/// # Examples
///
/// ```
/// use corundum::alloc::heap::*;
/// use corundum::sync::Parc;
///
/// Heap::transaction(|j| {
/// let zero = Parc::<u32,Heap>::new_zeroed(j);
/// let zero = unsafe { zero.assume_init() };
///
/// assert_eq!(*zero, 0)
/// }).unwrap();
/// ```
///
pub fn new_zeroed(journal: &Journal<A>) -> Parc<mem::MaybeUninit<T>, A> {
unsafe {
let mut uninit = Self::new_uninit(journal);
std::ptr::write_bytes::<T>(Parc::get_mut_unchecked(&mut uninit).as_mut_ptr(), 0, 1);
uninit
}
}
}
impl<T: PSafe + ?Sized, A: MemPool> Parc<T, A> {
#[inline]
fn from_inner(ptr: Ptr<ParcInner<T, A>, A>) -> Self {
Parc {
ptr,
phantom: PhantomData,
}
}
#[inline(always)]
fn inner(&self) -> &mut ParcInner<T, A> {
self.ptr.get_mut()
}
#[allow(clippy::missing_safety_doc)]
unsafe fn from_ptr(ptr: *mut ParcInner<T, A>, j: &Journal<A>) -> Self {
let off = A::off_unchecked(ptr);
let res = Self::from_inner(Ptr::from_off_unchecked(off));
fetch_inc((*ptr).counter.lock.as_mut(), &mut (*ptr).counter.strong, j);
res
}
#[inline(never)]
unsafe fn drop_slow(&mut self, j: &Journal<A>) {
// Destroy the data at this time, even though we may not free the box
// allocation itself (there may still be weak pointers lying around).
std::ptr::drop_in_place(&mut self.ptr.as_mut().value);
let inner = self.inner();
if fetch_dec(inner.counter.lock.as_mut(), &mut inner.counter.weak, j) == 1 {
atomic::fence(Acquire);
A::free(self.ptr.as_mut());
#[cfg(not(feature = "no_volatile_pointers"))]
std::ptr::drop_in_place(self.ptr.as_mut().vlist.as_mut());
}
}
}
impl<T: PSafe, A: MemPool> Parc<mem::MaybeUninit<T>, A> {
/// Converts to `Parc<T>`.
///
/// # Safety
///
/// As with [`MaybeUninit::assume_init`],
/// it is up to the caller to guarantee that the inner value
/// really is in an initialized state.
/// Calling this when the content is not yet fully initialized
/// causes immediate undefined behavior.
///
/// [`MaybeUninit::assume_init`]: std::mem::MaybeUninit#method.assume_init
///
/// # Examples
///
/// ```
/// use corundum::alloc::heap::*;
/// use corundum::sync::Parc;
///
/// corundum::transaction(|j| {
/// let mut five = Parc::<u32,Heap>::new_uninit(j);
///
/// let five = unsafe {
/// // Deferred initialization:
/// Parc::get_mut_unchecked(&mut five).as_mut_ptr().write(5);
///
/// five.assume_init()
/// };
///
/// assert_eq!(*five, 5);
/// }).unwrap();
/// ```
#[inline]
pub unsafe fn assume_init(self) -> Parc<T, A> {
Parc::from_inner(mem::ManuallyDrop::new(self).ptr.cast())
}
}
impl<T: PSafe, A: MemPool> Parc<MaybeUninit<T>, A> {
#[inline]
/// Returns a mutable reference into the given `Parc`, if there are
/// no other [`Parc`] or [`Weak`] pointers to the same allocation.
///
/// Returns `None` otherwise, because it is not safe to mutate a shared
/// value. It only works for `Parc<MaybeUninit<T>>` to be able to defer the
/// initialization.
///
/// # Examples
///
/// ```
/// use corundum::alloc::heap::*;
/// use corundum::sync::Parc;
///
/// corundum::transaction(|j| {
/// let mut five = Parc::<u32,Heap>::new_uninit(j);
///
/// let five = unsafe {
/// // Deferred initialization:
/// Parc::get_mut(&mut five).unwrap().as_mut_ptr().write(5);
///
/// five.assume_init()
/// };
///
/// assert_eq!(*five, 5)
/// }).unwrap();
/// ```
pub fn get_mut(this: &mut Self) -> Option<&mut MaybeUninit<T>> {
if Parc::is_unique(this) {
unsafe { Some(Parc::get_mut_unchecked(this)) }
} else {
None
}
}
#[inline]
/// Returns a mutable reference into the given `Parc`, without any check.
///
/// It only works for `Parc<MaybeUninit<T>>` to be able to defer the
/// initialization.
///
/// # Safety
///
/// Any other [`Parc`] or [`Weak`] pointers to the same allocation must not
/// be dereferenced for the duration of the returned borrow. This is
/// trivially the case if no such pointers exist, for example immediately
/// after [`Parc::new`].
///
/// # Examples
///
/// ```
/// use corundum::alloc::heap::*;
/// use corundum::sync::Parc;
///
/// corundum::transaction(|j| {
/// let mut five = Parc::<u32,Heap>::new_uninit(j);
///
/// let five = unsafe {
/// // Deferred initialization:
/// Parc::get_mut_unchecked(&mut five).as_mut_ptr().write(5);
///
/// five.assume_init()
/// };
///
/// assert_eq!(*five, 5);
/// }).unwrap();
/// ```
pub unsafe fn get_mut_unchecked(this: &mut Self) -> &mut MaybeUninit<T> {
&mut this.ptr.value
}
}
impl<T: PSafe + ?Sized, A: MemPool> Parc<T, A> {
/// Creates a new [`Weak`] pointer to this allocation.
///
/// The [`Weak`] pointer can be [`upgrade`]d later in a transaction.
///
/// # Examples
///
/// ```
/// use corundum::alloc::heap::*;
/// use corundum::sync::Parc;
///
/// Heap::transaction(|j| {
/// let five = Parc::new(5, j);
/// let _weak_five = Parc::downgrade(&five, j);
/// }).unwrap()
/// ```
///
/// [`upgrade`]: ./struct.Weak.html#method.upgrade
pub fn downgrade(this: &Self, j: &Journal<A>) -> Weak<T, A> {
let inner = this.inner();
let _lock = SpinLock::acquire(inner.counter.lock.as_mut());
lock_free_fetch_inc(&mut inner.counter.weak, j);
Weak {
ptr: this.ptr.clone(),
}
}
/// Creates a new sharable [`VWeak`](./struct.VWeak.html) pointer to this
/// allocation.
///
/// # Errors
///
/// This function requires the allocation to be reachable from the
/// persistent root. Therefore, it panics if it gets called inside a
/// transaction.
///
/// # Examples
///
/// ```
/// use corundum::default::*;
///
/// type P = Allocator;
///
/// let obj = P::open::<Parc<i32>>("foo.pool", O_CF).unwrap();
///
/// let v = obj.demote();
/// assert_eq!(Parc::strong_count(&obj), 1);
///
/// P::transaction(|j| {
/// if let Some(obj) = v.promote(j) {
/// assert_eq!(Parc::strong_count(&obj), 2);
/// }
/// }).unwrap();
///
/// assert_eq!(Parc::strong_count(&obj), 1);
/// ```
pub fn demote(&self) -> VWeak<T, A> {
debug_assert!(!self.ptr.is_dangling());
assert!(
!Journal::<A>::is_running(),
"Parc::demote() cannot be called from a transaction"
);
VWeak::new(self)
}
/// Demote without dynamically checking transaction boundaries
pub unsafe fn unsafe_demote(&self) -> VWeak<T, A> {
debug_assert!(!self.ptr.is_dangling());
VWeak::new(self)
}
#[inline]
/// Gets the number of `Weak` pointers to this allocation.
///
/// # Examples
///
/// ```
/// use corundum::alloc::heap::*;
/// use corundum::sync::Parc;
///
/// Heap::transaction(|j| {
/// let five = Parc::new(5, j);
///
/// let _weak_five = Parc::downgrade(&five, j);
/// assert_eq!(1, Parc::weak_count(&five));
/// }).unwrap()
/// ```
pub fn weak_count(this: &Self) -> usize {
let inner = this.inner();
let cnt = load(inner.counter.lock.as_mut(), &this.inner().counter.weak);
// If the weak count is currently locked, the value of the
// count was 0 just before taking the lock.
if cnt == usize::MAX {
0
} else {
cnt - 1
}
}
#[inline]
/// Gets the number of `Strong` pointers to this allocation.
///
/// # Examples
///
/// ```
/// use corundum::alloc::heap::*;
/// use corundum::sync::Parc;
/// use corundum::clone::PClone;
///
/// Heap::transaction(|j| {
/// let five = Parc::new(5, j);
/// let _also_five = Parc::pclone(&five, j);
/// assert_eq!(2, Parc::strong_count(&five));
/// }).unwrap();
/// ```
pub fn strong_count(this: &Self) -> usize {
let inner = this.inner();
load(inner.counter.lock.as_mut(), &inner.counter.strong)
}
#[inline]
fn is_unique(this: &Self) -> bool {
Parc::weak_count(this) == 0 && Parc::strong_count(this) == 1
}
#[inline]
/// Returns `true` if the two `Parc`s point to the same allocation
/// (in a vein similar to [`std::ptr::eq`]).
///
/// # Examples
///
/// ```
/// use corundum::alloc::heap::*;
/// use corundum::sync::Parc;
/// use corundum::clone::PClone;
///
/// Heap::transaction(|j| {
/// let five = Parc::new(5, j);
/// let same_five = Parc::pclone(&five, j);
/// let other_five = Parc::new(5, j);
///
/// assert!(Parc::ptr_eq(&five, &same_five));
/// assert!(!Parc::ptr_eq(&five, &other_five));
/// }).unwrap();
/// ```
pub fn ptr_eq(this: &Self, other: &Self) -> bool {
this.ptr.off() == other.ptr.off()
}
}
impl<T: PSafe, A: MemPool> PmemUsage for Parc<T, A> {
default fn size_of() -> usize {
Ptr::<ParcInner<T, A>, A>::size_of()
}
}
impl<T: PSafe + PmemUsage + ?Sized, A: MemPool> PmemUsage for Parc<T, A> {
fn size_of() -> usize {
Ptr::<ParcInner<T, A>, A>::size_of() + T::size_of()
}
}
impl<T: PSafe + ?Sized, A: MemPool> Deref for Parc<T, A> {
type Target = T;
#[inline(always)]
fn deref(&self) -> &T {
&self.inner().value
}
}
impl<T: PSafe, A: MemPool> Parc<T, A> {
/// Initializes boxed data with `value` in-place if it is `None`
///
/// This function should not be called from a transaction as it updates
/// data without taking high-level logs. If transaction is unsuccessful,
/// there is no way to recover data.
/// However, it is safe to use it outside a transaction because it uses
/// low-level logs to provide safety for a single update without drop.
/// A dynamic check at the beginning makes sure of that.
///
/// # Examples
///
/// ```
/// use corundum::default::*;
///
/// type P = Allocator;
///
/// let root = P::open::<Option<Parc<i32>>>("foo.pool", O_CF).unwrap();
///
/// Parc::initialize(&*root, 25);
///
/// let value = **root.as_ref().unwrap();
/// assert_eq!(value, 25);
/// ```
///
pub fn initialize(arc: &Option<Parc<T, A>>, value: T) -> crate::result::Result<()> {
assert!(
!Journal::<A>::is_running(),
"Parc::initialize() cannot be used inside a transaction"
);
match arc {
Some(_) => Err("already initialized".to_string()),
None => if A::valid(arc) {
unsafe {
let new = A::atomic_new(
ParcInner::<T, A> {
counter: Counter {
strong: 1,
weak: 1,
lock: VCell::new(0),
},
#[cfg(not(feature = "no_volatile_pointers"))]
vlist: VCell::new(VWeakList::default()),
marker: PhantomData,
value,
});
let pnew = Some(Parc::<T, A>::from_inner(Ptr::from_off_unchecked(new.1)));
let src = crate::utils::as_slice64(&pnew);
let mut base = A::off_unchecked(arc);
for i in src {
A::log64(base, *i, new.3);
base += 8;
}
A::perform(new.3);
}
Ok(())
} else {
Err("The object is not in the PM".to_string())
}
}
}
}
unsafe impl<#[may_dangle] T: PSafe + ?Sized, A: MemPool> Drop for Parc<T, A> {
/// Drops the `Parc` safely
///
/// This will decrement the strong reference count. If the strong reference
/// count reaches zero then the only other references (if any) are
/// `Weak`, so we `drop` the inner value on commit using a `DropOnCommit` log.
///
/// # Examples
///
/// ```
/// use corundum::alloc::heap::*;
/// use corundum::sync::Parc;
/// use corundum::clone::PClone;
///
/// struct Foo;
///
/// impl Drop for Foo {
/// fn drop(&mut self) {
/// println!("dropped!");
/// }
/// }
///
/// Heap::transaction(|j| {
/// let foo = Parc::new(Foo, j);
/// let foo2 = Parc::pclone(&foo, j);
///
/// drop(foo); // Doesn't print anything
/// drop(foo2); // Prints "dropped!"
/// }).unwrap();
/// ```
///
fn drop(&mut self) {
unsafe {
let journal = &*Journal::<A>::current(true).unwrap().0;
let inner = self.inner();
// Because `fetch_sub` is already atomic, we do not need to synchronize
// with other threads unless we are going to delete the object. This
// same logic applies to the below `fetch_sub` to the `weak` count.
if fetch_dec(inner.counter.lock.as_mut(),
&mut inner.counter.strong, journal) != 1
{
return;
}
self.drop_slow(journal);
}
}
}
impl<T: PSafe + ?Sized, A: MemPool> PClone<A> for Parc<T, A> {
#[inline]
fn pclone(&self, j: &Journal<A>) -> Parc<T, A> {
let inner = self.inner();
let old_size = fetch_inc(inner.counter.lock.as_mut(),
&mut inner.counter.strong, j);
// However we need to guard against massive ref counts in case someone
// is `mem::forget`ing Arcs. If we don't do this the count can overflow
// and users will use-after free. We racily saturate to `isize::MAX` on
// the assumption that there aren't ~2 billion threads incrementing
// the reference count at once. This branch will never be taken in
// any realistic program.
//
// We abort because such a program is incredibly degenerate, and we
// don't care to support it.
if old_size > MAX_REFCOUNT {
std::process::abort();
}
Self::from_inner(self.ptr)
}
}
impl<T: RootObj<A> + PSafe, A: MemPool> RootObj<A> for Parc<T, A> {
#[inline]
default fn init(journal: &Journal<A>) -> Parc<T, A> {
Parc::new(T::init(journal), journal)
}
}
// impl<T: Default + PSafe + ?Sized, A: MemPool> RootObj<A> for Parc<T, A> {
// #[inline]
// default fn init(journal: &Journal<A>) -> Parc<T, A> {
// Parc::new(T::default(), journal)
// }
// }
trait RcEqIdent<T: PartialEq + PSafe + ?Sized, A: MemPool> {
fn eq(&self, other: &Parc<T, A>) -> bool;
fn ne(&self, other: &Parc<T, A>) -> bool;
}
impl<T: PartialEq + PSafe + ?Sized, A: MemPool> RcEqIdent<T, A> for Parc<T, A> {
#[inline]
fn eq(&self, other: &Parc<T, A>) -> bool {
**self == **other
}
#[inline]
fn ne(&self, other: &Parc<T, A>) -> bool {
**self != **other
}
}
impl<T: PartialEq + PSafe + ?Sized, A: MemPool> PartialEq for Parc<T, A> {
#[inline]
fn eq(&self, other: &Parc<T, A>) -> bool {
RcEqIdent::eq(self, other)
}
}
impl<T: Eq + PSafe + ?Sized, A: MemPool> Eq for Parc<T, A> {}
impl<T: PartialOrd + PSafe + ?Sized, A: MemPool> PartialOrd for Parc<T, A> {
#[inline(always)]
fn partial_cmp(&self, other: &Parc<T, A>) -> Option<Ordering> {
(**self).partial_cmp(&**other)
}
#[inline(always)]
fn lt(&self, other: &Parc<T, A>) -> bool {
**self < **other
}
#[inline(always)]
fn le(&self, other: &Parc<T, A>) -> bool {
**self <= **other
}
#[inline(always)]
fn gt(&self, other: &Parc<T, A>) -> bool {
**self > **other
}
#[inline(always)]
fn ge(&self, other: &Parc<T, A>) -> bool {
**self >= **other
}
}
impl<T: Ord + PSafe + ?Sized, A: MemPool> Ord for Parc<T, A> {
#[inline]
fn cmp(&self, other: &Parc<T, A>) -> Ordering {
(**self).cmp(&**other)
}
}
impl<T: Hash + PSafe, A: MemPool> Hash for Parc<T, A> {
fn hash<H: Hasher>(&self, state: &mut H) {
(**self).hash(state);
}
}
impl<T: fmt::Display + PSafe, A: MemPool> fmt::Display for Parc<T, A> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(&**self, f)
}
}
impl<T: fmt::Debug + PSafe, A: MemPool> fmt::Debug for Parc<T, A> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.deref().fmt(f)
}
}
impl<T: PSafe + ?Sized, A: MemPool> fmt::Pointer for Parc<T, A> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Pointer::fmt(&(&**self as *const T), f)
}
}
/// `Weak` is a version of [`Parc`] that holds a non-owning reference to the
/// managed allocation. The allocation is accessed by calling [`upgrade`] on the
/// `Weak` pointer, which returns an [`Option`]`<`[`Parc`]`<T>>`.
///
/// Since a `Weak` reference does not count towards ownership, it will not
/// prevent the value stored in the allocation from being dropped, and `Weak`
/// itself makes no guarantees about the value still being present. Thus it may
/// return [`None`] when [`upgrade`]d. Note however that a `Weak` reference
/// *does* prevent the allocation itself (the backing store) from being
/// deallocated.
///
/// A `Weak` pointer is useful for keeping a temporary reference to the
/// allocation managed by [`Parc`] without preventing its inner value from being
/// dropped. It is also used to prevent circular references between [`Parc`]
/// pointers, since mutual owning references would never allow either [`Parc`]
/// to be dropped. For example, a tree could have strong [`Parc`] pointers from
/// parent nodes to children, and `Weak` pointers from children back to their
/// parents.
///
/// The typical way to obtain a `Weak` pointer is to call [`Parc::downgrade`].
///
/// [`Parc::downgrade`]: ./struct.Parc.html#method.downgrade
/// [`upgrade`]: #method.upgrade
pub struct Weak<T: PSafe + ?Sized, A: MemPool> {
ptr: Ptr<ParcInner<T, A>, A>,
}
impl<T: ?Sized, A: MemPool> !TxOutSafe for Weak<T, A> {}
impl<T: ?Sized, A: MemPool> !Sync for Weak<T, A> {}
impl<T: ?Sized, A: MemPool> !Send for Weak<T, A> {}
impl<T: ?Sized, A: MemPool> !VSafe for Weak<T, A> {}
impl<T: PSafe, A: MemPool> Weak<T, A> {
pub fn as_raw(&self) -> *const T {
match self.inner() {
None => std::ptr::null(),
Some(inner) => {
let offset = data_offset_sized::<T, A>();
let ptr = inner as *const ParcInner<T, A>;
// Note: while the pointer we create may already point to dropped value, the
// allocation still lives (it must hold the weak point as long as we are alive).
// Therefore, the offset is OK to do, it won't get out of the allocation.
let ptr = unsafe { (ptr as *const u8).offset(offset) };
ptr as *const T
}
}
}
pub fn into_raw(self) -> *const T {
let result = self.as_raw();
mem::forget(self);
result
}
#[allow(clippy::missing_safety_doc)]
pub unsafe fn from_raw(ptr: *const T) -> Self {
if ptr.is_null() {
Self::new()
} else {
// See Rc::from_raw for details
let offset = data_offset::<T, A>(ptr);
let fake_ptr = ptr as *mut ParcInner<T, A>;
let ptr = set_data_ptr(fake_ptr, (ptr as *mut u8).offset(-offset));
Weak {
ptr: Ptr::from_raw(ptr),
}
}
}
}
impl<T: PSafe + ?Sized, A: MemPool> Weak<T, A> {
/// Creates a new dangling weak pointer
pub fn new() -> Weak<T, A> {
Weak {
ptr: Ptr::dangling(),
}
}
fn is_dangling(&self) -> bool {
self.ptr.is_dangling()
}
/// Attempts to upgrade the `Weak` pointer to an [`Parc`], delaying
/// dropping of the inner value if successful.
///
/// Returns [`None`] if the inner value has since been dropped.
///
/// # Examples
///
/// ```
/// use corundum::alloc::heap::*;
/// use corundum::sync::Parc;
///
/// Heap::transaction(|j| {
/// let five = Parc::new(5, j);
/// let weak_five = Parc::downgrade(&five, j);
/// let strong_five = weak_five.upgrade(j);
/// assert!(strong_five.is_some());
///
/// // Destroy all strong pointers.
/// drop(strong_five);
/// drop(five);
///
/// assert!(weak_five.upgrade(j).is_none());
/// }).unwrap()
/// ```
pub fn upgrade(&self, j: &Journal<A>) -> Option<Parc<T, A>> {
let inner = self.inner()?;
let _lock = SpinLock::acquire(inner.counter.lock.as_mut());
let n = inner.counter.strong;
if n == 0 {
return None;
}
// See comments in `Arc::clone` for why we do this (for `mem::forget`).
if n > MAX_REFCOUNT {
std::process::abort();
}
lock_free_fetch_inc(&mut inner.counter.strong, j);
Some(Parc::from_inner(self.ptr))
}
/// Gets the number of strong (`Parc`) pointers pointing to this allocation.
///
/// If `self` was created using [`Weak::new`], this will return 0.
pub fn strong_count(&self) -> usize {
if let Some(inner) = self.inner() {
load(inner.counter.lock.as_mut(), &inner.counter.strong)
} else {
0
}
}
/// Gets an approximation of the number of `Weak` pointers pointing to this
/// allocation.
///
/// If `self` was created using [`Weak::new`], or if there are no remaining
/// strong pointers, this will return 0.
///
/// # Accuracy
///
/// Due to implementation details, the returned value can be off by 1 in
/// either direction when other threads are manipulating any `Parc`s or
/// `Weak`s pointing to the same allocation.
pub fn weak_count(&self) -> usize {
self.inner()
.map(|inner| {
let weak = load(inner.counter.lock.as_mut(), &inner.counter.weak);
let strong = load(inner.counter.lock.as_mut(), &inner.counter.strong);
if strong == 0 {
0
} else {
// Since we observed that there was at least one strong pointer