-
Notifications
You must be signed in to change notification settings - Fork 1
/
bztree.cc
1746 lines (1571 loc) · 63.3 KB
/
bztree.cc
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
// Copyright (c) Simon Fraser University. All rights reserved.
// Licensed under the MIT license.
//
// Authors:
// Xiangpeng Hao <[email protected]>
// Tianzheng Wang <[email protected]>
#include <algorithm>
#include <iostream>
#include <string>
#include "bztree.h"
#ifndef MAX_FREEZE_RETRY
#define MAX_FREEZE_RETRY 1
#endif
#ifndef ENABLE_MERGE
#define ENABLE_MERGE 1
#endif
namespace bztree {
#ifdef PMDK
pmwcas::PMDKAllocator *Allocator::allocator_ = nullptr;
#endif
uint64_t global_epoch = 0;
void InternalNode::New(bztree::InternalNode **mem, uint32_t alloc_size) {
#ifdef PMDK
Allocator::Get()->AllocateDirect(reinterpret_cast<void **>(mem), alloc_size);
memset(*mem, 0, alloc_size);
(*mem)->header.size = alloc_size;
*mem = Allocator::Get()->GetOffset(*mem);
#else
pmwcas::Allocator::Get()->Allocate(reinterpret_cast<void **>(mem), alloc_size);
memset(*mem, 0, alloc_size);
(*mem)->header.size = alloc_size;
#endif // PMDK
}
// Create an internal node with a new key and associated child pointers inserted
// based on an existing internal node
void InternalNode::New(InternalNode *src_node,
const char *key,
uint32_t key_size,
uint64_t left_child_addr,
uint64_t right_child_addr,
InternalNode **mem) {
uint32_t alloc_size = src_node->GetHeader()->size +
RecordMetadata::PadKeyLength(key_size) +
sizeof(right_child_addr) + sizeof(RecordMetadata);
#ifdef PMDK
Allocator::Get()->AllocateDirect(reinterpret_cast<void **>(mem), alloc_size);
memset(*mem, 0, alloc_size);
new(*mem) InternalNode(alloc_size, src_node, 0, src_node->header.sorted_count,
key, key_size, left_child_addr, right_child_addr);
pmwcas::NVRAM::Flush(alloc_size, *mem);
*mem = Allocator::Get()->GetOffset(*mem);
#else
pmwcas::Allocator::Get()->Allocate(reinterpret_cast<void **>(mem), alloc_size);
memset(*mem, 0, alloc_size);
new(*mem) InternalNode(alloc_size, src_node, 0, src_node->header.sorted_count,
key, key_size, left_child_addr, right_child_addr);
#ifdef PMEM
pmwcas::NVRAM::Flush(alloc_size, *mem);
#endif // PMEM
#endif // PMDK
}
// Create an internal node with a single separator key and two pointers
void InternalNode::New(const char *key,
uint32_t key_size,
uint64_t left_child_addr,
uint64_t right_child_addr,
InternalNode **mem) {
uint32_t alloc_size = sizeof(InternalNode) +
RecordMetadata::PadKeyLength(key_size) +
sizeof(left_child_addr) +
sizeof(right_child_addr) +
sizeof(RecordMetadata) * 2;
#ifdef PMDK
Allocator::Get()->AllocateDirect(reinterpret_cast<void **>(mem), alloc_size);
memset(*mem, 0, alloc_size);
new(*mem) InternalNode(alloc_size, key, key_size, left_child_addr, right_child_addr);
pmwcas::NVRAM::Flush(alloc_size, *mem);
*mem = Allocator::Get()->GetOffset(*mem);
#else
pmwcas::Allocator::Get()->Allocate(reinterpret_cast<void **>(mem), alloc_size);
memset(*mem, 0, alloc_size);
new(*mem) InternalNode(alloc_size, key, key_size, left_child_addr, right_child_addr);
#ifdef PMEM
pmwcas::NVRAM::Flush(alloc_size, *mem);
#endif // PMEM
#endif // PMDK
}
// Create an internal node with keys and pointers in the provided range from an
// existing source node
void InternalNode::New(InternalNode *src_node,
uint32_t begin_meta_idx, uint32_t nr_records,
const char *key, uint32_t key_size,
uint64_t left_child_addr, uint64_t right_child_addr,
InternalNode **new_node,
uint64_t left_most_child_addr) {
// Figure out how large the new node will be
uint32_t alloc_size = sizeof(InternalNode);
if (begin_meta_idx > 0) {
// Will not copy from the first element (dummy key), so add it here
alloc_size += src_node->record_metadata[0].GetTotalLength();
alloc_size += sizeof(RecordMetadata);
}
assert(nr_records > 0);
for (uint32_t i = begin_meta_idx; i < begin_meta_idx + nr_records; ++i) {
RecordMetadata meta = src_node->record_metadata[i];
alloc_size += meta.GetTotalLength();
alloc_size += sizeof(RecordMetadata);
}
// Add the new key, if provided
if (key) {
ALWAYS_ASSERT(key_size > 0);
alloc_size +=
(RecordMetadata::PadKeyLength(key_size) + sizeof(uint64_t) + sizeof(RecordMetadata));
}
#ifdef PMDK
Allocator::Get()->AllocateDirect(reinterpret_cast<void **>(new_node), alloc_size);
memset(*new_node, 0, alloc_size);
new(*new_node) InternalNode(alloc_size, src_node, begin_meta_idx, nr_records,
key, key_size, left_child_addr, right_child_addr,
left_most_child_addr);
pmwcas::NVRAM::Flush(alloc_size, new_node);
*new_node = Allocator::Get()->GetOffset(*new_node);
#else
pmwcas::Allocator::Get()->Allocate(reinterpret_cast<void **>(new_node), alloc_size);
memset(*new_node, 0, alloc_size);
new(*new_node) InternalNode(alloc_size, src_node, begin_meta_idx, nr_records,
key, key_size, left_child_addr, right_child_addr,
left_most_child_addr);
#ifdef PMEM
pmwcas::NVRAM::Flush(alloc_size, *new_node);
#endif // PMEM
#endif // PMDK
}
InternalNode::InternalNode(uint32_t node_size,
const char *key,
const uint16_t key_size,
uint64_t left_child_addr,
uint64_t right_child_addr)
: BaseNode(false, node_size) {
// Initialize a new internal node with one key only
header.sorted_count = 2; // Includes the null dummy key
header.size = node_size;
// Fill in left child address, with an empty key
uint64_t offset = node_size - sizeof(left_child_addr);
record_metadata[0].FinalizeForInsert(offset, 0, sizeof(left_child_addr));
char *ptr = reinterpret_cast<char *>(this) + offset;
memcpy(ptr, &left_child_addr, sizeof(left_child_addr));
// Fill in right child address, with the separator key
auto padded_key_size = RecordMetadata::PadKeyLength(key_size);
auto total_len = padded_key_size + sizeof(right_child_addr);
offset -= total_len;
record_metadata[1].FinalizeForInsert(offset, key_size, total_len);
ptr = reinterpret_cast<char *>(this) + offset;
memcpy(ptr, key, key_size);
memcpy(ptr + padded_key_size, &right_child_addr, sizeof(right_child_addr));
assert((uint64_t) ptr == (uint64_t) this + sizeof(*this) + 2 * sizeof(RecordMetadata));
}
InternalNode::InternalNode(uint32_t node_size,
InternalNode *src_node,
uint32_t begin_meta_idx,
uint32_t nr_records,
const char *key,
const uint16_t key_size,
uint64_t left_child_addr,
uint64_t right_child_addr,
uint64_t left_most_child_addr)
: BaseNode(false, node_size) {
ALWAYS_ASSERT(src_node);
__builtin_prefetch((const void *) (src_node), 0, 3);
auto padded_key_size = RecordMetadata::PadKeyLength(key_size);
uint64_t offset = node_size;
bool need_insert_new = key;
uint32_t insert_idx = 0;
// See if we need a new left_most_child_addr, i.e., this must be the new node
// on the right
if (left_most_child_addr) {
offset -= sizeof(uint64_t);
record_metadata[0].FinalizeForInsert(offset, 0, sizeof(uint64_t));
memcpy(reinterpret_cast<char *>(this) + offset, &left_most_child_addr, sizeof(uint64_t));
++insert_idx;
}
assert(nr_records > 0);
for (uint32_t i = begin_meta_idx; i < begin_meta_idx + nr_records; ++i) {
RecordMetadata meta = src_node->record_metadata[i];
assert(meta.IsVisible());
uint64_t m_payload = 0;
char *m_key = nullptr;
char *m_data = nullptr;
src_node->GetRawRecord(meta, &m_data, &m_key, &m_payload);
auto m_key_size = meta.GetKeyLength();
if (!need_insert_new) {
// New key already inserted, so directly insert the key from src node
assert(meta.GetTotalLength() >= sizeof(uint64_t));
offset -= (meta.GetTotalLength());
record_metadata[insert_idx].FinalizeForInsert(offset, m_key_size, meta.GetTotalLength());
memcpy(reinterpret_cast<char *>(this) + offset, m_data, meta.GetTotalLength());
} else {
// Compare the two keys to see which one to insert (first)
auto cmp = KeyCompare(m_key, m_key_size, key, key_size);
ALWAYS_ASSERT(!(cmp == 0 && key_size == m_key_size));
if (cmp > 0) {
assert(insert_idx >= 1);
// Modify the previous key's payload to left_child_addr
auto prev_meta = record_metadata[insert_idx - 1];
memcpy(reinterpret_cast<char *>(this) +
prev_meta.GetOffset() + prev_meta.GetPaddedKeyLength(),
&left_child_addr, sizeof(left_child_addr));
// Now the new separtor key itself
offset -= (padded_key_size + sizeof(right_child_addr));
record_metadata[insert_idx].FinalizeForInsert(
offset, key_size, padded_key_size + sizeof(left_child_addr));
++insert_idx;
memcpy(reinterpret_cast<char *>(this) + offset, key, key_size);
memcpy(reinterpret_cast<char *>(this) + offset + padded_key_size,
&right_child_addr, sizeof(right_child_addr));
offset -= (meta.GetTotalLength());
assert(meta.GetTotalLength() >= sizeof(uint64_t));
record_metadata[insert_idx].FinalizeForInsert(offset, m_key_size, meta.GetTotalLength());
memcpy(reinterpret_cast<char *>(this) + offset, m_data, meta.GetTotalLength());
need_insert_new = false;
} else {
assert(meta.GetTotalLength() >= sizeof(uint64_t));
offset -= (meta.GetTotalLength());
record_metadata[insert_idx].FinalizeForInsert(offset, m_key_size, meta.GetTotalLength());
memcpy(reinterpret_cast<char *>(this) + offset, m_data, meta.GetTotalLength());
}
}
++insert_idx;
}
if (need_insert_new) {
// The new key-payload pair will be the right-most (largest key) element
uint32_t total_size = RecordMetadata::PadKeyLength(key_size) + sizeof(uint64_t);
offset -= total_size;
record_metadata[insert_idx].FinalizeForInsert(offset, key_size, total_size);
memcpy(reinterpret_cast<char *>(this) + offset, key, key_size);
memcpy(reinterpret_cast<char *>(this) + offset + RecordMetadata::PadKeyLength(key_size),
&right_child_addr, sizeof(right_child_addr));
// Modify the previous key's payload to left_child_addr
auto prev_meta = record_metadata[insert_idx - 1];
memcpy(reinterpret_cast<char *>(this) + prev_meta.GetOffset() + prev_meta.GetPaddedKeyLength(),
&left_child_addr, sizeof(left_child_addr));
++insert_idx;
}
header.size = node_size;
header.sorted_count = insert_idx;
}
// Insert record to this internal node. The node is frozen at this time.
bool InternalNode::PrepareForSplit(Stack &stack,
uint32_t split_threshold,
const char *key,
uint32_t key_size,
uint64_t left_child_addr, // [key]'s left child pointer
uint64_t right_child_addr, // [key]'s right child pointer
InternalNode **new_node,
pmwcas::Descriptor *pd,
pmwcas::DescriptorPool *pool,
bool backoff) {
uint32_t data_size = header.size + key_size +
sizeof(right_child_addr) + sizeof(RecordMetadata);
uint32_t new_node_size = sizeof(InternalNode) + data_size;
if (new_node_size < split_threshold) {
// good boy
InternalNode::New(this, key, key_size, left_child_addr,
right_child_addr, new_node);
return true;
}
// After adding a key and pointers the new node would be too large. This
// means we are effectively 'moving up' the tree to do split
// So now we split the node and generate two new internal nodes
ALWAYS_ASSERT(header.sorted_count >= 2);
uint32_t n_left = header.sorted_count >> 1;
auto i_left = pd->ReserveAndAddEntry(
reinterpret_cast<uint64_t *>(pmwcas::Descriptor::kAllocNullAddress),
reinterpret_cast<uint64_t>(nullptr),
pmwcas::Descriptor::kRecycleOnRecovery);
auto i_right = pd->ReserveAndAddEntry(
reinterpret_cast<uint64_t *>(pmwcas::Descriptor::kAllocNullAddress),
reinterpret_cast<uint64_t>(nullptr),
pmwcas::Descriptor::kRecycleOnRecovery);
uint64_t *ptr_l = pd->GetNewValuePtr(i_left);
uint64_t *ptr_r = pd->GetNewValuePtr(i_right);
// Figure out where the new key will go
auto separator_meta = record_metadata[n_left];
char *separator_key = nullptr;
uint16_t separator_key_size = separator_meta.GetKeyLength();
uint64_t separator_payload = 0;
bool success = GetRawRecord(separator_meta, nullptr, &separator_key,
&separator_payload);
ALWAYS_ASSERT(success);
int cmp = KeyCompare(key, key_size, separator_key, separator_key_size);
if (cmp == 0) {
cmp = key_size - separator_key_size;
}
ALWAYS_ASSERT(cmp != 0);
if (cmp < 0) {
// Should go to left
InternalNode::New(this, 0, n_left, key, key_size,
left_child_addr, right_child_addr,
reinterpret_cast<InternalNode **>(ptr_l), 0);
InternalNode::New(this, n_left + 1, header.sorted_count - n_left - 1,
nullptr, 0, 0, 0,
reinterpret_cast<InternalNode **>(ptr_r), separator_payload);
} else {
InternalNode::New(this, 0, n_left, nullptr, 0, 0, 0,
reinterpret_cast<InternalNode **>(ptr_l), 0);
InternalNode::New(this, n_left + 1, header.sorted_count - n_left - 1,
key, key_size, left_child_addr, right_child_addr,
reinterpret_cast<InternalNode **>(ptr_r), separator_payload);
}
assert(*ptr_l);
assert(*ptr_r);
// Pop here as if this were a leaf node so that when we get back to the
// original caller, we get stack top as the "parent"
stack.Pop();
// Now get this internal node's real parent
InternalNode *parent = stack.Top() ?
stack.Top()->node : nullptr;
if (parent == nullptr) {
// Good!
InternalNode::New(separator_key, separator_key_size,
(uint64_t) *ptr_l, (uint64_t) *ptr_r, new_node);
return true;
}
__builtin_prefetch((const void *) (parent), 0, 2);
// Try to freeze the parent node first
bool frozen_by_me = false;
while (!parent->IsFrozen()) {
frozen_by_me = parent->Freeze(pool);
}
// Someone else froze the parent node and we are told not to compete with
// others (for now)
if (!frozen_by_me && backoff) {
return false;
}
return parent->PrepareForSplit(stack, split_threshold,
separator_key, separator_key_size,
(uint64_t) *ptr_l, (uint64_t) *ptr_r,
new_node, pd, pool, backoff);
}
void LeafNode::New(LeafNode **mem, uint32_t node_size) {
#ifdef PMDK
Allocator::Get()->AllocateDirect(reinterpret_cast<void **>(mem), node_size);
memset(*mem, 0, node_size);
new(*mem)LeafNode(node_size);
pmwcas::NVRAM::Flush(node_size, *mem);
*mem = Allocator::Get()->GetOffset(*mem);
#else
pmwcas::Allocator::Get()->Allocate(reinterpret_cast<void **>(mem), node_size);
memset(*mem, 0, node_size);
new(*mem) LeafNode(node_size);
#ifdef PMEM
pmwcas::NVRAM::Flush(node_size, *mem);
#endif // PMEM
#endif // PMDK
}
void BaseNode::Dump(pmwcas::EpochManager *epoch) {
std::cout << "-----------------------------" << std::endl;
std::cout << " Dumping node: " << this << (is_leaf ? " (leaf)" : " (internal)") << std::endl;
std::cout << " Header:\n";
if (is_leaf) {
std::cout << " - free space: " << (reinterpret_cast<LeafNode *>(this))->GetFreeSpace()
<< std::endl;
}
std::cout << " - status: 0x" << std::hex << header.status.word << std::endl
<< " (control = 0x" << (header.status.word & NodeHeader::StatusWord::kControlMask)
<< std::dec
<< ", frozen = " << header.status.IsFrozen()
<< ", block size = " << header.status.GetBlockSize()
<< ", delete size = " << header.status.GetDeletedSize()
<< ", record count = " << header.status.GetRecordCount() << ")\n"
<< " - sorted_count: " << header.sorted_count
<< std::endl;
std::cout << " - size: " << header.size << std::endl;
std::cout << " Record Metadata Array:" << std::endl;
uint32_t n_meta = std::max<uint32_t>(header.status.GetRecordCount(), header.sorted_count);
for (uint32_t i = 0; i < n_meta; ++i) {
RecordMetadata meta = record_metadata[i];
std::cout << " - record " << i << ": meta = 0x" << std::hex << meta.meta << std::endl;
std::cout << std::hex;
std::cout << " (control = 0x" << (meta.meta & RecordMetadata::kControlMask)
<< std::dec
<< ", visible = " << meta.IsVisible()
<< ", offset = " << meta.GetOffset()
<< ", key length = " << meta.GetKeyLength()
<< ", total length = " << meta.GetTotalLength()
<< std::endl;
}
}
void LeafNode::Dump(pmwcas::EpochManager *epoch) {
BaseNode::Dump(epoch);
std::cout << " Key-Payload Pairs:" << std::endl;
for (uint32_t i = 0; i < header.status.GetRecordCount(); ++i) {
RecordMetadata meta = record_metadata[i];
if (meta.IsVisible()) {
uint64_t payload = 0;
char *key = nullptr;
GetRawRecord(meta, &key, &payload, epoch);
assert(key);
std::string keystr(key, key + meta.GetKeyLength());
std::cout << " - record " << i << ": key = " << keystr
<< ", payload = " << payload << std::endl;
}
}
std::cout << "-----------------------------" << std::endl;
}
void InternalNode::Dump(pmwcas::EpochManager *epoch, bool dump_children) {
BaseNode::Dump(epoch);
std::cout << " Child pointers and separator keys:" << std::endl;
assert(header.status.GetRecordCount() == 0);
for (uint32_t i = 0; i < header.sorted_count; ++i) {
auto &meta = record_metadata[i];
assert((i == 0 && meta.GetKeyLength() == 0) || (i > 0 && meta.GetKeyLength() > 0));
uint64_t right_child_addr = 0;
char *key = nullptr;
GetRawRecord(meta, nullptr, &key, &right_child_addr);
if (key) {
std::string keystr(key, key + meta.GetKeyLength());
std::cout << " || " << keystr << " | ";
}
std::cout << std::hex << "0x" << right_child_addr << std::dec;
}
std::cout << std::endl;
if (dump_children) {
for (uint32_t i = 0; i < header.sorted_count; ++i) {
uint64_t node_addr = *GetPayloadPtr(record_metadata[i]);
#ifdef PMDK
BaseNode *node = Allocator::Get()->GetDirect(reinterpret_cast<BaseNode *>(node_addr));
#else
BaseNode *node = reinterpret_cast<BaseNode *>(node_addr);
#endif
if (node->IsLeaf()) {
(reinterpret_cast<LeafNode *>(node))->Dump(epoch);
} else {
(reinterpret_cast<InternalNode *>(node))->Dump(epoch, true);
}
}
}
}
ReturnCode LeafNode::Insert(const char *key, uint16_t key_size, uint64_t payload,
pmwcas::DescriptorPool *pmwcas_pool, uint32_t split_threshold) {
retry:
NodeHeader::StatusWord expected_status = header.GetStatus();
// If frozon then retry
if (expected_status.IsFrozen()) {
return ReturnCode::NodeFrozen();
}
auto uniqueness = CheckUnique(key, key_size, pmwcas_pool->GetEpoch());
if (uniqueness == Duplicate) {
return ReturnCode::KeyExists();
}
// Check space to see if we need to split the node
auto new_size = LeafNode::GetUsedSpace(expected_status) + sizeof(RecordMetadata) +
RecordMetadata::PadKeyLength(key_size) + sizeof(payload);
if (new_size >= split_threshold) {
return ReturnCode::NotEnoughSpace();
}
// Now try to reserve space in the free space region using a PMwCAS. Two steps:
// Step 1. Incrementing the record count and block size fields in [status]
// Step 2. Flip the record metadata entry's high order bit and fill in global
// epoch
NodeHeader::StatusWord desired_status = expected_status;
// Block size includes both key and payload sizes
auto padded_key_size = RecordMetadata::PadKeyLength(key_size);
auto total_size = padded_key_size + sizeof(payload);
desired_status.PrepareForInsert(total_size);
// Get the tentative metadata entry (again, make a local copy to work on it)
RecordMetadata *meta_ptr = &record_metadata[expected_status.GetRecordCount()];
RecordMetadata expected_meta = *meta_ptr;
if (!expected_meta.IsVacant()) {
goto retry;
}
RecordMetadata desired_meta;
desired_meta.PrepareForInsert();
// Now do the PMwCAS
pmwcas::Descriptor *pd = pmwcas_pool->AllocateDescriptor();
pd->AddEntry(&(&header.status)->word, expected_status.word, desired_status.word);
pd->AddEntry(&meta_ptr->meta, expected_meta.meta, desired_meta.meta);
if (!pd->MwCAS()) {
goto retry;
}
// Reserved space! Now copy data
// The key size must be padded to 64bit
uint64_t offset = header.size - desired_status.GetBlockSize();
char *ptr = &(reinterpret_cast<char *>(this))[offset];
memcpy(ptr, key, key_size);
memcpy(ptr + padded_key_size, &payload, sizeof(payload));
// Flush the word
#ifdef PMEM
pmwcas::NVRAM::Flush(total_size, ptr);
#endif
retry_phase2:
// Re-check if the node is frozen
if (uniqueness == ReCheck) {
auto new_uniqueness = RecheckUnique(key, key_size,
expected_status.GetRecordCount());
if (new_uniqueness == Duplicate) {
memset(ptr, 0, key_size);
memset(ptr + padded_key_size, 0, sizeof(payload));
offset = 0;
} else if (new_uniqueness == NodeFrozen) {
return ReturnCode::NodeFrozen();
}
}
// Final step: make the new record visible, a 2-word PMwCAS:
// 1. Metadata - set the visible bit and actual block offset
// 2. Status word - set to the initial value read above (s) to detect
// conflicting threads that are trying to set the frozen bit
auto new_meta = desired_meta;
new_meta.FinalizeForInsert(offset, key_size, total_size);
assert(new_meta.GetTotalLength() < 100);
NodeHeader::StatusWord s = header.GetStatus();
if (s.IsFrozen()) {
return ReturnCode::NodeFrozen();
}
pd = pmwcas_pool->AllocateDescriptor();
pd->AddEntry(&(&header.status)->word, s.word, s.word);
pd->AddEntry(&meta_ptr->meta, desired_meta.meta, new_meta.meta);
if (pd->MwCAS()) {
return ReturnCode::Ok();
} else {
goto retry_phase2;
}
}
LeafNode::Uniqueness LeafNode::CheckUnique(const char *key,
uint32_t key_size,
pmwcas::EpochManager *epoch) {
auto metadata = SearchRecordMeta(epoch, key, key_size, nullptr);
if (metadata.IsVacant()) {
return IsUnique;
}
// we need to perform a key compare again
// consider this case:
// a key is inserting when we "SearchRecordMeta"
// when get back, this meta may have finished inserting, so the following if will be false
// however, this key may not be duplicate, so we need to compare the key again
// even if this key is not duplicate, we need to return a "Recheck"
if (metadata.IsInserting()) {
return ReCheck;
}
ALWAYS_ASSERT(metadata.IsVisible());
if (KeyCompare(key, key_size, GetKey(metadata), metadata.GetKeyLength()) == 0) {
return Duplicate;
}
return ReCheck;
}
LeafNode::Uniqueness LeafNode::RecheckUnique(const char *key, uint32_t key_size, uint32_t end_pos) {
auto current_status = GetHeader()->GetStatus();
if (current_status.IsFrozen()) {
return NodeFrozen;
}
// Linear search on unsorted field
uint32_t linear_end = std::min<uint32_t>(header.GetStatus().GetRecordCount(), end_pos);
static std::vector<uint32_t> check_idx;
check_idx.clear();
auto check_metadata = [key, key_size, this](uint32_t i, bool push) -> LeafNode::Uniqueness {
RecordMetadata md = GetMetadata(i);
if (md.IsInserting()) {
if (push) {
check_idx.push_back(i);
}
return ReCheck;
} else if (md.IsVacant() || !md.IsVisible()) {
return IsUnique;
} else {
ALWAYS_ASSERT(md.IsVisible());
auto len = md.GetKeyLength();
if (key_size == len && (KeyCompare(key, key_size, GetKey(md), len) == 0)) {
return Duplicate;
}
return IsUnique;
}
};
for (uint32_t i = header.sorted_count; i < linear_end; i++) {
if (check_metadata(i, true) == Duplicate) {
return Duplicate;
}
}
uint32_t need_check = check_idx.size();
while (need_check > 0) {
for (uint32_t i = 0; i < check_idx.size(); ++i) {
auto result = check_metadata(i, false);
if (result == Duplicate) {
return Duplicate;
} else if (result != ReCheck) {
--need_check;
}
}
}
return IsUnique;
}
ReturnCode LeafNode::Update(const char *key,
uint16_t key_size,
uint64_t payload,
pmwcas::DescriptorPool *pmwcas_pool) {
retry:
auto old_status = header.GetStatus();
if (old_status.IsFrozen()) {
return ReturnCode::NodeFrozen();
}
RecordMetadata *meta_ptr = nullptr;
auto metadata = SearchRecordMeta(pmwcas_pool->GetEpoch(), key, key_size, &meta_ptr);
if (metadata.IsVacant()) {
return ReturnCode::NotFound();
} else if (metadata.IsInserting()) {
goto retry;
}
char *record_key = nullptr;
uint64_t record_payload = 0;
GetRawRecord(metadata, &record_key, &record_payload, pmwcas_pool->GetEpoch());
if (payload == record_payload) {
return ReturnCode::Ok();
}
// 1. Update the corresponding payload
// 2. Make sure meta data is not changed
// 3. Make sure status word is not changed
auto pd = pmwcas_pool->AllocateDescriptor();
pd->AddEntry(reinterpret_cast<uint64_t *>(record_key + metadata.GetPaddedKeyLength()),
record_payload, payload);
pd->AddEntry(&meta_ptr->meta, metadata.meta, metadata.meta);
pd->AddEntry(&(&header.status)->word, old_status.word, old_status.word);
if (!pd->MwCAS()) {
goto retry;
}
return ReturnCode::Ok();
}
RecordMetadata BaseNode::SearchRecordMeta(pmwcas::EpochManager *epoch,
const char *key,
uint32_t key_size,
RecordMetadata **out_metadata_ptr,
uint32_t start_pos,
uint32_t end_pos,
bool check_concurrency) {
// Binary search on sorted field
for (uint32_t i = 0; i < header.sorted_count; i++) {
RecordMetadata current = GetMetadata(i);
char *current_key = GetKey(current);
assert(current_key || !is_leaf);
auto cmp_result = KeyCompare(key, key_size, current_key, current.GetKeyLength());
if (cmp_result == 0) {
if (!current.IsVisible()) {
break;
}
if (out_metadata_ptr) {
*out_metadata_ptr = record_metadata + i;
}
return current;
}
}
// Linear search on unsorted field
// uint32_t linear_end = std::min<uint32_t>(header.GetStatus().GetRecordCount(), end_pos);
for (uint32_t i = header.sorted_count; i < header.GetStatus().GetRecordCount(); i++) {
RecordMetadata current = GetMetadata(i);
if (current.IsInserting()) {
if (check_concurrency) {
// Encountered an in-progress insert, recheck later
if (out_metadata_ptr) {
*out_metadata_ptr = record_metadata + i;
}
return current;
} else {
continue;
}
}
if (current.IsVisible()) {
auto current_size = current.GetKeyLength();
if (current_size == key_size &&
KeyCompare(key, key_size, GetKey(current), current_size) == 0) {
if (out_metadata_ptr) {
*out_metadata_ptr = record_metadata + i;
}
return current;
}
}
}
return RecordMetadata{0};
}
ReturnCode LeafNode::Delete(const char *key,
uint16_t key_size,
pmwcas::DescriptorPool *pmwcas_pool) {
retry:
NodeHeader::StatusWord old_status = header.GetStatus();
if (old_status.IsFrozen()) {
return ReturnCode::NodeFrozen();
}
RecordMetadata *meta_ptr = nullptr;
auto metadata = SearchRecordMeta(pmwcas_pool->GetEpoch(), key, key_size, &meta_ptr);
if (metadata.IsVacant()) {
return ReturnCode::NotFound();
} else if (metadata.IsInserting()) {
// FIXME(hao): not mentioned in the paper, should confirm later;
goto retry;
}
auto new_meta = metadata;
new_meta.SetVisible(false);
auto new_status = old_status;
auto old_delete_size = old_status.GetDeletedSize();
new_status.SetDeleteSize(old_delete_size + metadata.GetTotalLength());
pmwcas::Descriptor *pd = pmwcas_pool->AllocateDescriptor();
pd->AddEntry(&(&header.status)->word, old_status.word, new_status.word);
pd->AddEntry(&meta_ptr->meta, metadata.meta, new_meta.meta);
if (!pd->MwCAS()) {
goto retry;
}
return ReturnCode::Ok();
}
ReturnCode LeafNode::Read(const char *key, uint16_t key_size, uint64_t *payload,
pmwcas::DescriptorPool *pmwcas_pool) {
auto meta = SearchRecordMeta(pmwcas_pool->GetEpoch(), key, key_size, nullptr,
0, (uint32_t) -1, false);
if (meta.IsVacant()) {
return ReturnCode::NotFound();
}
char *source_addr = (reinterpret_cast<char *>(this) + meta.GetOffset());
*payload = reinterpret_cast<pmwcas::MwcTargetField<uint64_t> *>(
source_addr + meta.GetPaddedKeyLength())->GetValueProtected();
return ReturnCode::Ok();
}
ReturnCode LeafNode::RangeScanBySize(const char *key1,
uint32_t size1,
uint32_t to_scan,
std::list<std::unique_ptr<Record>> *result,
pmwcas::DescriptorPool *pmwcas_pool) {
static std::vector<Record *> tmp_result;
tmp_result.clear();
if (to_scan == 0) {
return ReturnCode::Ok();
}
// Enter a new epoch and copy data
pmwcas::EpochGuard guard(pmwcas_pool->GetEpoch());
// Have to scan all keys
auto count = header.GetStatus().GetRecordCount();
for (uint32_t i = 0; i < count; ++i) {
auto curr_meta = GetMetadata(i);
if (curr_meta.IsVisible()) {
int cmp = KeyCompare(key1, size1, GetKey(curr_meta), curr_meta.GetKeyLength());
if (cmp <= 0) {
tmp_result.emplace_back(Record::New(curr_meta, this));
}
}
}
std::sort(tmp_result.begin(), tmp_result.end(),
[this](Record *a, Record *b) -> bool {
auto cmp = KeyCompare(a->GetKey(), a->meta.GetKeyLength(),
b->GetKey(), b->meta.GetKeyLength());
return cmp < 0;
});
for (auto item : tmp_result) {
result->emplace_back(item);
}
return ReturnCode::Ok();
}
ReturnCode LeafNode::RangeScanByKey(const char *key1,
uint32_t size1,
const char *key2,
uint32_t size2,
std::vector<Record *> *result,
pmwcas::DescriptorPool *pmwcas_pool) {
// entering a new epoch and copying the data
pmwcas::EpochGuard guard(pmwcas_pool->GetEpoch());
// scan the sorted fields first
uint32_t i = 0;
auto count = header.GetStatus().GetRecordCount();
while (i < count) {
auto curr_meta = GetMetadata(i);
if (!curr_meta.IsVisible()) {
i += 1;
continue;
}
char *curr_key;
GetRawRecord(curr_meta, &curr_key, nullptr, pmwcas_pool->GetEpoch());
auto range_code = KeyInRange(curr_key, curr_meta.GetKeyLength(), key1, size1, key2, size2);
if (range_code == 0) {
result->emplace_back(Record::New(curr_meta, this));
} else if (range_code == 1 && i < header.sorted_count) {
// current key is larger than upper bound
// jump to the unsorted field
i = header.sorted_count;
continue;
}
i += 1;
}
std::sort(result->begin(), result->end(),
[this](Record *a, Record *b) -> bool {
auto cmp = BaseNode::KeyCompare(a->GetKey(), a->meta.GetKeyLength(),
b->GetKey(), b->meta.GetKeyLength());
return cmp < 0;
});
return ReturnCode::Ok();
}
bool BaseNode::Freeze(pmwcas::DescriptorPool *pmwcas_pool) {
NodeHeader::StatusWord expected = header.GetStatus();
if (expected.IsFrozen()) {
return false;
}
pmwcas::Descriptor *pd = pmwcas_pool->AllocateDescriptor();
pd->AddEntry(&(&header.status)->word, expected.word, expected.Freeze().word);
return pd->MwCAS();
}
LeafNode *LeafNode::Consolidate(pmwcas::DescriptorPool *pmwcas_pool) {
// Freeze the node to prevent new modifications first
if (!Freeze(pmwcas_pool)) {
return nullptr;
}
static std::vector<RecordMetadata> meta_vec;
meta_vec.clear();
SortMetadataByKey(meta_vec, true, pmwcas_pool->GetEpoch());
// Allocate and populate a new node
LeafNode *new_leaf = nullptr;
LeafNode::New(&new_leaf, this->header.size);
new_leaf->CopyFrom(this, meta_vec.begin(), meta_vec.end(), pmwcas_pool->GetEpoch());
#ifdef PMEM
pmwcas::NVRAM::Flush(this->header.size, new_leaf);
#endif
return new_leaf;
}
uint32_t LeafNode::SortMetadataByKey(std::vector<RecordMetadata> &vec,
bool visible_only,
pmwcas::EpochManager *epoch) {
// Node is frozen at this point
// there should not be any on-going pmwcas
assert(header.status.IsFrozen());
uint32_t total_size = 0;
uint32_t count = header.GetStatus().GetRecordCount();
for (uint32_t i = 0; i < count; ++i) {
// TODO(tzwang): handle deletes
auto meta = record_metadata[i];
if (meta.IsVisible()) {
vec.emplace_back(meta);
total_size += (meta.GetTotalLength());
assert(meta.GetTotalLength());
}
}
// Lambda for comparing two keys
auto key_cmp = [this](RecordMetadata &m1, RecordMetadata &m2) -> bool {
auto l1 = m1.GetKeyLength();
auto l2 = m2.GetKeyLength();
char *k1 = GetKey(m1);
char *k2 = GetKey(m2);
return KeyCompare(k1, l1, k2, l2) < 0;
};
std::sort(vec.begin(), vec.end(), key_cmp);
return total_size;
}
void LeafNode::CopyFrom(LeafNode *node,
std::vector<RecordMetadata>::iterator begin_it,
std::vector<RecordMetadata>::iterator end_it,
pmwcas::EpochManager *epoch) {
// meta_vec is assumed to be in sorted order, insert records one by one
uint32_t offset = this->header.size;
uint16_t nrecords = 0;
for (auto it = begin_it; it != end_it; ++it) {
auto meta = *it;
uint64_t payload = 0;
char *key;
node->GetRawRecord(meta, &key, &payload, epoch);
// Copy data
assert(meta.GetTotalLength() >= sizeof(uint64_t));
uint64_t total_len = meta.GetTotalLength();
assert(offset >= total_len);
offset -= total_len;
char *ptr = &(reinterpret_cast<char *>(this))[offset];
memcpy(ptr, key, total_len);
// Setup new metadata
record_metadata[nrecords].FinalizeForInsert(offset, meta.GetKeyLength(), total_len);
++nrecords;
}
// Finalize header stats
header.status.SetBlockSize(this->header.size - offset);
header.status.SetRecordCount(nrecords);
header.sorted_count = nrecords;
#ifdef PMDK
Allocator::Get()->PersistPtr(this, this->header.size);
#endif
}
void InternalNode::DeleteRecord(uint32_t meta_to_update,
uint64_t new_child_ptr,
bztree::InternalNode **new_node) {
uint32_t meta_to_delete = meta_to_update + 1;
uint32_t offset = this->header.size -
this->record_metadata[meta_to_delete].GetTotalLength() - sizeof(RecordMetadata);
InternalNode::New(new_node, offset);
uint32_t insert_idx = 0;
for (uint32_t i = 0; i < this->header.sorted_count; i += 1) {
if (i == meta_to_delete) {
continue;
}
RecordMetadata meta = record_metadata[i];
uint64_t m_payload = 0;
char *m_key = nullptr;
char *m_data = nullptr;