-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathbztree.h
2454 lines (2227 loc) · 71.5 KB
/
bztree.h
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
#ifndef BZTREE_H
#define BZTREE_H
#include <thread>
#include <vector>
#include <tuple>
#include <algorithm>
#include <queue>
#include "bzerrno.h"
#include "PMwCAS.h"
#include "utils.h"
#include <mutex>
#include <fstream>
//Consolidation types
#define BZ_SPLIT 1
#define BZ_MERGE 2
#define BZ_CONSOLIDATE 3
#define BZ_FROZEN 4
//Action types
#define BZ_ACTION_INSERT 1
#define BZ_ACTION_DELETE 2
#define BZ_ACTION_UPDATE 3
#define BZ_ACTION_UPSERT 4
#define BZ_ACTION_READ 5
//Node types
const uint64_t BZ_KEY_MAX = 0xdeadbeafdeadbeaf;
#define BZ_TYPE_LEAF 1
#define BZ_TYPE_NON_LEAF 2
template<typename Key, typename Val>
struct bz_tree;
//Print
#include <iomanip>
std::mutex mylock;
std::fstream fs("log.txt", std::ios::app);
/* BzTree节点头部 */
//如果是叶节点,则Val代表实际数据的类型,否则Val为uint64_t,代表孩子节点的相对指针
template<typename Key, typename Val>
struct bz_node
{
/* length 32: node size, 31: sorted count, 1: is_leaf */
uint64_t length_;
/* status 3: PMwCAS control, 1: frozen, 16: record count, 22: block size, 22: delete size */
uint64_t status_;
/* record meta entry 3: PMwCAS control, 1: visiable, 28: offset, 16: key length, 16: total length */
uint64_t * rec_meta_arr();
/* K-V getter and setter */
Key * get_key(uint64_t meta);
void set_key(uint32_t offset, const Key * key);
void copy_key(Key * dst, const Key * src);
Val * get_value(uint64_t meta);
void set_value(uint32_t offset, const Val * val);
void copy_value(Val * dst, const Val * src);
/* 键值比较函数 */
int key_cmp(uint64_t meta_1, const Key * key);
bool key_cmp_meta(uint64_t meta_1, uint64_t meta_2);
/* 辅助函数 */
/* 基本操作 */
uint32_t binary_search(const Key * key, int size = 0, uint64_t * meta_arr = nullptr);
bool find_key_sorted(const Key * key, uint32_t &pos);
bool find_key_unsorted(const Key * key, uint64_t status_rd, uint32_t alloc_epoch, uint32_t &pos, bool &recheck);
uint64_t status_add_rec_blk(uint64_t status_rd, uint32_t total_size);
uint64_t status_del(uint64_t status_rd, uint32_t total_size);
template<typename TreeVal>
bool add_dele_sz(bz_tree<Key, TreeVal> * tree, uint32_t total_size);
uint64_t status_frozen(uint64_t status_rd);
uint64_t meta_vis_off(uint64_t meta_rd, bool set_vis, uint32_t new_offset);
uint64_t meta_vis_off_klen_tlen(uint64_t meta_rd, bool set_vis, uint32_t new_offset, uint32_t key_size, uint32_t total_size);
void copy_data(uint32_t new_offset, const Key * key, const Val * val, uint32_t key_size, uint32_t total_size);
void copy_data(uint64_t meta_rd, std::vector<std::pair<std::shared_ptr<Key>, std::shared_ptr<Val>>> & res);
template<typename TreeVal>
int rescan_unsorted(bz_tree<Key, TreeVal> * tree, uint32_t beg_pos, uint32_t rec_cnt, const Key * key, uint32_t total_size, uint32_t alloc_epoch);
/* SMO辅助函数 */
int triger_consolidate();
uint32_t copy_node_to(rel_ptr<bz_node<Key, Val>> dst, uint64_t status_rd = 0);
void fr_sort_meta();
void fr_remove_meta(int pos);
int fr_insert_meta(const Key * key, uint64_t left, uint32_t key_sz, uint64_t right);
int fr_root_init(const Key * key, uint64_t left, uint32_t key_sz, uint64_t right);
uint32_t copy_sort_meta_to(rel_ptr<bz_node<Key, Val>> dst);
uint32_t copy_payload_to(rel_ptr<bz_node<Key, Val>> dst, uint32_t new_rec_cnt);
void init_header(rel_ptr<bz_node<Key, Val>> dst, uint32_t new_rec_cnt, uint32_t blk_sz, int leaf_opt = 0, uint32_t dele_sz = 0);
uint32_t valid_block_size(uint64_t status_rd = 0);
uint32_t valid_node_size(uint64_t status_rd = 0);
uint32_t valid_record_count(uint64_t status_rd = 0);
uint32_t fr_get_balanced_count(rel_ptr<bz_node<Key, Val>> dst);
rel_ptr<uint64_t> nth_child(int n);
Key * nth_key(int n);
Val * nth_val(int n);
template<typename TreeVal>
mdesc_t try_freeze(bz_tree<Key, TreeVal> * tree);
template<typename TreeVal>
bool unfreeze(bz_tree<Key, TreeVal> * tree);
template<typename TreeVal>
int consolidate(bz_tree<Key, TreeVal> * tree, rel_ptr<uint64_t> parent_status, rel_ptr<uint64_t> parent_ptr);
template<typename TreeVal>
int split(bz_tree<Key, TreeVal> * tree, rel_ptr<bz_node<Key, uint64_t>> parent, rel_ptr<uint64_t> grandpa_status, rel_ptr<uint64_t> grandpa_ptr);
template<typename TreeVal>
int merge(bz_tree<Key, TreeVal> * tree, int child_id, rel_ptr<bz_node<Key, uint64_t>> parent, rel_ptr<uint64_t> grandpa_status, rel_ptr<uint64_t> grandpa_ptr);
/* 执行叶节点的数据项操作 */
template<typename TreeVal>
int insert(bz_tree<Key, TreeVal> * tree, const Key * key, const Val * val, uint32_t key_size, uint32_t total_size, uint32_t alloc_epoch);
template<typename TreeVal>
int remove(bz_tree<Key, TreeVal> * tree, const Key * key);
template<typename TreeVal>
int update(bz_tree<Key, TreeVal> * tree, const Key * key, const Val * val, uint32_t key_size, uint32_t total_size, uint32_t alloc_epoch);
template<typename TreeVal>
int read(bz_tree<Key, TreeVal> * tree, const Key * key, Val * buffer, uint32_t max_val_size);
template<typename TreeVal>
int upsert(bz_tree<Key, TreeVal> * tree, const Key * key, const Val * val, uint32_t key_size, uint32_t total_size, uint32_t alloc_epoch);
std::vector<std::pair<std::shared_ptr<Key>, std::shared_ptr<Val>>> range_scan(const Key * beg_key, const Key * end_key);
void print_log(const char * action, const Key * k = nullptr, uint64_t ret = -1, bool pr =
#ifdef BZ_DEBUG
true
#else
false
#endif // BZ_DEBUG
);
};
/* BzTree */
template<typename Key, typename Val>
struct bz_tree {
PMEMobjpool * pop_;
pmwcas_pool pool_;
uint64_t root_;
uint32_t epoch_;
void first_use(PMEMobjpool * pop, PMEMoid base_oid);
int init(PMEMobjpool * pop, PMEMoid base_oid);
void recovery();
void finish();
int insert(const Key * key, const Val * val, uint32_t key_size, uint32_t total_size);
int remove(const Key * key);
int update(const Key * key, const Val * val, uint32_t key_size, uint32_t total_size);
int upsert(const Key * key, const Val * val, uint32_t key_size, uint32_t total_size);
int read(const Key * key, Val * buffer, uint32_t max_val_size);
/* 辅助函数 */
void register_this();
bool acquire_wr(bz_path_stack * path_stack);
void acquire_rd();
void release();
template<typename NType>
bool smo(bz_path_stack * path_stack, int & ret);
int new_root();
int traverse(int action, bool wr, const Key * key, const Val * val = nullptr, uint32_t key_size = 0, uint32_t total_size = 0, Val * buffer = nullptr, uint32_t max_val_size = 0);
template<typename NType>
rel_ptr<rel_ptr<bz_node<Key, NType>>> alloc_node(mdesc_t mdesc, int magic = 0);
mdesc_t alloc_mdesc(int recycle = 0);
void recycle_node(rel_ptr<rel_ptr<uint64_t>> ptr);
int pack_pmwcas(std::vector<std::tuple<rel_ptr<uint64_t>, uint64_t, uint64_t>> casn);
void print_node(uint64_t ptr, int extra);
void print_tree(bool pr =
#ifdef BZ_DEBUG
true
#else
false
#endif // BZ_DEBUG
);
void print_dfs(uint64_t ptr, int level);
};
template<typename Key, typename Val>
int bz_tree<Key, Val>::traverse(int action, bool wr, const Key * key, const Val * val, uint32_t key_size, uint32_t total_size, Val * buffer, uint32_t max_val_size)
{
register_this();
if (!pmwcas_read(&root_)) {
new_root();
}
bz_path_stack path_stack;
int retry = 0;
while (true)
{
path_stack.reset();
uint64_t root = pmwcas_read(&root_);
path_stack.push(root, -1);
while (true)
{
if (wr && acquire_wr(&path_stack)) {
break;
}
else if (!wr) {
acquire_rd();
}
uint64_t ptr = path_stack.get_node();
if (is_leaf_node(ptr)) {
rel_ptr<bz_node<Key, Val>> node(ptr);
int ret;
if (action == BZ_ACTION_INSERT)
ret = node->insert(this, key, val, key_size, total_size, epoch_);
else if (action == BZ_ACTION_DELETE)
ret = node->remove(this, key);
else if (action == BZ_ACTION_UPDATE)
ret = node->update(this, key, val, key_size, total_size, epoch_);
else if (action == BZ_ACTION_UPSERT)
ret = node->upsert(this, key, val, key_size, total_size, epoch_);
else
ret = node->read(this, key, buffer, max_val_size);
release();
if (ret == EPMWCASALLOC || ret == EFROZEN) {
std::this_thread::sleep_for(std::chrono::milliseconds(++retry));
break;
}
return ret;
}
else {
rel_ptr<bz_node<Key, uint64_t>> node(ptr);
int child_id = (int)node->binary_search(key);
uint64_t next = *node->nth_val(child_id);
while (next & MwCAS_BIT || next & RDCSS_BIT || next & DIRTY_BIT) {
std::this_thread::sleep_for(std::chrono::milliseconds(1));
next = *node->nth_val(child_id);
//assert(0);
//node->print_log("READ_BUG");
}
path_stack.push(next, child_id);
release();
}
}
}
}
template<typename Key, typename Val>
inline void bz_tree<Key, Val>::register_this()
{
gc_register(pool_.gc);
}
/* 检查是否需要调整节点结构 & 进入GC临界区 */
/* @param path_stack <节点相对地址, 父节点到孩子指针的相对地址> */
template<typename Key, typename Val>
bool bz_tree<Key, Val>::acquire_wr(bz_path_stack * path_stack)
{
//访问节点
gc_crit_enter(pool_.gc);
//检查是否需要结构调整SMO
bool smo_type;
int ret;
uint64_t ptr = path_stack->get_node();
if (is_leaf_node(ptr)) {
smo_type = smo<Val>(path_stack, ret);
}
else {
smo_type = smo<uint64_t>(path_stack, ret);
}
if (smo_type) {
gc_crit_exit(pool_.gc);
}
if (ret == EFROZEN || ret == EPMWCASALLOC) {
std::this_thread::sleep_for(std::chrono::milliseconds(1));
}
return smo_type;
}
/* 进入GC临界区 */
template<typename Key, typename Val>
inline void bz_tree<Key, Val>::acquire_rd()
{
//进入节点
gc_crit_enter(pool_.gc);
}
template<typename Key, typename Val>
inline void bz_tree<Key, Val>::release()
{
//退出节点
gc_crit_exit(pool_.gc);
}
template<typename Key, typename Val>
template<typename NType>
bool bz_tree<Key, Val>::smo(bz_path_stack * path_stack, int & ret)
{
rel_ptr<bz_node<Key, NType>> node(path_stack->get_node());
int child_id = path_stack->get_child_id();
int smo_type = node->triger_consolidate();
if (smo_type == BZ_CONSOLIDATE) {
CONSOLIDATE_TAG:
if (child_id < 0) {
ret = node->consolidate<Val>(this, rel_ptr<uint64_t>::null(), rel_ptr<uint64_t>::null());
}
else {
path_stack->pop();
rel_ptr<bz_node<Key, uint64_t>> parent(path_stack->get_node());
ret = node->consolidate<Val>(this, &parent->status_, parent->nth_val(child_id));
path_stack->push();
}
}
else if (smo_type == BZ_SPLIT) {
if (child_id < 0) {
ret = node->split<Val>(this, rel_ptr<bz_node<Key, uint64_t>>::null(),
rel_ptr<uint64_t>::null(), rel_ptr<uint64_t>::null());
}
else {
path_stack->pop();
rel_ptr<bz_node<Key, uint64_t>> parent(path_stack->get_node());
int grand_id = path_stack->get_child_id();
if (grand_id < 0) {
ret = node->split<Val>(this, parent, rel_ptr<uint64_t>::null(), rel_ptr<uint64_t>::null());
}
else {
path_stack->pop();
rel_ptr<bz_node<Key, uint64_t>> grandpa(path_stack->get_node());
ret = node->split<Val>(this, parent, &grandpa->status_, grandpa->nth_val(grand_id));
path_stack->push();
}
path_stack->push();
}
}
else if (smo_type == BZ_MERGE) {
if (child_id < 0)
goto CONSOLIDATE_TAG;
path_stack->pop();
rel_ptr<bz_node<Key, uint64_t>> parent(path_stack->get_node());
int grand_id = path_stack->get_child_id();
if (grand_id < 0) {
ret = node->merge<Val>(this, child_id, parent, rel_ptr<uint64_t>::null(), rel_ptr<uint64_t>::null());
}
else {
path_stack->pop();
rel_ptr<bz_node<Key, uint64_t>> grandpa(path_stack->get_node());
ret = node->merge<Val>(this, child_id, parent, &grandpa->status_, grandpa->nth_val(grand_id));
path_stack->push();
}
path_stack->push();
}
return smo_type && (ret == EFROZEN || !ret || ret == EPMWCASALLOC);
}
template<typename Key, typename Val>
template<typename NType>
rel_ptr<rel_ptr<bz_node<Key, NType>>> bz_tree<Key, Val>::alloc_node(mdesc_t mdesc, int magic)
{
rel_ptr<rel_ptr<bz_node<Key, NType>>> new_node_ptr =
pmwcas_reserve<bz_node<Key, NType>>(mdesc,
get_magic(&pool_, magic), 0, NOCAS_RELEASE_NEW_ON_FAILED);
pool_.mem_.acquire(new_node_ptr);
uint32_t node_sz = NODE_ALLOC_SIZE;
rel_ptr<bz_node<Key, NType>> node = *new_node_ptr;
memset(node.abs(), 0, sizeof(bz_node<Key, NType>));
set_node_size(node->length_, node_sz);
persist(node.abs(), sizeof(bz_node<uint64_t, uint64_t>));
return new_node_ptr;
/*
//原子分配空间
TX_BEGIN(pop_) {
pmemobj_tx_add_range_direct(new_node_ptr.abs(), sizeof(uint64_t));
*new_node_ptr = pmemobj_tx_alloc(NODE_ALLOC_SIZE, TOID_TYPE_NUM(struct bz_node_fake));
} TX_END;
assert(!new_node_ptr->is_null());
rel_ptr<bz_node<Key, Val>> new_node = *new_node_ptr;
memset(new_node.abs(), 0, NODE_ALLOC_SIZE);
set_node_size(new_node->length_, NODE_ALLOC_SIZE);
return new_node;
*/
}
template<typename Key, typename Val>
int bz_node<Key, Val>::triger_consolidate()
{
uint64_t status_rd = pmwcas_read(&status_);
if (is_frozen(status_rd))
return BZ_FROZEN;
uint32_t rec_cnt = get_record_count(status_rd);
uint32_t blk_sz = get_block_size(status_rd);
uint32_t dele_sz = get_delete_size(status_rd);
uint32_t node_sz = get_node_size(length_);
uint32_t free_sz = node_sz - blk_sz - sizeof(*this) - rec_cnt * sizeof(uint64_t);
if (free_sz <= NODE_MIN_FREE_SIZE || dele_sz >= NODE_MAX_DELETE_SIZE) {
uint32_t new_node_sz = valid_node_size(status_rd);
if (new_node_sz >= NODE_SPLIT_SIZE)
return BZ_SPLIT;
else if (new_node_sz <= NODE_MERGE_SIZE)
return BZ_MERGE;
else
return BZ_CONSOLIDATE;
}
return 0;
}
/*
merge N
1. choose N's left/right sibling if
1.1 shares the same parent
1.2 small enough to absorb N's records
2. if neither is ok, return false
3. freeze N and L status
4. allocate 2 new nodes:
4.1 new node N' contains N and L's records
4.2 N and L parent P' that swaps the child ptr to L to N'
5. 3-word PMwCAS
5.1 G's child ptr to P
5.2 G's status
5.3 freeze P
*/
template<typename Key, typename Val>
template<typename TreeVal>
int bz_node<Key, Val>::merge(bz_tree<Key, TreeVal> * tree, int child_id,
rel_ptr<bz_node<Key, uint64_t>> parent,
rel_ptr<uint64_t> grandpa_status, rel_ptr<uint64_t> grandpa_ptr)
{
/* Global Variables */
uint64_t status_parent;
uint64_t status_cur;
uint64_t status_sibling;
int sibling_type = 0; //-1: 左 1: 右
rel_ptr<bz_node<Key, Val>> sibling;
rel_ptr<rel_ptr<bz_node<Key, Val>>> new_node_ptr;
rel_ptr<rel_ptr<bz_node<Key, uint64_t>>> new_parent_ptr;
uint32_t child_max;
int ret = 0;
bool forbids[2] = { false, false };
mdesc_t mdesc = try_freeze<TreeVal>(tree);
if (mdesc.is_null())
return EFROZEN;
//寻找兄弟节点
while (true) {
sibling_type = 0;
//读当前节点
status_cur = pmwcas_read(&status_);
//如果没有数据,删除节点
uint32_t valid_rec_cnt = valid_record_count(status_cur);
if (!valid_rec_cnt) {
if (!parent.is_null()) {
//读父节点,为后续做准备
status_parent = pmwcas_read(&parent->status_);
if (is_frozen(status_parent)) {
if (this->unfreeze(tree))
pmwcas_abort(mdesc);
return EFROZEN;
}
child_max = get_record_count(status_parent);
}
break;
}
//根节点无法merge
if (parent.is_null()) {
if (this->unfreeze(tree))
pmwcas_abort(mdesc);
else
return EPMWCASALLOC;
return ENONEED;
}
//读父节点
status_parent = pmwcas_read(&parent->status_);
if (is_frozen(status_parent)) {
if (this->unfreeze(tree))
pmwcas_abort(mdesc);
return EFROZEN;
}
child_max = get_record_count(status_parent);
uint32_t cur_sz = valid_node_size(status_cur);
//选择兄弟节点
if (!forbids[0] && child_id > 0) {
//判断左兄弟
sibling = parent->nth_child(child_id - 1);
status_sibling = pmwcas_read(&sibling->status_);
if (!is_frozen(status_sibling)) {
uint32_t left_sz = sibling->valid_node_size(status_sibling);
if (cur_sz + left_sz - sizeof(*this) < NODE_SPLIT_SIZE) {
sibling_type = -1;
}
}
else {
forbids[0] = true;
}
}
if (!forbids[1] && !sibling_type && (uint32_t)child_id + 1 < child_max) {
//判断右兄弟
sibling = parent->nth_child(child_id + 1);
status_sibling = pmwcas_read(&sibling->status_);
if (!is_frozen(status_sibling)) {
uint32_t right_sz = sibling->valid_node_size(status_sibling);
if (cur_sz + right_sz - sizeof(*this) < NODE_SPLIT_SIZE) {
sibling_type = 1;
}
}
else {
forbids[1] = true;
}
}
if (!sibling_type) {
//没有合适的
if (this->unfreeze(tree))
pmwcas_abort(mdesc);
else
return EPMWCASALLOC;
return ENONEED;
}
//尝试freeze兄弟节点
uint64_t status_sibling_new = status_frozen(status_sibling);
pmwcas_add(mdesc, &sibling->status_, status_sibling_new, status_sibling, NOCAS_EXECUTE_ON_FAILED);
int cas_res = tree->pack_pmwcas({{ &sibling->status_, status_sibling, status_sibling_new }});
if (!cas_res)
break;
print_log("MERGE-SIBLING_ERACE");
if (this->unfreeze(tree))
pmwcas_abort(mdesc);
else
return EPMWCASALLOC;
return ERACE;
}
print_log("MERGE_BEGIN", NULL, sibling.rel());
//删除根节点
if (parent.is_null()) {
pmwcas_add(mdesc, &tree->root_, rel_ptr<bz_node<Key, Val>>(this).rel(), 0, RELEASE_EXP_ON_SUCCESS);
if (!pmwcas_commit(mdesc))
return ERACE;
return 0;
}
//freeze old parent
uint64_t status_parent_new = status_frozen(status_parent);
pmwcas_add(mdesc, &parent->status_, status_parent, status_parent_new, 0);
if (sibling_type) {
/* 初始化N' */
new_node_ptr = tree->alloc_node<Val>(mdesc, 0);
rel_ptr<bz_node<Key, Val>> new_node = *new_node_ptr;
uint32_t new_blk_sz = 0;
uint32_t new_rec_cnt = 0;
//拷贝N和sibling的meta和k-v
this->copy_node_to(new_node);
uint32_t tot_rec_cnt = sibling->copy_node_to(new_node);
new_node->fr_sort_meta();
//初始化status和length
persist(new_node.abs(), NODE_ALLOC_SIZE);
}
rel_ptr<uint64_t> this_node((uint64_t*)this);
rel_ptr<uint64_t> sibling_addr(sibling);
if (child_max > 2
|| child_max == 2 && BZ_KEY_MAX != *(uint64_t*)parent->nth_key(1)
|| new_node_ptr.is_null())
{
//保留父亲节点
/* 初始化P' BEGIN */
new_parent_ptr = tree->alloc_node<uint64_t>(mdesc, 1);
rel_ptr<bz_node<Key, uint64_t>> new_parent = *new_parent_ptr;
uint32_t new_parent_rec_cnt = parent->copy_node_to(new_parent) - 1;
int pos = sibling_type < 0 ? child_id - 1 : child_id;
new_parent->fr_remove_meta(pos);
if (sibling_type)
*new_parent->nth_val(pos) = new_node_ptr->rel();
set_sorted_count(new_parent->length_, new_parent_rec_cnt);
persist(new_parent.abs(), NODE_ALLOC_SIZE);
//pmwcas
if (grandpa_ptr.is_null()) {
pmwcas_add(mdesc, &tree->root_, parent.rel(), new_parent.rel(), RELEASE_EXP_ON_SUCCESS);
}
else {
pmwcas_add(mdesc, grandpa_ptr, parent.rel(), new_parent.rel(), RELEASE_EXP_ON_SUCCESS);
uint64_t status_grandpa_rd = pmwcas_read(grandpa_status.abs());
if (is_frozen(status_grandpa_rd)) {
ret = EFROZEN;
goto IMMEDIATE_ABORT;
}
pmwcas_add(mdesc, grandpa_status, status_grandpa_rd, status_grandpa_rd);
}
}
else {
//删除父亲节点
if (grandpa_ptr.is_null()) {
pmwcas_add(mdesc, &tree->root_, parent.rel(), new_node_ptr->rel(), RELEASE_EXP_ON_SUCCESS);
}
else {
pmwcas_add(mdesc, grandpa_ptr, parent.rel(), new_node_ptr->rel(), RELEASE_EXP_ON_SUCCESS);
uint64_t status_grandpa_rd = pmwcas_read(grandpa_status.abs());
if (is_frozen(status_grandpa_rd)) {
ret = EFROZEN;
goto IMMEDIATE_ABORT;
}
pmwcas_add(mdesc, grandpa_status, status_grandpa_rd, status_grandpa_rd);
}
}
//释放当前节点和兄弟节点
pmwcas_add(mdesc, this_node, 0, 0, NOCAS_RELEASE_ADDR_ON_SUCCESS);
if (sibling_type) {
pmwcas_add(mdesc, sibling_addr, 0, 0, NOCAS_RELEASE_ADDR_ON_SUCCESS);
}
//执行pmwcas
if (!pmwcas_commit(mdesc)) {
ret = ERACE;
}
IMMEDIATE_ABORT:
pmwcas_free(mdesc);
print_log("MERGE_END", NULL, ret);
if (!ret) {
if (!new_node_ptr.is_null())
(*new_node_ptr)->print_log("MERGE_NEW");
if (!new_parent_ptr.is_null())
(*new_parent_ptr)->print_log("MERGE_NEW_PARENT");
}
return ret;
}
/*
split
1. freeze the node (k1, k2]
2. scan all valid keys and find the seperator key K
3. allocate 3 new nodes:
3.1 new N' (K, k2]
3.2 N' sibling O (k1, K]
3.3 N' new parent P' (add new key record K and ptr to O)
4. 3-word PMwCAS
4.1 freeze P status
4.2 swap G's ptr to P to P'
4.3 G's status to detect conflicts
NOTES:
Of new nodes, N' and O are not taken care of.
So we need an extra PMwCAS mdesc to record those memories:
in case failure before memory transmition, pmwcas will help reclaim;
in case success, abort the pmwcas since it has been safe.
*/
template<typename Key, typename Val>
template<typename TreeVal>
int bz_node<Key, Val>::split(
bz_tree<Key, TreeVal> * tree, rel_ptr<bz_node<Key, uint64_t>> parent,
rel_ptr<uint64_t> grandpa_status, rel_ptr<uint64_t> grandpa_ptr)
{
/* Global Variables */
uint64_t status_parent_rd;
int ret = 0;
mdesc_t mdesc = try_freeze<TreeVal>(tree);
if (mdesc.is_null())
return EFROZEN;
print_log("SPLIT_BEGIN");
/* 分配N'、O、P */
rel_ptr<rel_ptr<bz_node<Key, Val>>> new_left_ptr = tree->alloc_node<Val>(mdesc, 0);
rel_ptr<bz_node<Key, Val>> new_left = *new_left_ptr;
/* 初始化N'和O BEGIN */
//拷贝meta到new_left并按键值排序
uint32_t new_rec_cnt = this->copy_sort_meta_to(new_left);
if (new_rec_cnt < 2) {
pmwcas_free(mdesc);
print_log("SPLIT-NEW_REC_CNT");
return ENONEED;
}
rel_ptr<uint64_t> this_node_addr((uint64_t*)this);
//分配给O和P'
rel_ptr<rel_ptr<bz_node<Key, Val>>> new_right_ptr = tree->alloc_node<Val>(mdesc, 1);
rel_ptr<bz_node<Key, Val>> new_right = *new_right_ptr;
rel_ptr<rel_ptr<bz_node<Key, uint64_t>>> new_parent_ptr = tree->alloc_node<uint64_t>(mdesc, 2);
rel_ptr<bz_node<Key, uint64_t>> new_parent = *new_parent_ptr;
//按照大小平均分配键值对
uint32_t left_rec_cnt = this->fr_get_balanced_count(new_left);
//保证至少有一个到右节点
if (left_rec_cnt == new_rec_cnt) {
--left_rec_cnt;
}
uint32_t right_rec_cnt = new_rec_cnt - left_rec_cnt;
//拷贝meta到new_right
memcpy(new_right->rec_meta_arr(), new_left->rec_meta_arr() + left_rec_cnt,
right_rec_cnt * sizeof(uint64_t));
//拷贝k-v payload
uint32_t left_blk_sz = this->copy_payload_to(new_left, left_rec_cnt);
uint32_t right_blk_sz = this->copy_payload_to(new_right, right_rec_cnt);
//初始化status和length
this->init_header(new_left, left_rec_cnt, left_blk_sz);
this->init_header(new_right, right_rec_cnt, right_blk_sz);
//持久化
persist(new_left.abs(), NODE_ALLOC_SIZE);
persist(new_right.abs(), NODE_ALLOC_SIZE);
/* 初始化 N'和O END */
/* 初始化P' BEGIN */
//获得分割键值K
uint64_t meta_key = new_left->rec_meta_arr()[left_rec_cnt - 1];
const Key * K = new_left->get_key(meta_key);
uint32_t key_sz = get_key_length(meta_key);
uint32_t tot_sz = key_sz + sizeof(uint64_t);
uint64_t V = new_left.rel();
uint64_t * parent_meta_arr = new_parent->rec_meta_arr();
if (!parent.is_null()) {
/* 如果当前节点是非根节点 */
status_parent_rd = pmwcas_read(&parent->status_);
if (is_frozen(status_parent_rd)) {
ret = EFROZEN;
goto IMMEDIATE_ABORT;
}
uint32_t new_parent_rec_cnt = parent->copy_node_to(new_parent, status_parent_rd);
if (ret = new_parent->fr_insert_meta(K, V, key_sz, new_right.rel()))
goto IMMEDIATE_ABORT;
//持久化
persist(new_parent.abs(), NODE_ALLOC_SIZE);
}
else {
/* 如果当前节点是根节点 */
if (ret = new_parent->fr_root_init(K, V, key_sz, new_right.rel()))
goto IMMEDIATE_ABORT;
persist(new_parent.abs(), NODE_ALLOC_SIZE);
}
/* 初始化P' END */
/* 3-word pmwcas */
if (!grandpa_ptr.is_null()) {
/* 存在祖父节点 */
//3.1 G's ptr to P -> P'
pmwcas_add(mdesc, grandpa_ptr, parent.rel(), new_parent.rel(), RELEASE_EXP_ON_SUCCESS);
//3.2 freeze P's status
uint64_t status_parent_new = status_frozen(status_parent_rd);
pmwcas_add(mdesc, &parent->status_, status_parent_rd, status_parent_new);
//3.3 make sure G's status is not frozen
uint64_t status_grandpa_rd = pmwcas_read(grandpa_status.abs());
if (is_frozen(status_grandpa_rd)) {
ret = EFROZEN;
goto IMMEDIATE_ABORT;
}
pmwcas_add(mdesc, grandpa_status, status_grandpa_rd, status_grandpa_rd);
pmwcas_add(mdesc, this_node_addr, 0, 0, NOCAS_RELEASE_ADDR_ON_SUCCESS);
}
else if (!parent.is_null()) {
/* 父节点是根节点 */
//3.1 root's ptr to P -> P'
pmwcas_add(mdesc, &tree->root_, parent.rel(), new_parent.rel(), RELEASE_EXP_ON_SUCCESS);
//3.2 freeze P's status
uint64_t status_parent_new = status_frozen(status_parent_rd);
pmwcas_add(mdesc, &parent->status_, status_parent_rd, status_parent_new);
pmwcas_add(mdesc, this_node_addr, 0, 0, NOCAS_RELEASE_ADDR_ON_SUCCESS);
}
else {
/* 当前节点是根节点 */
rel_ptr<bz_node<Key, Val>> cur_ptr = this;
pmwcas_add(mdesc, &tree->root_, cur_ptr.rel(), new_parent.rel(), RELEASE_EXP_ON_SUCCESS);
}
//执行pmwcas
if (!pmwcas_commit(mdesc)) {
ret = ERACE;
}
IMMEDIATE_ABORT:
pmwcas_free(mdesc);
print_log("SPLIT_END", NULL, ret);
if (!ret) {
string msg = "SPLIT";
if (!grandpa_ptr.is_null())
msg += "_3_";
else if (!parent.is_null())
msg += "_2_";
else
msg += "_1_";
new_left->print_log(string(msg + "NEW_LEFT").c_str(), nullptr, left_rec_cnt);
new_right->print_log(string(msg + "NEW_RIGHT").c_str(), nullptr, right_rec_cnt);
new_parent->print_log(string(msg + "NEW_PARENT").c_str());
}
return ret;
}
/*
consolidate:
trigger by
either free space too small or deleted space too large
1) single-word PMwCAS on status => frozen bit
2) scan all valid records(visiable and not deleted)
calculate node size = record size + free space
2.1) if node size too large, do a split
2.2) otherwise, allocate a new node N', copy records sorted, init header
3) use path stack to find Node's parent P
3.1) if P's frozen, retraverse to locate P
4) 2-word PMwCAS
r in P that points to N => N'
P's status => detect concurrent freeze
5) N is ready for gc
6)
*/
template<typename Key, typename Val>
template<typename TreeVal>
int bz_node<Key, Val>::consolidate(bz_tree<Key, TreeVal> * tree,
rel_ptr<uint64_t> parent_status, rel_ptr<uint64_t> parent_ptr)
{
int ret = 0;
mdesc_t mdesc = try_freeze<TreeVal>(tree);
if (mdesc.is_null())
return EFROZEN;
print_log("CONSOLIDATE_BEGIN");
//初始化节点内容为0
rel_ptr<rel_ptr<bz_node<Key, Val>>> node_ptr = tree->alloc_node<Val>(mdesc);
rel_ptr<bz_node<Key, Val>> node = *node_ptr;
this->copy_node_to(node);
node->fr_sort_meta();
//持久化
persist(node.abs(), NODE_ALLOC_SIZE);
rel_ptr<bz_node<Key, Val>> this_node(this);
//如果需要修改父节点,确保其Frozen != 0
if (!parent_ptr.is_null()) {
uint64_t status_rd = pmwcas_read(parent_status.abs());
if (is_frozen(status_rd)) {
ret = EFROZEN;
goto IMMEDIATE_ABORT;
}
pmwcas_add(mdesc, parent_status, status_rd, status_rd, 0);
pmwcas_add(mdesc, parent_ptr, this_node.rel(), node.rel(), RELEASE_EXP_ON_SUCCESS);
}
else {
pmwcas_add(mdesc, &tree->root_, this_node.rel(), node.rel(), RELEASE_EXP_ON_SUCCESS);
}
//执行pmwcas
if (!pmwcas_commit(mdesc))
ret = ERACE;
IMMEDIATE_ABORT:
pmwcas_free(mdesc);
print_log("CONSOLIDATE_END", NULL, ret);
if (!ret) {
node->print_log("CONSOLIDATE_NEW");
}
return ret;
}
/* 计算节点均分时坐节点的数据项个数,单线程调用 */
template<typename Key, typename Val>
uint32_t bz_node<Key, Val>::fr_get_balanced_count(rel_ptr<bz_node<Key, Val>> dst)
{
uint32_t old_blk_sz = valid_block_size();
uint64_t * meta_arr = dst->rec_meta_arr();
uint32_t left_rec_cnt = 0;
for (uint32_t i = 0, acc_sz = 0; acc_sz < old_blk_sz / 2; ++i) {
if (is_visiable(meta_arr[i])) {
++left_rec_cnt;
acc_sz += get_total_length(meta_arr[i]);
}
}
return left_rec_cnt;
}
template<typename Key, typename Val>
uint32_t bz_node<Key, Val>::copy_node_to(rel_ptr<bz_node<Key, Val>> dst, uint64_t status_rd)
{
if (!status_rd)
status_rd = pmwcas_read(&status_);
uint64_t * meta_arr = rec_meta_arr();
uint64_t * new_meta_arr = dst->rec_meta_arr();
uint32_t rec_cnt = get_record_count(status_rd);
uint32_t new_rec_cnt = get_record_count(dst->status_);
uint32_t new_blk_sz = get_block_size(dst->status_);
uint32_t new_node_sz = get_node_size(dst->length_);
for (uint32_t i = 0; i < rec_cnt; ++i) {
uint64_t meta_rd = pmwcas_read(&meta_arr[i]);
if (is_visiable(meta_rd)) {
const Key * key = get_key(meta_rd);
const Val * val = get_value(meta_rd);
//assert(*(uint64_t*)key < 65 || *(uint64_t*)key == BZ_KEY_MAX);
uint64_t tmp = *(uint64_t*)val;
if ((tmp & MwCAS_BIT || tmp & RDCSS_BIT || tmp & DIRTY_BIT)) {
std::this_thread::sleep_for(std::chrono::milliseconds(1));
uint64_t tt = *(uint64_t*)val;
assert(0);
}
uint32_t key_sz = get_key_length(meta_rd);
uint32_t tot_sz = get_total_length(meta_rd);
uint32_t offset = new_node_sz - new_blk_sz - tot_sz - 1;
new_meta_arr[new_rec_cnt] = meta_vis_off_klen_tlen(0, true, offset, key_sz, tot_sz);
dst->copy_data(offset, key, val, key_sz, tot_sz);
new_blk_sz += tot_sz;
++new_rec_cnt;
}
}
set_record_count(dst->status_, new_rec_cnt);
set_block_size(dst->status_, new_blk_sz);
if (is_leaf(length_)) {
set_leaf(dst->length_);
}
else {
set_non_leaf(dst->length_);
}
return new_rec_cnt;
}
template<typename Key, typename Val>
void bz_node<Key, Val>::fr_sort_meta()
{
uint64_t tot_rec_cnt = get_record_count(status_);
uint64_t * new_meta_arr = rec_meta_arr();
std::sort(new_meta_arr, new_meta_arr + tot_rec_cnt,
std::bind(&bz_node<Key, Val>::key_cmp_meta, this, std::placeholders::_1, std::placeholders::_2));
//计算有效meta数目
uint32_t new_rec_cnt = binary_search(nullptr, (int)tot_rec_cnt);
set_sorted_count(length_, new_rec_cnt);
set_record_count(status_, new_rec_cnt);
}
template<typename Key, typename Val>
inline void bz_node<Key, Val>::fr_remove_meta(int pos)
{
uint64_t * parent_meta_arr = rec_meta_arr();
uint32_t rec_cnt = get_record_count(status_);
uint32_t dele_sz = get_delete_size(status_);
memmove(parent_meta_arr + pos, parent_meta_arr + pos + 1, (rec_cnt - 1 - pos) * sizeof(uint64_t));
//增加delete size,减少rec_cnt
set_record_count(status_, rec_cnt - 1);
set_delete_size(status_, dele_sz + get_total_length(parent_meta_arr[pos]));
}
template<typename Key, typename Val>
inline int bz_node<Key, Val>::fr_insert_meta(const Key * K, uint64_t left, uint32_t key_sz, uint64_t right)
{
uint64_t * meta_arr = rec_meta_arr();
uint32_t tot_sz = key_sz + sizeof(uint64_t);
uint32_t rec_cnt = get_record_count(status_);
uint32_t blk_sz = get_block_size(status_);
uint32_t node_sz = get_node_size(length_);
uint32_t pos = binary_search(K, rec_cnt);
if ((rec_cnt + 2) * sizeof(uint64_t) + key_sz + blk_sz + sizeof(*this) > node_sz) {
return EALLOCSIZE;
}
memmove(meta_arr + pos + 1, meta_arr + pos, sizeof(uint64_t) * (rec_cnt - pos));
uint32_t key_offset = node_sz - blk_sz - tot_sz - 1;
meta_arr[pos] = meta_vis_off_klen_tlen(0, true, key_offset, key_sz, tot_sz);
this->copy_data(key_offset, K, &left, key_sz, tot_sz);
//修改原来指向N的指针,现在指向new_right
*get_value(meta_arr[pos + 1]) = right;
assert(!(right & MwCAS_BIT || right & RDCSS_BIT || right & DIRTY_BIT));
set_record_count(status_, rec_cnt + 1);
set_sorted_count(length_, rec_cnt + 1);
set_block_size(status_, blk_sz + tot_sz);
return 0;
}
template<typename Key, typename Val>
int bz_node<Key, Val>::fr_root_init(const Key * K, uint64_t left, uint32_t key_sz, uint64_t right)
{
uint64_t * meta_arr = rec_meta_arr();
uint32_t node_sz = get_node_size(length_);
uint32_t tot_sz = key_sz + sizeof(uint64_t);