This repository has been archived by the owner on Sep 27, 2019. It is now read-only.
/
bwtree.h
executable file
·9086 lines (7516 loc) · 314 KB
/
bwtree.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
//===----------------------------------------------------------------------===//
//
// Peloton
//
// bwtree.h
//
// Identification: src/include/index/bwtree.h
//
// Copyright (c) 2015-2018, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//
//
// NOTE: If you encounter any bug, assertion failure, segment fault or
// other anomalies, please contact:
//
// Ziqi Wang
// ziqiw a.t. andrew.cmu.edu
//
// in order to get a quick response and diagnosis
//
//===----------------------------------------------------------------------===//
#ifndef _BWTREE_H
#define _BWTREE_H
#pragma once
#include <algorithm>
#include <array>
#include <atomic>
#include <chrono>
#include <thread>
#include <unordered_set>
// offsetof() is defined here
#include <cstddef>
#include <vector>
#include <sys/mman.h>
/*
* BWTREE_PELOTON - Specifies whether Peloton-specific features are
* Compiled or not
* We strive to make BwTree a standalone and independent
* module that can be plugged-and-played in any situation
*/
#define BWTREE_PELOTON
/*
* BWTREE_NODEBUG - This flag disables usage of print_flag, which greatly
* reduces performance
*/
#define BWTREE_NODEBUG
#ifdef BWTREE_PELOTON
#include "index/index.h"
#endif
// This must be declared before all include directives
#include <inttypes.h>
using NodeID = uint64_t;
#include "sorted_small_set.h"
#include "bloom_filter.h"
#include "atomic_stack.h"
// We use this to control from the compiler
#ifndef BWTREE_NODEBUG
/*
* BWTREE_DEBUG - This flag enables assertions that check for
* structural consistency
*
* REMOVING THIS FLAG FOR RELEASE
*/
#define BWTREE_DEBUG
#endif
/*
* ALL_PUBLIC - This flag makes all private members become public
* to simplify debugging
*/
#define ALL_PUBLIC
/*
* USE_OLD_EPOCH - This flag switches between old epoch and new epoch mechanism
*/
#define USE_OLD_EPOCH
/*
* BWTREE_TEMPLATE_ARGUMENTS - Save some key strokes
*/
#define BWTREE_TEMPLATE_ARGUMENTS \
template <typename KeyType, typename ValueType, typename KeyComparator, \
typename KeyEqualityChecker, typename KeyHashFunc, \
typename ValueEqualityChecker, typename ValueHashFunc>
#ifdef BWTREE_PELOTON
namespace peloton {
namespace index {
#else
namespace wangziqi2013 {
namespace bwtree {
#endif
// This could not be set as a macro since we will change the flag inside
// the testing framework
extern bool print_flag;
// This constant represents INVALID_NODE_ID which is used as an indication
// that the node is actually the last node on that level
#define INVALID_NODE_ID ((NodeID)0UL)
// The NodeID for the first leaf is fixed, which is 2
#define FIRST_LEAF_NODE_ID ((NodeID)2UL)
// This is the value we use in epoch manager to make sure
// no thread sneaking in while GC decision is being made
#define MAX_THREAD_COUNT ((int)0x7FFFFFFF)
// The maximum number of nodes we could map in this index
#define MAPPING_TABLE_SIZE ((size_t)(1 << 20))
// If the length of delta chain exceeds ( >= ) this then we consolidate the node
#define INNER_DELTA_CHAIN_LENGTH_THRESHOLD ((int)8)
#define LEAF_DELTA_CHAIN_LENGTH_THRESHOLD ((int)8)
// If node size goes above this then we split it
#define INNER_NODE_SIZE_UPPER_THRESHOLD ((int)128)
#define INNER_NODE_SIZE_LOWER_THRESHOLD ((int)32)
#define LEAF_NODE_SIZE_UPPER_THRESHOLD ((int)128)
#define LEAF_NODE_SIZE_LOWER_THRESHOLD ((int)32)
#define PREALLOCATE_THREAD_NUM ((size_t)1024)
/*
* InnerInlineAllocateOfType() - allocates a chunk of memory from base node and
* initialize it using placement new and then
* return its pointer
*
* This is used for InnerNode delta chains
*/
#define InnerInlineAllocateOfType(T, node_p, ...) \
(static_cast<T *>(new (ElasticNode<KeyNodeIDPair>::InlineAllocate( \
&node_p->GetLowKeyPair(), sizeof(T))) T{__VA_ARGS__}))
/*
* LeafInlineAllocateOfType() - allocates a chunk of memory from base node and
* initialize it using placement new and then
* return its pointer
*
* This is used for LeafNode delta chains
*/
#define LeafInlineAllocateOfType(T, node_p, ...) \
(static_cast<T *>(new (ElasticNode<KeyValuePair>::InlineAllocate( \
&node_p->GetLowKeyPair(), sizeof(T))) T{__VA_ARGS__}))
/*
* class BwTreeBase - Base class of BwTree that stores some common members
*/
class BwTreeBase {
public:
// This is the presumed size of cache line
static constexpr size_t CACHE_LINE_SIZE = 64;
// This is the mask we used for address alignment (AND with this)
static constexpr size_t CACHE_LINE_MASK = ~(CACHE_LINE_SIZE - 1);
// We invoke the GC procedure after this has been reached
static constexpr size_t GC_NODE_COUNT_THREADHOLD = 1024;
/*
* class GarbageNode - Garbage node used to represent delayed allocation
*
* Note that since we could not know the actual definition of BaseNode here,
* all garbage pointer to BaseNode should be represented as void *, and are
* casted to appropriate type manually
*/
class GarbageNode {
public:
// The epoch that this node is unlinked
// This do not have to be exact - just make sure it is no earlier than the
// actual epoch it is unlinked from the data structure
uint64_t delete_epoch;
void *node_p;
GarbageNode *next_p;
/*
* Constructor
*/
GarbageNode(uint64_t p_delete_epoch, void *p_node_p)
: delete_epoch{p_delete_epoch}, node_p{p_node_p}, next_p{nullptr} {}
GarbageNode() : delete_epoch{0UL}, node_p{nullptr}, next_p{nullptr} {}
};
/*
* class GCMetaData - Metadata for performing GC on per-thread basis
*/
class GCMetaData {
public:
// This is the last active epoch counter; all garbages before this counter
// are guaranteed to be not being used by this thread
// So if we take a global minimum of this value, that minimum could be
// be used as the global epoch value to decide whether a garbage node could
// be recycled
uint64_t last_active_epoch;
// We only need a pointer
GarbageNode header;
// This points to the last node in the garbage node linked list
// We always append new nodes to this pointer, and thus inside one
// node's context these garbage nodes are always sorted, from low
// epoch to high epoch. This facilitates memory reclaimation since we
// just start from the lowest epoch garbage and traverse the linked list
// until we see an epoch >= GC epoch
GarbageNode *last_p;
// The number of nodes inside this GC context
// We use this as a threshold to trigger GC
uint64_t node_count;
/*
* Default constructor
*/
GCMetaData()
: last_active_epoch{0UL}, header{}, last_p{&header}, node_count{0UL} {}
};
// Make sure class Data does not exceed one cache line
static_assert(sizeof(GCMetaData) < CACHE_LINE_SIZE,
"class Data size exceeds cache line length!");
/*
* class PaddedData - Padded data to the length of a cache line
*/
template <typename DataType, size_t Alignment>
class PaddedData {
public:
// This is the alignment of padded data - we adjust its alignment
// after malloc() a chunk of memory
static constexpr size_t ALIGNMENT = Alignment;
// This is where real data goes
DataType data;
/*
* Default constructor - This is called if DataType could be initialized
* without any constructor
*/
PaddedData() : data{} {}
private:
char padding[ALIGNMENT - sizeof(DataType)];
};
using PaddedGCMetadata = PaddedData<GCMetaData, CACHE_LINE_SIZE>;
static_assert(sizeof(PaddedGCMetadata) == PaddedGCMetadata::ALIGNMENT,
"class PaddedGCMetadata size does"
" not conform to the alignment!");
public:
// This is used as the garbage collection ID, and is maintained in a per
// thread level
// This is initialized to -1 in order to distinguish between registered
// threads and unregistered threads
static thread_local int gc_id;
private:
// This is used to count the number of threads participating GC process
// We use this number to initialize GC data structure
static std::atomic<size_t> total_thread_num;
// This is the array being allocated for performing GC
// The allocation aligns its address to cache line boundary
PaddedGCMetadata *gc_metadata_p;
// We use this to compute aligned memory address to be
// used as the gc metadata array
unsigned char *original_p;
// This is the number of thread that this instance could support
size_t thread_num;
// This is current epoch
// We need to make it atomic since multiple threads might try to modify it
uint64_t epoch;
public:
/*
* DestroyThreadLocal() - Destroies thread local
*
* This function calls destructor for each metadata element and then
* frees the memory
*
* NOTE: We should also free all garbage nodes before this is called. However
* since we do not know the type of garbage nodes yet, we should call the
* function inside BwTree destructor
*
* This function must be called when the garbage pool is empty
*/
void DestroyThreadLocal() {
LOG_TRACE("Destroy %lu thread local slots", thread_num);
// There must already be metadata allocated
PELOTON_ASSERT(original_p != nullptr);
// Manually call destructor
for (size_t i = 0; i < thread_num; i++) {
PELOTON_ASSERT((gc_metadata_p + i)->data.header.next_p == nullptr);
(gc_metadata_p + i)->~PaddedGCMetadata();
}
// Free memory using original pointer rather than adjusted pointer
free(original_p);
return;
}
/*
* PrepareThreadLocal() - Initialize thread local variables
*
* This function uses thread_num to initialize number of threads
*/
void PrepareThreadLocal() {
LOG_TRACE("Preparing %lu thread local slots", thread_num);
// This is the unaligned base address
// We allocate one more element than requested as the buffer
// for doing alignment
original_p = static_cast<unsigned char *>(
malloc(CACHE_LINE_SIZE * (thread_num + 1)));
PELOTON_ASSERT(original_p != nullptr);
// Align the address to cache line boundary
gc_metadata_p = reinterpret_cast<PaddedGCMetadata *>(
(reinterpret_cast<size_t>(original_p) + CACHE_LINE_SIZE - 1) &
CACHE_LINE_MASK);
// Make sure it is aligned
PELOTON_ASSERT(((size_t)gc_metadata_p % CACHE_LINE_SIZE) == 0);
// Make sure we do not overflow the chunk of memory
PELOTON_ASSERT(((size_t)gc_metadata_p + thread_num * CACHE_LINE_SIZE) <=
((size_t)original_p + (thread_num + 1) * CACHE_LINE_SIZE));
// At last call constructor of the class; we use placement new
for (size_t i = 0; i < thread_num; i++) {
new (gc_metadata_p + i) PaddedGCMetadata{};
}
return;
}
/*
* SetThreadNum() - Sets number of threads manually
*/
void SetThreadNum(size_t p_thread_num) {
thread_num = p_thread_num;
return;
}
public:
/*
* Constructor - Initialize GC data structure
*/
BwTreeBase()
: gc_metadata_p{nullptr},
original_p{nullptr},
thread_num{total_thread_num.load()},
epoch{0UL} {
// Allocate memory for thread local data structure
PrepareThreadLocal();
return;
}
/*
* Destructor - Manually call destructor and then frees the memory
*/
~BwTreeBase() {
// Frees all metadata
DestroyThreadLocal();
LOG_TRACE("Finished destroying class BwTreeBase");
return;
}
/*
* GetThreadNum() - Returns the number of thread currently this instance of
* BwTree is serving
*/
inline size_t GetThreadNum() { return thread_num; }
/*
* AssignGCID() - Assigns a gc_id manually
*
* This is mainly used for debugging
*/
inline void AssignGCID(int p_gc_id) {
gc_id = p_gc_id;
return;
}
/*
* RegisterThread() - Registers a thread for GC for all instances of BwTree
* in the current process's address space
*
* This function assigns an ID to a thread starting from 0, which could be
* used as thread ID for the garbage collection process.
*
* Also note that only threads registered before an instance is created will
* be considered as being eligible for GC for that thread
*
* This function does not return any value, and instead it uses an atomic
* counter to counter the number of threads currently in this system, and
* assigns the thread ID to a thread local variable called gc_id decleared
* inside this class
*
* Each thread being allocated a GC ID has a context for garbage collection
* that is aligned to cache lines. The context will be allocated for every
* thread being registered, even if it has already exited. Therefore, this
* approach is only suitable for thread pools where the number of threads
* is fixed at startup time.
*/
static void RegisterThread() {
gc_id = total_thread_num.fetch_add(1);
return;
}
/*
* IncreaseEpoch() - Go to the next epoch by increasing the counter
*
* Note that this should not be called by worker threads since
* it will cause contention
*/
inline void IncreaseEpoch() {
epoch++;
return;
}
/*
* UpdateLastActiveEpoch() - Updates the last active epoch field of thread
* local storage
*
* This is the core of GC algorithm. Its implication is that all garbage nodes
* unlinked before this epoch could be safely collected since at the time
* the thread local counter is updated, we know all references to shared
* resources have been released
*/
inline void UpdateLastActiveEpoch() {
GetCurrentGCMetaData()->last_active_epoch = GetGlobalEpoch();
return;
}
/*
* UnregisterThread() - Unregisters a thread by setting its epoch to
* 0xFFFFFFFFFFFFFFFF such that it will not be considered
* for GC
*/
inline void UnregisterThread(int thread_id) {
GetGCMetaData(thread_id)->last_active_epoch = static_cast<uint64_t>(-1);
}
/*
* GetGlobalEpoch() - Returns the current global epoch counter
*
* Note that this function might return a stale value, which does not affect
* correctness as long as unlinking the node form data structure is atomic
* since all refreshing operations will read the same or smaller value
* when it reads the counter
*/
inline uint64_t GetGlobalEpoch() { return epoch; }
/*
* GetGCMetaData() - Returns the thread-local metadata for GC for a specified
* thread
*/
inline GCMetaData *GetGCMetaData(int thread_id) {
// The thread ID must be within the range
PELOTON_ASSERT(thread_id >= 0 && thread_id < static_cast<int>(thread_num));
return &(gc_metadata_p + thread_id)->data;
}
/*
* GetCurrentGCMetaData() - Returns the metadata for the current thread
*/
inline GCMetaData *GetCurrentGCMetaData() { return GetGCMetaData(gc_id); }
/*
* SummarizeGCEpoch() - Returns the minimum epochs among the current epoch
* counters of all threads
*
* Note that if this is called then it must be true that there are at least
* one thread participating into the GC process
*/
uint64_t SummarizeGCEpoch() {
PELOTON_ASSERT(thread_num >= 1);
// Use the first metadata's epoch as min and update it on the fly
uint64_t min_epoch = GetGCMetaData(0)->last_active_epoch;
// This might not be executed if there is only one thread
for (int i = 1; i < static_cast<int>(thread_num); i++) {
// This will be compiled into using CMOV which is more efficient
// than CMP and JMP
min_epoch = std::min(GetGCMetaData(i)->last_active_epoch, min_epoch);
}
return min_epoch;
}
};
/*
* class BwTree - Lock-free BwTree index implementation
*
* Template Arguments:
*
* template <typename KeyType,
* typename ValueType,
* typename KeyComparator = std::less<KeyType>,
* typename KeyEqualityChecker = std::equal_to<KeyType>,
* typename KeyHashFunc = std::hash<KeyType>,
* typename ValueEqualityChecker = std::equal_to<ValueType>,
* typename ValueHashFunc = std::hash<ValueType>>
*
* Explanation:
*
* - KeyType: Key type of the map
*
* - ValueType: Value type of the map. Note that it is possible
* that a single key is mapped to multiple values
*
* - KeyComparator: "less than" relation comparator for KeyType
* Returns true if "less than" relation holds
* *** NOTE: THIS OBJECT DO NOT NEED TO HAVE A DEFAULT
* CONSTRUCTOR. THIS MODIFICATION WAS MADE TO FIT
* INTO Peloton's ARCHITECTURE
* Please refer to main.cpp, class KeyComparator for more
* information on how to define a proper key comparator
*
* - KeyEqualityChecker: Equality checker for KeyType
* Returns true if two keys are equal
*
* - KeyHashFunc: Hashes KeyType into size_t. This is used in unordered_set
*
* - ValueEqualityChecker: Equality checker for value type
* Returns true for ValueTypes that are equal
*
* - ValueHashFunc: Hashes ValueType into a size_t
* This is used in unordered_set
*
* If not specified, then by default all arguments except the first two will
* be set as the standard operator in C++ (i.e. the operator for primitive types
* AND/OR overloaded operators for derived types)
*/
template <typename KeyType, typename ValueType,
typename KeyComparator = std::less<KeyType>,
typename KeyEqualityChecker = std::equal_to<KeyType>,
typename KeyHashFunc = std::hash<KeyType>,
typename ValueEqualityChecker = std::equal_to<ValueType>,
typename ValueHashFunc = std::hash<ValueType>>
class BwTree : public BwTreeBase {
/*
* Private & Public declaration
*/
#ifndef ALL_PUBLIC
private:
#else
public:
#endif
// This does not have to be the friend class of BwTree
class EpochManager;
public:
class BaseNode;
class NodeSnapshot;
class KeyNodeIDPairComparator;
class KeyNodeIDPairHashFunc;
class KeyNodeIDPairEqualityChecker;
class KeyValuePairHashFunc;
class KeyValuePairEqualityChecker;
/*
* private: Basic type definition
*/
#ifndef ALL_PUBLIC
private:
#else
public:
#endif
// KeyType-NodeID pair
using KeyNodeIDPair = std::pair<KeyType, NodeID>;
using KeyNodeIDPairSet =
std::unordered_set<KeyNodeIDPair, KeyNodeIDPairHashFunc,
KeyNodeIDPairEqualityChecker>;
using KeyNodeIDPairBloomFilter =
BloomFilter<KeyNodeIDPair, KeyNodeIDPairEqualityChecker,
KeyNodeIDPairHashFunc>;
// KeyType-ValueType pair
using KeyValuePair = std::pair<KeyType, ValueType>;
using KeyValuePairBloomFilter =
BloomFilter<KeyValuePair, KeyValuePairEqualityChecker,
KeyValuePairHashFunc>;
using ValueSet =
std::unordered_set<ValueType, ValueHashFunc, ValueEqualityChecker>;
using EpochNode = typename EpochManager::EpochNode;
/*
* enum class NodeType - Bw-Tree node type
*/
enum class NodeType : short {
// We separate leaf and inner into two different intervals
// to make it possible for compiler to optimize
InnerType = 0,
// Only valid for inner
InnerInsertType = 1,
InnerDeleteType = 2,
InnerSplitType = 3,
InnerRemoveType = 4,
InnerMergeType = 5,
InnerAbortType = 6, // Unconditional abort
LeafStart = 7,
// Data page type
LeafType = 7,
// Only valid for leaf
LeafInsertType = 8,
LeafSplitType = 9,
LeafDeleteType = 10,
LeafRemoveType = 11,
LeafMergeType = 12,
};
///////////////////////////////////////////////////////////////////
// Comparator, equality checker and hasher for key-NodeID pair
///////////////////////////////////////////////////////////////////
/*
* class KeyNodeIDPairComparator - Compares key-value pair for < relation
*
* Only key values are compares. However, we should use WrappedKeyComparator
* instead of the raw one, since there could be -Inf involved in inner nodes
*/
class KeyNodeIDPairComparator {
public:
const KeyComparator *key_cmp_obj_p;
/*
* Default constructor - deleted
*/
KeyNodeIDPairComparator() = delete;
/*
* Constructor - Initialize a key-NodeID pair comparator using
* wrapped key comparator
*/
KeyNodeIDPairComparator(BwTree *p_tree_p)
: key_cmp_obj_p{&p_tree_p->key_cmp_obj} {}
/*
* operator() - Compares whether a key NodeID pair is less than another
*
* We only compare keys since there should not be duplicated
* keys inside an inner node
*/
inline bool operator()(const KeyNodeIDPair &knp1,
const KeyNodeIDPair &knp2) const {
// First compare keys for relation
return (*key_cmp_obj_p)(knp1.first, knp2.first);
}
};
/*
* class KeyNodeIDPairEqualityChecker - Checks KeyNodeIDPair equality
*
* Only keys are checked since there should not be duplicated keys inside
* inner nodes. However we should always use wrapped key eq checker rather
* than wrapped raw key eq checker
*/
class KeyNodeIDPairEqualityChecker {
public:
const KeyEqualityChecker *key_eq_obj_p;
/*
* Default constructor - deleted
*/
KeyNodeIDPairEqualityChecker() = delete;
/*
* Constructor - Initialize a key node pair eq checker
*/
KeyNodeIDPairEqualityChecker(BwTree *p_tree_p)
: key_eq_obj_p{&p_tree_p->key_eq_obj} {}
/*
* operator() - Compares key-NodeID pair by comparing keys
*/
inline bool operator()(const KeyNodeIDPair &knp1,
const KeyNodeIDPair &knp2) const {
return (*key_eq_obj_p)(knp1.first, knp2.first);
}
};
/*
* class KeyNodeIDPairHashFunc - Hashes a key-NodeID pair into size_t
*/
class KeyNodeIDPairHashFunc {
public:
const KeyHashFunc *key_hash_obj_p;
/*
* Default constructor - deleted
*/
KeyNodeIDPairHashFunc() = delete;
/*
* Constructor - Initialize a key value pair hash function
*/
KeyNodeIDPairHashFunc(BwTree *p_tree_p)
: key_hash_obj_p{&p_tree_p->key_hash_obj} {}
/*
* operator() - Hashes a key-value pair by hashing each part and
* combine them into one size_t
*
* We use XOR to combine hashes of the key and value together into one
* single hash value
*/
inline size_t operator()(const KeyNodeIDPair &knp) const {
return (*key_hash_obj_p)(knp.first);
}
};
///////////////////////////////////////////////////////////////////
// Comparator, equality checker and hasher for key-value pair
///////////////////////////////////////////////////////////////////
/*
* class KeyValuePairComparator - Comparator class for KeyValuePair
*/
class KeyValuePairComparator {
public:
const KeyComparator *key_cmp_obj_p;
/*
* Default constructor - deleted
*/
KeyValuePairComparator() = delete;
/*
* Constructor
*/
KeyValuePairComparator(BwTree *p_tree_p)
: key_cmp_obj_p{&p_tree_p->key_cmp_obj} {}
/*
* operator() - Compares key-value pair by comparing each component
* of them
*
* NOTE: This function only compares keys with KeyType. For +/-Inf
* the wrapped raw key comparator will fail
*/
inline bool operator()(const KeyValuePair &kvp1,
const KeyValuePair &kvp2) const {
return (*key_cmp_obj_p)(kvp1.first, kvp2.first);
}
};
/*
* class KeyValuePairEqualityChecker - Checks KeyValuePair equality
*/
class KeyValuePairEqualityChecker {
public:
const KeyEqualityChecker *key_eq_obj_p;
const ValueEqualityChecker *value_eq_obj_p;
/*
* Default constructor - deleted
*/
KeyValuePairEqualityChecker() = delete;
/*
* Constructor - Initialize a key value pair equality checker with
* WrappedKeyEqualityChecker and ValueEqualityChecker
*/
KeyValuePairEqualityChecker(BwTree *p_tree_p)
: key_eq_obj_p{&p_tree_p->key_eq_obj},
value_eq_obj_p{&p_tree_p->value_eq_obj} {}
/*
* operator() - Compares key-value pair by comparing each component
* of them
*
* NOTE: This function only compares keys with KeyType. For +/-Inf
* the wrapped raw key comparator will fail
*/
inline bool operator()(const KeyValuePair &kvp1,
const KeyValuePair &kvp2) const {
return ((*key_eq_obj_p)(kvp1.first, kvp2.first)) &&
((*value_eq_obj_p)(kvp1.second, kvp2.second));
}
};
/*
* class KeyValuePairHashFunc - Hashes a key-value pair into size_t
*
* This is used as the hash function of unordered_map
*/
class KeyValuePairHashFunc {
public:
const KeyHashFunc *key_hash_obj_p;
const ValueHashFunc *value_hash_obj_p;
/*
* Default constructor - deleted
*/
KeyValuePairHashFunc() = delete;
/*
* Constructor - Initialize a key value pair hash function
*/
KeyValuePairHashFunc(BwTree *p_tree_p)
: key_hash_obj_p{&p_tree_p->key_hash_obj},
value_hash_obj_p{&p_tree_p->value_hash_obj} {}
/*
* operator() - Hashes a key-value pair by hashing each part and
* combine them into one size_t
*
* We use XOR to combine hashes of the key and value together into one
* single hash value
*/
inline size_t operator()(const KeyValuePair &kvp) const {
return ((*key_hash_obj_p)(kvp.first)) ^ ((*value_hash_obj_p)(kvp.second));
}
};
///////////////////////////////////////////////////////////////////
// Key Comparison Member Functions
///////////////////////////////////////////////////////////////////
/*
* KeyCmpLess() - Compare two keys for "less than" relation
*
* If key1 < key2 return true
* If not return false
*
* NOTE: In older version of the implementation this might be defined
* as the comparator to wrapped key type. However wrapped key has
* been removed from the newest implementation, and this function
* compares KeyType specified in template argument.
*/
inline bool KeyCmpLess(const KeyType &key1, const KeyType &key2) const {
return key_cmp_obj(key1, key2);
}
/*
* KeyCmpEqual() - Compare a pair of keys for equality
*
* This functions compares keys for equality relation
*/
inline bool KeyCmpEqual(const KeyType &key1, const KeyType &key2) const {
return key_eq_obj(key1, key2);
}
/*
* KeyCmpGreaterEqual() - Compare a pair of keys for >= relation
*
* It negates result of keyCmpLess()
*/
inline bool KeyCmpGreaterEqual(const KeyType &key1,
const KeyType &key2) const {
return !KeyCmpLess(key1, key2);
}
/*
* KeyCmpGreater() - Compare a pair of keys for > relation
*
* It flips input for keyCmpLess()
*/
inline bool KeyCmpGreater(const KeyType &key1, const KeyType &key2) const {
return KeyCmpLess(key2, key1);
}
/*
* KeyCmpLessEqual() - Compare a pair of keys for <= relation
*/
inline bool KeyCmpLessEqual(const KeyType &key1, const KeyType &key2) const {
return !KeyCmpGreater(key1, key2);
}
///////////////////////////////////////////////////////////////////
// Value Comparison Member
///////////////////////////////////////////////////////////////////
/*
* ValueCmpEqual() - Compares whether two values are equal
*/
inline bool ValueCmpEqual(const ValueType &v1, const ValueType &v2) {
return value_eq_obj(v1, v2);
}
/*
* class Context - Stores per thread context data that is used during
* tree traversal
*
* NOTE: For each thread there could be only 1 instance of this object
* so we forbid copy construction and assignment and move
*/
class Context {
public:
// We choose to keep the search key as a member rather than pointer
// inside the context object
const KeyType search_key;
// We only need to keep current snapshot and parent snapshot
NodeSnapshot current_snapshot;
NodeSnapshot parent_snapshot;
#ifdef BWTREE_DEBUG
// Counts abort in one traversal
int abort_counter;
// Represents current level we are on the tree
// root is level 0
// On initialization this is set to -1
int current_level;
#endif
// Whether to abort current traversal, and start a new one
// after seeing this flag, all function should return without
// any further action, and let the main driver to perform abort
// and restart
// NOTE: Only the state machine driver could abort
// and other functions just return on seeing this flag
bool abort_flag;
/*
* Constructor - Initialize a context object into initial state
*/
inline Context(const KeyType &p_search_key)
:
#ifdef BWTREE_PELOTON
// Because earlier versions of g++ does not support
// initializer list so must use () form
search_key(p_search_key),
#else
search_key{p_search_key},
#endif
#ifdef BWTREE_DEBUG
abort_counter{0},
current_level{-1},
#endif
abort_flag{false} {
}
/*
* Destructor - Cleanup
*/
~Context() {}
/*
* Copy constructor - deleted
* Assignment operator - deleted
* Move constructor - deleted
* Move assignment - deleted
*/
Context(const Context &p_context) = delete;
Context &operator=(const Context &p_context) = delete;
Context(Context &&p_context) = delete;