-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathclevel.rs
2192 lines (1920 loc) · 69.2 KB
/
clevel.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
//! Concurrent Level Hash Table.
#![allow(missing_docs)]
use core::fmt::Debug;
use core::hash::{Hash, Hasher};
use core::mem::MaybeUninit;
use core::ptr;
use core::sync::atomic::{fence, Ordering};
use crossbeam_channel::{Receiver, Sender};
use std::sync::atomic::AtomicUsize;
use cfg_if::cfg_if;
use crossbeam_epoch as epoch;
use etrace::*;
use fasthash::Murmur3HasherExt;
use itertools::*;
use libc::c_void;
use mmt_derive::Collectable;
use tinyvec::*;
use crate::pepoch::atomic::cut_as_high_tag_len;
use crate::pepoch::{PAtomic, PDestroyable, POwned, PShared};
use crate::ploc::{Cas, Checkpoint, DetectableCASAtomic};
use crate::pmem::*;
use crate::PDefault;
use crate::*;
const TINY_VEC_CAPACITY: usize = 8;
cfg_if! {
if #[cfg(any(feature = "stress", feature = "tcrash", feature = "pmcheck"))] {
// For stress test.
const SLOTS_IN_BUCKET: usize = 1;
const LEVEL_DIFF: usize = 2;
const MIN_SIZE: usize = 1;
#[inline]
const fn level_size_next(size: usize) -> usize {
size + LEVEL_DIFF
}
#[inline]
const fn level_size_prev(size: usize) -> usize {
size - LEVEL_DIFF
}
} else {
// For real workload.
// Size of hash: MIN_SIZE * SLOTS_IN_BUCKET * (1+LEVEL_RATIO)
const SLOTS_IN_BUCKET: usize = 8; // fixed
const LEVEL_RATIO: usize = 2; // fixed
const MIN_SIZE: usize = 786432; // Change this size
#[inline]
const fn level_size_next(size: usize) -> usize {
size * LEVEL_RATIO
}
#[inline]
const fn level_size_prev(size: usize) -> usize {
size / LEVEL_RATIO
}
}
}
fn hashes<T: Hash>(t: &T) -> (u16, [u32; 2]) {
let mut hasher = Murmur3HasherExt::default();
t.hash(&mut hasher);
let hash = hasher.finish() as usize;
let tag = hash.rotate_left(16) as u16;
let tag = cut_as_high_tag_len(tag as usize) as u16;
let left = hash as u32;
let right = hash.rotate_right(32) as u32;
(tag, [left, if left != right { right } else { right + 1 }])
}
/// Insert client
#[derive(Debug, Memento, Collectable)]
pub struct Insert<K, V: Collectable> {
found_slot: Checkpoint<(bool, PAtomic<Slot<K, V>>, PAtomic<Context<K, V>>)>,
insert_inner: InsertInner<K, V>,
move_if_resized: MoveIfResized<K, V>,
}
impl<K, V: Collectable> Default for Insert<K, V> {
fn default() -> Self {
Self {
found_slot: Default::default(),
insert_inner: Default::default(),
move_if_resized: Default::default(),
}
}
}
/// Move if resized client
#[derive(Debug, Memento, Collectable)]
pub struct MoveIfResized<K, V: Collectable> {
arg_chk: Checkpoint<(
PAtomic<Context<K, V>>,
PPtr<DetectableCASAtomic<Slot<K, V>>>,
usize, // FindResult's size
)>,
move_if_resized_inner: MoveIfResizedInner<K, V>,
}
impl<K, V: Collectable> Default for MoveIfResized<K, V> {
fn default() -> Self {
Self {
arg_chk: Default::default(),
move_if_resized_inner: Default::default(),
}
}
}
/// Move if resized client
#[derive(Debug, Memento, Collectable)]
pub struct MoveIfResizedInner<K, V: Collectable> {
prev_slot_chk: Checkpoint<PPtr<DetectableCASAtomic<Slot<K, V>>>>,
context_new_chk: Checkpoint<PAtomic<Context<K, V>>>,
slot_cas: Cas<Slot<K, V>>,
insert_inner: InsertInner<K, V>,
dirty_cas: Cas<Slot<K, V>>,
}
impl<K, V: Collectable> Default for MoveIfResizedInner<K, V> {
fn default() -> Self {
Self {
prev_slot_chk: Default::default(),
context_new_chk: Default::default(),
slot_cas: Default::default(),
insert_inner: Default::default(),
dirty_cas: Default::default(),
}
}
}
/// Insert inner client
#[derive(Debug, Memento, Collectable)]
pub struct InsertInner<K, V: Collectable> {
ctx_chk: Checkpoint<PAtomic<Context<K, V>>>,
try_slot_insert: TrySlotInsert<K, V>,
add_lv: AddLevel<K, V>,
}
impl<K, V: Collectable> Default for InsertInner<K, V> {
fn default() -> Self {
Self {
ctx_chk: Default::default(),
try_slot_insert: Default::default(),
add_lv: Default::default(),
}
}
}
/// Try slot insert client
#[derive(Debug, Memento, Collectable)]
pub struct TrySlotInsert<K, V: Collectable> {
slot_chk: Checkpoint<Option<(usize, PPtr<DetectableCASAtomic<Slot<K, V>>>)>>,
slot_cas: Cas<Slot<K, V>>,
fail: Checkpoint<()>,
}
impl<K, V: Collectable> Default for TrySlotInsert<K, V> {
fn default() -> Self {
Self {
slot_chk: Default::default(),
slot_cas: Default::default(),
fail: Default::default(),
}
}
}
/// Add level client
#[derive(Debug, Memento, Collectable)]
pub struct AddLevel<K, V: Collectable> {
next_level: NextLevel<K, V>,
ctx_new_chk: Checkpoint<PAtomic<Context<K, V>>>,
ctx_cas: Cas<Context<K, V>>,
ctx_chk: Checkpoint<PAtomic<Context<K, V>>>,
len_chk: Checkpoint<bool>,
}
impl<K, V: Collectable> Default for AddLevel<K, V> {
fn default() -> Self {
Self {
next_level: Default::default(),
ctx_new_chk: Default::default(),
ctx_cas: Default::default(),
ctx_chk: Default::default(),
len_chk: Default::default(),
}
}
}
/// Next level client
#[derive(Debug, Memento, Collectable)]
pub struct NextLevel<K, V: Collectable> {
next_level_chk: Checkpoint<PAtomic<Node<Bucket<K, V>>>>,
my_node_chk: Checkpoint<PAtomic<Node<Bucket<K, V>>>>,
next_cas: Cas<Node<Bucket<K, V>>>,
}
impl<K, V: Collectable> Default for NextLevel<K, V> {
fn default() -> Self {
Self {
next_level_chk: Default::default(),
my_node_chk: Default::default(),
next_cas: Default::default(),
}
}
}
/// Delete client
#[derive(Debug, Memento, Collectable)]
pub struct TryDelete<K, V: Collectable> {
slot_cas: Cas<Slot<K, V>>,
find_result_chk: Checkpoint<(PPtr<DetectableCASAtomic<Slot<K, V>>>, PAtomic<Slot<K, V>>)>,
}
impl<K, V: Collectable> Default for TryDelete<K, V> {
fn default() -> Self {
Self {
slot_cas: Default::default(),
find_result_chk: Default::default(),
}
}
}
/// Delete client
#[derive(Debug, Memento, Collectable)]
pub struct Delete<K, V: Collectable> {
try_delete: TryDelete<K, V>,
}
impl<K, V: Collectable> Default for Delete<K, V> {
fn default() -> Self {
Self {
try_delete: Default::default(),
}
}
}
/// Resize client
#[derive(Debug, Memento, Collectable)]
pub struct Resize<K, V: Collectable> {
recv_chk: Checkpoint<bool>,
ctx_chk: Checkpoint<PAtomic<Context<K, V>>>,
resize_inner: ResizeInner<K, V>,
}
impl<K, V: Collectable> Default for Resize<K, V> {
fn default() -> Self {
Self {
recv_chk: Default::default(),
ctx_chk: Default::default(),
resize_inner: Default::default(),
}
}
}
/// Resize inner client
#[derive(Debug, Memento, Collectable)]
pub struct ResizeInner<K, V: Collectable> {
ctx_chk: Checkpoint<PAtomic<Context<K, V>>>,
resize_clean: ResizeClean<K, V>,
resize_chg_ctx: ResizeChangeContext<K, V>,
}
impl<K, V: Collectable> Default for ResizeInner<K, V> {
fn default() -> Self {
Self {
ctx_chk: Default::default(),
resize_clean: Default::default(),
resize_chg_ctx: Default::default(),
}
}
}
/// Resize clean client
#[derive(Debug, Memento, Collectable)]
pub struct ResizeClean<K, V: Collectable> {
loop_i: Checkpoint<usize>,
loop_j: Checkpoint<(usize, PAtomic<Context<K, V>>, PPtr<Node<Bucket<K, V>>>)>,
resize_clean_inner: ResizeCleanInner<K, V>,
resize_move: ResizeMove<K, V>,
}
impl<K, V: Collectable> Default for ResizeClean<K, V> {
fn default() -> Self {
Self {
loop_i: Default::default(),
loop_j: Default::default(),
resize_clean_inner: Default::default(),
resize_move: Default::default(),
}
}
}
#[derive(Debug, Memento, Collectable)]
struct ResizeCleanInner<K, V: Collectable> {
res_slot_slot_ptr_chk:
Checkpoint<Option<(PPtr<DetectableCASAtomic<Slot<K, V>>>, PAtomic<Slot<K, V>>)>>,
slot_cas: Cas<Slot<K, V>>,
}
impl<K, V: Collectable> Default for ResizeCleanInner<K, V> {
fn default() -> Self {
Self {
res_slot_slot_ptr_chk: Default::default(),
slot_cas: Default::default(),
}
}
}
/// Resize chagne context client
#[derive(Debug, Memento, Collectable)]
pub struct ResizeChangeContext<K, V: Collectable> {
ctx_chk: Checkpoint<PAtomic<Context<K, V>>>,
ctx_new_chk: Checkpoint<PAtomic<Context<K, V>>>,
ctx_cas: Cas<Context<K, V>>,
}
impl<K, V: Collectable> Default for ResizeChangeContext<K, V> {
fn default() -> Self {
Self {
ctx_chk: Default::default(),
ctx_new_chk: Default::default(),
ctx_cas: Default::default(),
}
}
}
/// Resize move client
#[derive(Debug, Memento, Collectable)]
pub struct ResizeMove<K, V: Collectable> {
ctx_fst_chk: Checkpoint<(PAtomic<Context<K, V>>, PPtr<Node<Bucket<K, V>>>)>,
resize_move_inner: ResizeMoveInner<K, V>,
}
impl<K, V: Collectable> Default for ResizeMove<K, V> {
fn default() -> Self {
Self {
ctx_fst_chk: Default::default(),
resize_move_inner: Default::default(),
}
}
}
/// Resize move inner client
#[derive(Debug, Memento, Collectable)]
pub struct ResizeMoveInner<K, V: Collectable> {
resize_move_slot_insert: ResizeMoveSlotInsert<K, V>,
add_lv: AddLevel<K, V>,
}
impl<K, V: Collectable> Default for ResizeMoveInner<K, V> {
fn default() -> Self {
Self {
resize_move_slot_insert: Default::default(),
add_lv: Default::default(),
}
}
}
/// Resize move slot insert client
#[derive(Debug, Memento, Collectable)]
pub struct ResizeMoveSlotInsert<K, V: Collectable> {
slot_slot_first_chk:
Checkpoint<Option<(PPtr<DetectableCASAtomic<Slot<K, V>>>, PAtomic<Slot<K, V>>)>>,
slot_cas: Cas<Slot<K, V>>,
fail: Checkpoint<()>,
}
impl<K, V: Collectable> Default for ResizeMoveSlotInsert<K, V> {
fn default() -> Self {
Self {
slot_slot_first_chk: Default::default(),
slot_cas: Default::default(),
fail: Default::default(),
}
}
}
#[derive(Debug, Default)]
struct Slot<K, V: Collectable> {
key: K,
value: V,
}
impl<K, V: Collectable> Collectable for Slot<K, V> {
fn filter(slot: &mut Self, tid: usize, gc: &mut GarbageCollection, pool: &mut PoolHandle) {
V::filter(&mut slot.value, tid, gc, pool);
}
}
#[derive(Debug)]
#[repr(align(64))]
struct Bucket<K, V: Collectable> {
slots: [DetectableCASAtomic<Slot<K, V>>; SLOTS_IN_BUCKET],
}
impl<K, V: Collectable> Default for Bucket<K, V> {
fn default() -> Self {
Self {
slots: array_init::array_init(|_| DetectableCASAtomic::<_>::default()),
}
}
}
impl<K, V: Collectable> Collectable for Bucket<K, V> {
fn filter(bucket: &mut Self, tid: usize, gc: &mut GarbageCollection, pool: &mut PoolHandle) {
for slot in bucket.slots.iter_mut() {
DetectableCASAtomic::filter(slot, tid, gc, pool);
}
}
}
#[derive(Debug, Default)]
struct Node<T: Collectable> {
data: PAtomic<[MaybeUninit<T>]>,
next: DetectableCASAtomic<Self>,
}
impl<T: Collectable> From<PAtomic<[MaybeUninit<T>]>> for Node<T> {
fn from(data: PAtomic<[MaybeUninit<T>]>) -> Self {
Self {
data,
next: DetectableCASAtomic::default(),
}
}
}
impl<T: Collectable> Collectable for Node<T> {
fn filter(node: &mut Self, tid: usize, gc: &mut GarbageCollection, pool: &mut PoolHandle) {
let guard = unsafe { epoch::unprotected() };
let mut data = node.data.load(Ordering::SeqCst, guard);
let data_ref = unsafe { data.deref_mut(pool) };
for b in data_ref.iter_mut() {
MaybeUninit::<T>::mark(b, tid, gc);
}
DetectableCASAtomic::filter(&mut node.next, tid, gc, pool);
}
}
#[derive(Debug)]
struct NodeIter<'g, T: Collectable> {
inner: PShared<'g, Node<T>>,
last: PShared<'g, Node<T>>,
handle: &'g Handle,
}
impl<'g, T: Debug + Collectable> Iterator for NodeIter<'g, T> {
type Item = &'g [MaybeUninit<T>];
fn next(&mut self) -> Option<Self::Item> {
let pool = global_pool().unwrap();
let inner_ref = unsafe { self.inner.as_ref(pool) }?;
self.inner = if self.inner == self.last {
PShared::null()
} else {
inner_ref.next.load(Ordering::Acquire, self.handle)
};
Some(unsafe {
inner_ref
.data
.load(Ordering::Relaxed, &self.handle.guard)
.deref(pool)
})
}
}
#[derive(Debug)]
struct Context<K, V: Collectable> {
/// invariant: It is not changed after it is initialized.
first_level: PAtomic<Node<Bucket<K, V>>>,
/// invariant: It is not changed after it is initialized.
last_level: PAtomic<Node<Bucket<K, V>>>,
/// Should resize until the last level's size > resize_size
///
/// invariant: resize_size = first_level_size / 2 / 2
resize_size: AtomicUsize,
}
impl<K, V: Collectable> Collectable for Context<K, V> {
fn filter(context: &mut Self, tid: usize, gc: &mut GarbageCollection, pool: &mut PoolHandle) {
PAtomic::filter(&mut context.last_level, tid, gc, pool);
}
}
#[derive(Debug)]
pub struct Clevel<K, V: Collectable> {
context: DetectableCASAtomic<Context<K, V>>,
}
impl<K, V: Collectable> Collectable for Clevel<K, V> {
fn filter(clevel: &mut Self, tid: usize, gc: &mut GarbageCollection, pool: &mut PoolHandle) {
DetectableCASAtomic::filter(&mut clevel.context, tid, gc, pool);
}
}
impl<K, V: Collectable> PDefault for Clevel<K, V> {
fn pdefault(handle: &Handle) -> Self {
let pool = handle.pool;
let guard = unsafe { epoch::unprotected() }; // SAFE when initialization
let first_level = new_node(level_size_next(MIN_SIZE), pool).into_shared(guard);
let last_level = new_node(MIN_SIZE, pool);
let last_level_ref = unsafe { last_level.deref(pool) };
last_level_ref
.next
.inner
.store(first_level, Ordering::Relaxed);
persist_obj(&last_level_ref.next, true);
let context = alloc_persist(
Context {
first_level: first_level.into(),
last_level: last_level.into(),
resize_size: AtomicUsize::new(0),
},
pool,
)
.into_shared(guard);
Clevel {
context: DetectableCASAtomic::from(context),
}
}
}
#[derive(Debug)]
struct FindResult<'g, K, V: Collectable> {
/// level's size
size: usize,
slot: &'g DetectableCASAtomic<Slot<K, V>>,
slot_ptr: PShared<'g, Slot<K, V>>,
}
impl<K, V: Collectable> Default for FindResult<'_, K, V> {
#[allow(deref_nullptr)]
fn default() -> Self {
Self {
size: 0,
slot: unsafe { &*ptr::null() },
slot_ptr: PShared::null(),
}
}
}
impl<K: PartialEq + Hash, V: Collectable> Context<K, V> {
fn level_iter<'g>(&'g self, handle: &'g Handle) -> NodeIter<'g, Bucket<K, V>> {
NodeIter {
inner: self.last_level.load(Ordering::Acquire, &handle.guard),
last: self.first_level.load(Ordering::Acquire, &handle.guard),
handle,
}
}
}
impl<K: Debug + PartialEq + Hash, V: Debug + Collectable> Context<K, V> {
/// `Ok`: found something (may not be unique)
///
/// `Err` means contention
fn find_fast<'g>(
&'g self,
key: &K,
key_tag: u16,
key_hashes: [u32; 2],
handle: &'g Handle,
) -> Result<Option<FindResult<'g, K, V>>, ()> {
let mut found_moved = false;
// level_iter: from last (small) to first (large)
for array in self.level_iter(handle) {
let size = array.len();
for key_hash in key_hashes
.into_iter()
.map(|key_hash| key_hash as usize % size)
.sorted()
.dedup()
{
for slot in unsafe { array[key_hash].assume_init_ref().slots.iter() } {
let slot_ptr = slot.load(Ordering::Acquire, handle);
// check 2-byte tag
if slot_ptr.high_tag() != key_tag as usize {
continue;
}
let slot_ref = some_or!(unsafe { slot_ptr.as_ref(handle.pool) }, continue);
if *key != slot_ref.key {
continue;
}
// `tag = 1` means the slot is being moved or already moved.
//
// CAUTION: we should use another bit for tagging in Memento. The LSB is for SMO.
if slot_ptr.tag() == 1 {
found_moved = true;
continue;
}
return Ok(Some(FindResult {
size,
slot,
slot_ptr,
}));
}
}
}
if found_moved {
// We cannot conclude whether we the moved item is in the hash table. On the one hand,
// the moved item may already have been removed by another thread. On the other hand,
// the being moved item may not yet been added again.
Err(())
} else {
Ok(None)
}
}
/// `Ok`: found a unique item (by deduplication)
///
/// `Err` means contention
fn find<'g>(
&'g self,
key: &K,
key_tag: u16,
key_hashes: [u32; 2],
handle: &'g Handle,
) -> Result<Option<FindResult<'g, K, V>>, ()> {
let mut found = tiny_vec!([_; TINY_VEC_CAPACITY]);
// "bottom-to-top" or "last-to-first"
for array in self.level_iter(handle) {
let size = array.len();
for key_hash in key_hashes
.into_iter()
.map(|key_hash| key_hash as usize % size)
.sorted()
.dedup()
{
for slot in unsafe { array[key_hash].assume_init_ref().slots.iter() } {
let slot_ptr = slot.load(Ordering::Acquire, handle);
// check 2-byte tag
if slot_ptr.high_tag() != key_tag as usize {
continue;
}
let slot_ref = some_or!(unsafe { slot_ptr.as_ref(handle.pool) }, continue);
if *key != slot_ref.key {
continue;
}
found.push(FindResult {
size,
slot,
slot_ptr,
});
}
}
}
// find result nearest to the top.
// CAUTION: tag conflicts with Memento SMO.
let last = some_or!(found.pop(), return Ok(None));
if last.slot_ptr.tag() == 1 {
return Err(());
}
// ptrs to delete.
let mut owned_found = tiny_vec!([FindResult<'g, K, V>; TINY_VEC_CAPACITY]);
for find_result in found.into_iter().rev() {
if find_result.slot_ptr.tag() == 1 {
// The item is moved.
let slot_ptr = find_result.slot_ptr.with_tag(0);
if last.slot_ptr == slot_ptr || owned_found.iter().any(|x| x.slot_ptr == slot_ptr) {
// If the moved item is found again, help moving.
find_result
.slot
.inner
.store(PShared::null().with_tag(1), Ordering::Release); // exploit invariant
} else {
// If the moved item is not found again, retry.
return Err(());
}
} else {
owned_found.push(find_result);
}
}
// last is the find result to return.
// remove everything else.
for find_result in owned_found.into_iter() {
// caution: we need **strong** CAS to guarantee uniqueness. maybe next time...
// exploit invariant
match find_result
.slot
.cas_non_detectable(find_result.slot_ptr, PShared::null(), handle)
{
Ok(_) => unsafe {
handle.guard.defer_pdestroy(find_result.slot_ptr);
},
Err(e) => {
if e == find_result.slot_ptr.with_tag(1) {
// If the item is moved, retry.
return Err(());
}
}
}
}
Ok(Some(last))
}
}
fn new_node<K, V: Collectable>(size: usize, pool: &PoolHandle) -> POwned<Node<Bucket<K, V>>> {
let data = POwned::<[MaybeUninit<Bucket<K, V>>]>::init(size, pool);
let data_ref = unsafe { data.deref(pool) };
unsafe {
let _ = libc::memset(
data_ref as *const _ as *mut c_void,
0x0,
size * std::mem::size_of::<Bucket<K, V>>(),
);
}
persist_obj(&data_ref, true);
alloc_persist(Node::from(PAtomic::from(data)), pool)
}
impl<K: Debug + PartialEq + Hash, V: Debug + Collectable> Clevel<K, V> {
/// Check if resizing
pub fn is_resizing(&self, handle: &Handle) -> bool {
let (guard, pool) = (&handle.guard, handle.pool);
let context = self.context.load(Ordering::Acquire, handle);
let context_ref = unsafe { context.deref(pool) };
let last_level = context_ref.last_level.load(Ordering::Relaxed, guard);
(unsafe {
last_level
.deref(pool)
.data
.load(Ordering::Relaxed, guard)
.deref(pool)
.len()
}) <= context_ref.resize_size.load(Ordering::Relaxed)
}
fn next_level<'g>(
&self,
fst_lv: &'g Node<Bucket<K, V>>,
next_lv_size: usize,
mmt: &mut NextLevel<K, V>,
handle: &'g Handle,
) -> PShared<'g, Node<Bucket<K, V>>> {
let (guard, pool) = (&handle.guard, handle.pool);
let next_lv = mmt
.next_level_chk
.checkpoint(
|| {
let next_lv = fst_lv.next.load(Ordering::Acquire, handle);
PAtomic::from(next_lv)
},
handle,
)
.load(Ordering::Relaxed, guard);
if !next_lv.is_null() {
return next_lv;
}
// TODO: need lock?
let my_node = mmt
.my_node_chk
.checkpoint(|| PAtomic::from(new_node(next_lv_size, pool)), handle)
.load(Ordering::Relaxed, guard);
if let Err(e) = fst_lv
.next
.cas(PShared::null(), my_node, &mut mmt.next_cas, handle)
{
unsafe { guard.defer_pdestroy(my_node) };
return e;
}
my_node
}
fn add_level<'g>(
&'g self,
ctx: PShared<'g, Context<K, V>>,
mmt: &mut AddLevel<K, V>,
handle: &'g Handle,
) -> (PShared<'g, Context<K, V>>, bool) {
let (guard, pool) = (&handle.guard, handle.pool);
let ctx_ref = unsafe { ctx.deref(pool) };
let fst_lv = ctx_ref.first_level.load(Ordering::Acquire, guard);
let fst_lv_ref = unsafe { fst_lv.deref(pool) };
let fst_lv_data = unsafe { fst_lv_ref.data.load(Ordering::Relaxed, guard).deref(pool) };
let next_lv_size = level_size_next(fst_lv_data.len());
// insert a new level to the next of the first level.
let next_lv = self.next_level(fst_lv_ref, next_lv_size, &mut mmt.next_level, handle);
// update context.
let ctx_new = mmt
.ctx_new_chk
.checkpoint(
|| {
let c = Context {
first_level: PAtomic::from(next_lv),
last_level: ctx_ref.last_level.clone(),
resize_size: AtomicUsize::new(level_size_prev(level_size_prev(
next_lv_size,
))),
};
let new = alloc_persist(c, pool);
PAtomic::from(new)
},
handle,
)
.load(Ordering::Relaxed, guard);
let ctx_new_ref = unsafe { ctx_new.deref(pool) };
let mut phi = PAtomic::from(ctx);
loop {
let ctx = mmt
.ctx_chk
.checkpoint(|| phi, handle)
.load(Ordering::Relaxed, guard);
let res = self.context.cas(ctx, ctx_new, &mut mmt.ctx_cas, handle);
if res.is_ok() {
break;
}
let cur = res.unwrap_err();
let out = mmt.len_chk.checkpoint(
|| {
let cur_ref = unsafe { cur.deref(pool) };
let len = unsafe {
cur_ref
.first_level
.load(Ordering::Acquire, guard)
.deref(pool)
.data
.load(Ordering::Relaxed, guard)
.deref(pool)
}
.len();
let out = len >= next_lv_size;
if !out {
let last_lv = cur_ref.last_level.load(Ordering::Acquire, guard);
ctx_new_ref.last_level.store(last_lv, Ordering::Relaxed);
persist_obj(&ctx_new_ref.last_level, false); // cas soon
}
out
},
handle,
);
if out {
unsafe { guard.defer_pdestroy(ctx_new) };
return (cur, false);
}
phi = PAtomic::from(cur);
}
fence(Ordering::SeqCst);
(ctx_new, true)
}
/// f() function in LOOP-TRY rule for `resize_move_slot_insert`
fn resize_move_slot_insert_inner(
slot: &DetectableCASAtomic<Slot<K, V>>,
slot_ptr: PShared<'_, Slot<K, V>>,
slot_first_level: PShared<'_, Slot<K, V>>,
key_tag: u16,
mmt: &mut Cas<Slot<K, V>>,
handle: &Handle,
) -> Result<(), ()> {
if let Some(slot_ref) = unsafe { slot_first_level.as_ref(handle.pool) } {
// 2-byte tag checking
if slot_first_level.high_tag() != key_tag as usize {
return Err(());
}
if slot_ref.key != unsafe { slot_ptr.deref(handle.pool) }.key {
return Err(());
}
return Ok(());
}
if slot.cas(PShared::null(), slot_ptr, mmt, handle).is_ok() {
return Ok(());
}
Err(())
}
fn resize_move_slot_insert(
&self,
slot_ptr: PShared<'_, Slot<K, V>>,
fst_lv_ref: &Node<Bucket<K, V>>,
mmt: &mut ResizeMoveSlotInsert<K, V>,
handle: &Handle,
) -> Result<(), ()> {
let (guard, pool) = (&handle.guard, handle.pool);
let (key_tag, key_hashes) = hashes(&unsafe { slot_ptr.deref(handle.pool) }.key);
if handle.rec.load(Ordering::Relaxed) {
if mmt.fail.peek(handle).is_some() {
return Err(());
}
if let Some(v) = mmt.slot_slot_first_chk.peek(handle) {
let chk = some_or!(v, return Err(()));
let (slot, slot_first_level) = (
unsafe { chk.0.deref(pool) },
chk.1.load(Ordering::Relaxed, guard),
);
if let Ok(res) = Self::resize_move_slot_insert_inner(
slot,
slot_ptr,
slot_first_level,
key_tag,
&mut mmt.slot_cas,
handle,
) {
return Ok(res);
}
}
}
let fst_lv_data = unsafe { fst_lv_ref.data.load(Ordering::Relaxed, guard).deref(pool) };
let fst_lv_size = fst_lv_data.len();
let key_hashes = key_hashes
.into_iter()
.map(|key_hash| key_hash as usize % fst_lv_size)
.sorted()
.dedup();
// `(i, key_hash)`: argument of `i`th iteration of loop
for i in 0..SLOTS_IN_BUCKET {
for key_hash in key_hashes.clone() {
let (slot, slot_first_level) = {
let chk = mmt
.slot_slot_first_chk
.checkpoint(
|| {
let slot = unsafe {
fst_lv_data[key_hash]
.assume_init_ref()
.slots
.get_unchecked(i)
};
let slot_first_level = slot.load(Ordering::Acquire, handle);
Some((
unsafe { slot.as_pptr(pool) },
PAtomic::from(slot_first_level),
))
},
handle,
)
.unwrap();
(
unsafe { chk.0.deref(pool) },
chk.1.load(Ordering::Relaxed, guard),
)
};
if let Ok(res) = Self::resize_move_slot_insert_inner(
slot, // stable by checkpoint
slot_ptr, // stable by callerr
slot_first_level, // stable by checkpoint
key_tag,
&mut mmt.slot_cas,
handle,
) {
return Ok(res);
}
}