-
Notifications
You must be signed in to change notification settings - Fork 67
Expand file tree
/
Copy pathbtree.c
More file actions
4789 lines (4330 loc) · 165 KB
/
Copy pathbtree.c
File metadata and controls
4789 lines (4330 loc) · 165 KB
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 2018-2026 VMware, Inc.
// SPDX-License-Identifier: Apache-2.0
#include "btree_private.h"
#include "data_blob_build.h"
#include "platform_sleep.h"
#include "poison.h"
/*
* *****************************************************************
* Structure of a BTree node: Disk-resident structure:
*
* hdr->next_entry
* |
* 0 v page_size
* -----------------------------------------------------------
* | header | offsets table ---> | empty space | <--- entries|
* -----------------------------------------------------------
*
* header: struct btree_hdr{}
* entry : struct leaf_entry{}
*
* The arrows indicate that the offsets table grows to the left
* and the entries grow to the right.
*
* Entries are not physically sorted in a node. The offsets table
* gives the offset of each entry, in key order.
*
* Offsets are from byte 0 of the node.
*
* New entries are placed in the empty space.
*
* When an entry is replaced with a physically smaller entry, the
* replacement is performed in place. When an entry is replaced with
* a physically larger entry, then the new entry is stored in the
* empty space.
* A node may have free space fragmentation after some entries have
* been replaced. Defragmenting the node rebuilds it with no
* free-space fragmentation.
*
* When a node runs out of free space, we measure its dead space.
* If dead space is:
* - below a threshold, we split the node.
* - above the threshold, then we defragment the node instead of splitting it.
* *****************************************************************
*/
/*
* *****************************************************************
* Locking rules for BTree:
* 1. Locks must be acquired in the following order: read->claim->write
* 2. If a thread holds two locks, it must hold the lock that dominates
* both locks. For instance, if it has locked two children, we must
* lock their parent.
* 3. Threads may traverse from one node to the next without acquiring
* a lock upon the node that dominates them by first releasing the
* held lock and then taking a leap of faith by acquiring the lock
* on the second.
* 4. They may also traverse down the tree to a single leaf using hand
* over hand locking.
* 5. All threads follow the locking patterns in 3 or 4. They only hold
* a single lock at a time.
*
* Exceptions to these rules:
* 1. find_btree_node_and_get_idx_bounds(): To find the end_addr of the
* range iterator, we may acquire read locks along the path to the node
* which holds max_key. However, at the same time we hold a claim on the
* current node. We may not be holding the node that dominates both.
* 2. btree_split_child_leaf(): When splitting a leaf we hold write locks
* on the leaf we're splitting, its parent, and its original next leaf.
* However, this next leaf may have a different parent than the leaf
* we split.
*
* Why are these exceptions okay:
* Because by (5) we know that every other thread is holding only a single
* lock or is either an iterator finding the end_addr or performing a split.
* In either of these exception cases, we always acquire locks in increasing
* leaf order, thus, a thread will never hold a lock while attempting to
* acquire a lock on a previous leaf. As such, we can always safely wait for
* other threads to complete their work.
* *****************************************************************
*/
/* Threshold for splitting instead of defragmenting. */
#define BTREE_SPLIT_THRESHOLD(page_size) ((page_size) / 2)
/*
* After a split, the free space in the left node may be fragmented.
* If there's less than this much contiguous free space, then we also
* defrag the left node.
*/
#define BTREE_DEFRAGMENT_THRESHOLD(page_size) ((page_size) / 4)
/*
* Branches keep track of the number of keys and the total size of
* all keys and messages in their subtrees. But memtables do not
* (because it is difficult to maintain this information during
* insertion). However, the current implementation uses the same
* data structure for both memtables and branches. So memtables
* store BTREE_UNKNOWN_COUNTER for these counters.
*/
#define BTREE_UNKNOWN_COUNTER (0x7fffffffUL)
static const btree_pivot_stats BTREE_PIVOT_STATS_UNKNOWN = {
BTREE_UNKNOWN_COUNTER,
BTREE_UNKNOWN_COUNTER,
BTREE_UNKNOWN_COUNTER};
static const blob_build_config btree_blob_cfg = {
.extent_batch = 0,
.page_batch = 1,
.subpage_batch = 2,
.alignment = 0,
};
static void
btree_blob_ref_init(ondisk_ref *ref,
cache *cc,
const btree_config *cfg,
uint64 root_addr,
page_type type);
static inline uint8
btree_height(const btree_hdr *hdr)
{
return hdr->height;
}
static inline table_entry
btree_get_table_entry(btree_hdr *hdr, int i)
{
debug_assert(i < hdr->num_entries);
return hdr->offsets[i];
}
static inline table_index
btree_num_entries(const btree_hdr *hdr)
{
return hdr->num_entries;
}
static inline void
btree_increment_height(btree_hdr *hdr)
{
hdr->height++;
}
static inline void
btree_reset_node_entries(const btree_config *cfg, btree_hdr *hdr)
{
hdr->num_entries = 0;
hdr->next_entry = btree_page_size(cfg);
}
static inline uint64
index_entry_required_capacity(key pivot)
{
return sizeof(index_entry) + key_length(pivot);
}
static inline uint64
leaf_entry_required_capacity(key tuple_key, const message msg)
{
return sizeof(leaf_entry) + key_length(tuple_key) + message_length(msg);
}
static inline uint64
leaf_entry_key_size(const leaf_entry *entry)
{
return entry->key_length;
}
static inline uint64
leaf_entry_message_size(const leaf_entry *entry)
{
if (!ondisk_tuple_message_is_blob(entry)) {
return entry->message_length;
}
slice sblob = slice_create(entry->message_length,
entry->key_and_message + entry->key_length);
return blob_length(sblob);
}
/*********************************************************
* Code for tracing operations involving a particular key
*********************************************************/
// #define BTREE_KEY_TRACING
#ifdef BTREE_KEY_TRACING
static char trace_key[24] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
void
log_trace_key(key k, char *msg)
{
if (key_lex_cmp(k, key_create(sizeof(trace_key), trace_key)) == 0) {
platform_default_log("BTREE_TRACE_KEY: %s\n", msg);
}
}
/* Output msg if this leaf contains the trace_key */
void
log_trace_leaf(const btree_config *cfg, const btree_hdr *hdr, char *msg)
{
for (int i = 0; i < hdr->num_entries; i++) {
key tuple_key = btree_get_tuple_key(cfg, hdr, i);
log_trace_key(tuple_key, msg);
}
}
#else
# define log_trace_key(key, msg)
# define log_trace_leaf(cfg, hdr, msg)
#endif /* BTREE_KEY_TRACING */
/**************************************
* Basic get/set on index nodes
**************************************/
static inline void
btree_fill_index_entry(const btree_config *cfg,
btree_hdr *hdr,
index_entry *entry,
key new_pivot_key,
uint64 new_addr,
btree_pivot_stats stats)
{
debug_assert((void *)hdr <= (void *)entry);
debug_assert(diff_ptr(hdr, entry)
+ index_entry_required_capacity(new_pivot_key)
<= btree_page_size(cfg));
copy_key_to_ondisk_key(&entry->pivot, new_pivot_key);
entry->pivot_data.child_addr = new_addr;
entry->pivot_data.stats = stats;
}
bool32
btree_set_index_entry(const btree_config *cfg,
btree_hdr *hdr,
table_index k,
key new_pivot_key,
uint64 new_addr,
btree_pivot_stats stats)
{
platform_assert(
k <= hdr->num_entries, "k=%d, num_entries=%d\n", k, hdr->num_entries);
uint64 new_num_entries = k < hdr->num_entries ? hdr->num_entries : k + 1;
if (k < hdr->num_entries) {
index_entry *old_entry = btree_get_index_entry(cfg, hdr, k);
if (hdr->next_entry == diff_ptr(hdr, old_entry)
&& (diff_ptr(hdr, &hdr->offsets[new_num_entries])
+ index_entry_required_capacity(new_pivot_key)
<= hdr->next_entry + sizeof_index_entry(old_entry)))
{
/* special case to avoid creating fragmentation:
* the old entry is the physically first entry in the node
* and the new entry will fit in the space avaiable from the old
* entry plus the free space preceding the old_entry.
* In this case, just reset next_entry so we can insert the new entry.
*/
hdr->next_entry += sizeof_index_entry(old_entry);
} else if (index_entry_required_capacity(new_pivot_key)
<= sizeof_index_entry(old_entry))
{
/* old_entry is not the physically first in the node,
* but new entry will fit inside it.
*/
btree_fill_index_entry(
cfg, hdr, old_entry, new_pivot_key, new_addr, stats);
return TRUE;
}
/* Fall through */
}
if (hdr->next_entry < diff_ptr(hdr, &hdr->offsets[new_num_entries])
+ index_entry_required_capacity(new_pivot_key))
{
return FALSE;
}
index_entry *new_entry = pointer_byte_offset(
hdr, hdr->next_entry - index_entry_required_capacity(new_pivot_key));
btree_fill_index_entry(cfg, hdr, new_entry, new_pivot_key, new_addr, stats);
hdr->offsets[k] = diff_ptr(hdr, new_entry);
hdr->num_entries = new_num_entries;
hdr->next_entry = diff_ptr(hdr, new_entry);
return TRUE;
}
static inline bool32
btree_insert_index_entry(const btree_config *cfg,
btree_hdr *hdr,
uint32 k,
key new_pivot_key,
uint64 new_addr,
btree_pivot_stats stats)
{
bool32 succeeded = btree_set_index_entry(
cfg, hdr, hdr->num_entries, new_pivot_key, new_addr, stats);
if (succeeded) {
node_offset this_entry_offset = hdr->offsets[hdr->num_entries - 1];
memmove(&hdr->offsets[k + 1],
&hdr->offsets[k],
(hdr->num_entries - k - 1) * sizeof(hdr->offsets[0]));
hdr->offsets[k] = this_entry_offset;
}
return succeeded;
}
/**************************************
* Basic get/set on leaf nodes
**************************************/
static inline void
btree_fill_leaf_entry(const btree_config *cfg,
btree_hdr *hdr,
leaf_entry *entry,
key tuple_key,
message msg)
{
debug_assert(
pointer_byte_offset(entry, leaf_entry_required_capacity(tuple_key, msg))
<= pointer_byte_offset(hdr, btree_page_size(cfg)));
copy_tuple_to_ondisk_tuple(entry, tuple_key, msg);
debug_assert(ondisk_tuple_message_class(entry) == message_class(msg),
"entry->type not large enough to hold message_class");
}
static inline bool32
btree_can_set_leaf_entry(const btree_config *cfg,
const btree_hdr *hdr,
table_index k,
key new_key,
message new_message)
{
if (hdr->num_entries < k)
return FALSE;
if (k < hdr->num_entries) {
leaf_entry *old_entry = btree_get_leaf_entry(cfg, hdr, k);
if (leaf_entry_required_capacity(new_key, new_message)
<= sizeof_leaf_entry(old_entry))
{
return TRUE;
}
/* Fall through */
}
uint64 new_num_entries = k < hdr->num_entries ? hdr->num_entries : k + 1;
if (hdr->next_entry
< diff_ptr(hdr, &hdr->offsets[new_num_entries])
+ leaf_entry_required_capacity(new_key, new_message))
{
return FALSE;
}
return TRUE;
}
bool32
btree_set_leaf_entry(const btree_config *cfg,
btree_hdr *hdr,
table_index k,
key new_key,
message new_message)
{
if (k < hdr->num_entries) {
leaf_entry *old_entry = btree_get_leaf_entry(cfg, hdr, k);
if (leaf_entry_required_capacity(new_key, new_message)
<= sizeof_leaf_entry(old_entry))
{
btree_fill_leaf_entry(cfg, hdr, old_entry, new_key, new_message);
return TRUE;
}
/* Fall through */
}
platform_assert(k <= hdr->num_entries);
uint64 new_num_entries = k < hdr->num_entries ? hdr->num_entries : k + 1;
if (hdr->next_entry
< diff_ptr(hdr, &hdr->offsets[new_num_entries])
+ leaf_entry_required_capacity(new_key, new_message))
{
return FALSE;
}
leaf_entry *new_entry = pointer_byte_offset(
hdr,
hdr->next_entry - leaf_entry_required_capacity(new_key, new_message));
platform_assert(
(void *)&hdr->offsets[new_num_entries] <= (void *)new_entry,
"Offset addr 0x%p for index, new_num_entries=%lu is incorrect."
" It should be <= new_entry=0x%p\n",
&hdr->offsets[new_num_entries],
new_num_entries,
new_entry);
btree_fill_leaf_entry(cfg, hdr, new_entry, new_key, new_message);
hdr->offsets[k] = diff_ptr(hdr, new_entry);
hdr->num_entries = new_num_entries;
hdr->next_entry = diff_ptr(hdr, new_entry);
platform_assert(0 < hdr->num_entries);
return TRUE;
}
static bool32
btree_copy_leaf_entry(const btree_config *cfg,
btree_hdr *hdr,
table_index k,
const leaf_entry *entry)
{
key entry_key = ondisk_tuple_key(entry);
message entry_msg = ondisk_tuple_message(
ondisk_tuple_message_is_blob(entry) ? (cache *)1 : NULL, entry);
return btree_set_leaf_entry(cfg, hdr, k, entry_key, entry_msg);
}
static inline bool32
btree_insert_leaf_entry(const btree_config *cfg,
btree_hdr *hdr,
table_index k,
key new_key,
message new_message)
{
debug_assert(k <= hdr->num_entries);
bool32 succeeded =
btree_set_leaf_entry(cfg, hdr, hdr->num_entries, new_key, new_message);
if (succeeded) {
node_offset this_entry_offset = hdr->offsets[hdr->num_entries - 1];
debug_assert(k + 1 <= hdr->num_entries);
memmove(&hdr->offsets[k + 1],
&hdr->offsets[k],
(hdr->num_entries - k - 1) * sizeof(hdr->offsets[0]));
hdr->offsets[k] = this_entry_offset;
}
return succeeded;
}
/*
*-----------------------------------------------------------------------------
* btree_find_pivot --
*
* Returns idx such that
* - -1 <= idx < num_entries
* - forall i | 0 <= i <= idx :: key_i <= key
* - forall i | idx < i < num_entries :: key < key_i
* Also
* - *found == 0 || *found == 1
* - *found == 1 <==> (0 <= idx && key_idx == key)
*-----------------------------------------------------------------------------
*/
/*
* The C code below is a translation of the following verified Dafny
* implementation.
method bsearch(s: seq<int>, k: int) returns (idx: int, f: bool)
requires forall i, j | 0 <= i < j < |s| :: s[i] < s[j]
ensures -1 <= idx < |s|
ensures forall i | 0 <= i <= idx :: s[i] <= k
ensures forall i | idx < i < |s| :: k < s[i]
ensures f <==> (0 <= idx && s[idx] == k)
{
var lo := 0;
var hi := |s|;
f := false;
while lo < hi
invariant 0 <= lo <= hi <= |s|
invariant forall i | 0 <= i < lo :: s[i] <= k
invariant forall i | hi <= i < |s| :: k < s[i]
invariant f <==> (0 < lo && s[lo-1] == k)
{
var mid := (lo + hi) / 2;
if s[mid] <= k {
lo := mid + 1;
f := s[mid] == k;
} else {
hi := mid;
}
}
idx := lo - 1;
}
*/
int64
btree_find_pivot(const btree_config *cfg,
const btree_hdr *hdr,
key target,
bool32 *found)
{
int64 lo = 0, hi = btree_num_entries(hdr);
debug_assert(!key_is_null(target));
*found = FALSE;
while (lo < hi) {
int64 mid = (lo + hi) / 2;
int cmp = btree_key_compare(cfg, target, btree_get_pivot(cfg, hdr, mid));
if (cmp == 0) {
*found = TRUE;
return mid;
} else if (cmp > 0) {
lo = mid + 1;
} else {
hi = mid;
}
}
return lo - 1;
}
/*
*-----------------------------------------------------------------------------
* btree_find_tuple --
*
* Returns idx such that
* - -1 <= idx < num_entries
* - forall i | 0 <= i <= idx :: key_i <= key
* - forall i | idx < i < num_entries :: key < key_i
* Also
* - *found == 0 || *found == 1
* - *found == 1 <==> (0 <= idx && key_idx == key)
*-----------------------------------------------------------------------------
*/
/*
* The C code below is a translation of the same Dafny implementation as above.
*/
static inline int64
btree_find_tuple(const btree_config *cfg,
const btree_hdr *hdr,
key target,
bool32 *found)
{
int64 lo = 0, hi = btree_num_entries(hdr);
*found = FALSE;
while (lo < hi) {
int64 mid = (lo + hi) / 2;
int cmp =
btree_key_compare(cfg, target, btree_get_tuple_key(cfg, hdr, mid));
if (cmp == 0) {
*found = TRUE;
return mid;
} else if (cmp > 0) {
lo = mid + 1;
} else {
hi = mid;
}
}
return lo - 1;
}
/*
*-----------------------------------------------------------------------------
* btree_leaf_incorporate_tuple
*
* Adds the given key and value to node (must be a leaf).
*
* This is broken into several pieces to avoid repeated work during
* exceptional cases.
*
* - create_incorporate_spec() computes everything needed to update
* the leaf, i.e. the index of the key, whether it is replacing an
* existing entry, and the merged message if it is.
*
* - can_perform_incorporate_spec says whether the leaf has enough
* room to actually perform the incorporation.
*
* - perform_incorporate_spec() does what it says.
*
* - incorporate_tuple() is a convenience wrapper.
*-----------------------------------------------------------------------------
*/
static inline int
btree_merge_tuples(const btree_config *cfg,
key tuple_key,
message old_data,
merge_accumulator *new_data)
{
return data_merge_tuples(cfg->data_cfg, tuple_key, old_data, new_data);
}
static message
spec_message(const leaf_incorporate_spec *spec)
{
if (spec->use_new_message) {
return spec->msg.new_message;
} else {
return merge_accumulator_to_message(&spec->msg.modified_message);
}
}
static inline platform_status
btree_record_old_result(const btree_config *cfg,
cache *cc,
uint64 root_addr,
const btree_hdr *hdr,
const leaf_incorporate_spec *spec,
btree_insert_results *results)
{
lookup_result *old_result = results->old_result_buffer;
if (old_result == NULL || spec->old_entry_state != ENTRY_STILL_EXISTS) {
return STATUS_OK;
}
leaf_entry *entry = btree_get_leaf_entry(cfg, hdr, spec->idx);
message old_msg = leaf_entry_message(cc, entry);
ondisk_ref blob_ref = ONDISK_REF_NULL;
if (message_is_blob(old_msg)) {
btree_blob_ref_init(&blob_ref, cc, cfg, root_addr, PAGE_TYPE_MEMTABLE);
}
platform_status rc = lookup_result_update(
old_result, leaf_entry_key(entry), old_msg, &blob_ref);
ondisk_ref_deinit(&blob_ref);
return rc;
}
static inline platform_status
btree_record_insert_msg_blob(btree_insert_results *results,
const leaf_incorporate_spec *spec)
{
if (spec->old_entry_state != ENTRY_DID_NOT_EXIST || spec->use_new_message
|| !merge_accumulator_is_blob(&spec->msg.modified_message))
{
return STATUS_OK;
}
debug_assert(merge_accumulator_is_null(&results->msg_blob));
bool32 success = merge_accumulator_copy_message(
&results->msg_blob,
merge_accumulator_to_message(&spec->msg.modified_message));
return success ? STATUS_OK : STATUS_NO_MEMORY;
}
platform_status
btree_create_leaf_incorporate_spec(const btree_config *cfg,
cache *cc,
mini_allocator *mini,
platform_heap_id heap_id,
btree_hdr *hdr,
key tuple_key,
message msg,
leaf_incorporate_spec *spec)
{
platform_status rc = STATUS_OK;
spec->tuple_key = tuple_key;
bool32 found;
spec->idx = btree_find_tuple(cfg, hdr, tuple_key, &found);
spec->old_entry_state = found ? ENTRY_STILL_EXISTS : ENTRY_DID_NOT_EXIST;
if (!found) {
spec->idx++;
if (message_is_blob(msg)) {
spec->use_new_message = FALSE;
merge_accumulator_init(&spec->msg.modified_message, heap_id);
rc = message_clone(
&btree_blob_cfg, cc, mini, msg, &spec->msg.modified_message);
} else if (MAX_INLINE_MESSAGE_SIZE(btree_page_size(cfg))
< message_length(msg))
{
spec->use_new_message = FALSE;
merge_accumulator_init(&spec->msg.modified_message, heap_id);
rc = message_to_blob(
&btree_blob_cfg, cc, mini, msg, &spec->msg.modified_message);
} else {
spec->use_new_message = TRUE;
spec->msg.new_message = msg;
}
} else {
leaf_entry *entry = btree_get_leaf_entry(cfg, hdr, spec->idx);
message oldmessage = leaf_entry_message(cc, entry);
bool32 success;
spec->use_new_message = FALSE;
success = merge_accumulator_init_from_message(
&spec->msg.modified_message, heap_id, msg);
if (!success) {
return STATUS_NO_MEMORY;
}
if (btree_merge_tuples(
cfg, tuple_key, oldmessage, &spec->msg.modified_message))
{
merge_accumulator_deinit(&spec->msg.modified_message);
return STATUS_NO_MEMORY;
} else if (MAX_INLINE_MESSAGE_SIZE(btree_page_size(cfg))
< merge_accumulator_length(&spec->msg.modified_message))
{
rc = merge_accumulator_convert_to_blob(
&btree_blob_cfg, cc, mini, &spec->msg.modified_message);
}
}
if (!SUCCESS(rc) && !spec->use_new_message) {
merge_accumulator_deinit(&spec->msg.modified_message);
}
return rc;
}
void
destroy_leaf_incorporate_spec(leaf_incorporate_spec *spec)
{
if (!spec->use_new_message) {
merge_accumulator_deinit(&spec->msg.modified_message);
}
}
static inline bool32
btree_can_perform_leaf_incorporate_spec(const btree_config *cfg,
btree_hdr *hdr,
const leaf_incorporate_spec *spec)
{
if (spec->old_entry_state == ENTRY_DID_NOT_EXIST) {
return btree_can_set_leaf_entry(
cfg, hdr, btree_num_entries(hdr), spec->tuple_key, spec_message(spec));
} else if (spec->old_entry_state == ENTRY_STILL_EXISTS) {
return btree_can_set_leaf_entry(
cfg, hdr, spec->idx, spec->tuple_key, spec_message(spec));
} else {
debug_assert(spec->old_entry_state == ENTRY_HAS_BEEN_REMOVED);
return btree_can_set_leaf_entry(
cfg, hdr, btree_num_entries(hdr), spec->tuple_key, spec_message(spec));
}
}
bool32
btree_try_perform_leaf_incorporate_spec(const btree_config *cfg,
btree_hdr *hdr,
const leaf_incorporate_spec *spec,
uint64 *generation)
{
bool32 success;
message msg = spec_message(spec);
switch (spec->old_entry_state) {
case ENTRY_DID_NOT_EXIST:
success =
btree_insert_leaf_entry(cfg, hdr, spec->idx, spec->tuple_key, msg);
break;
case ENTRY_STILL_EXISTS:
{
success =
btree_set_leaf_entry(cfg, hdr, spec->idx, spec->tuple_key, msg);
break;
}
case ENTRY_HAS_BEEN_REMOVED:
{
success =
btree_insert_leaf_entry(cfg, hdr, spec->idx, spec->tuple_key, msg);
break;
}
default:
platform_assert(
FALSE,
"Unknown btree leaf_incorporate_spec->old_entry_state %d",
spec->old_entry_state);
}
if (success) {
*generation = hdr->generation++;
}
return success;
}
/*
*-----------------------------------------------------------------------------
* btree_defragment_leaf --
*
* Defragment a node. If spec != NULL, then we also remove the old
* entry that will be replaced by the insert, if such an old entry exists.
*
* If spec is NULL or if no old entry exists, then we just defrag the node.
*-----------------------------------------------------------------------------
*/
void
btree_defragment_leaf(const btree_config *cfg, // IN
btree_scratch *scratch,
btree_hdr *hdr,
leaf_incorporate_spec *spec) // IN/OUT
{
btree_hdr *scratch_hdr = (btree_hdr *)scratch->defragment_node.scratch_node;
memcpy(scratch_hdr, hdr, btree_page_size(cfg));
btree_reset_node_entries(cfg, hdr);
uint64 dst_idx = 0;
for (int64 i = 0; i < btree_num_entries(scratch_hdr); i++) {
if (spec && spec->old_entry_state == ENTRY_STILL_EXISTS && spec->idx == i)
{
spec->old_entry_state = ENTRY_HAS_BEEN_REMOVED;
} else {
leaf_entry *entry = btree_get_leaf_entry(cfg, scratch_hdr, i);
debug_only bool32 success =
btree_copy_leaf_entry(cfg, hdr, dst_idx++, entry);
debug_assert(success);
}
}
}
static inline void
btree_truncate_leaf(const btree_config *cfg, // IN
btree_hdr *hdr, // IN
uint64 target_entries) // IN
{
uint64 new_next_entry = btree_page_size(cfg);
for (uint64 i = 0; i < target_entries; i++) {
if (hdr->offsets[i] < new_next_entry)
new_next_entry = hdr->offsets[i];
}
hdr->num_entries = target_entries;
hdr->next_entry = new_next_entry;
}
/*
*-----------------------------------------------------------------------------
* btree_split_leaf --
*
* Splits the node at left_addr into a new node at right_addr.
*
* Assumes write lock on both nodes.
*-----------------------------------------------------------------------------
*/
static leaf_splitting_plan initial_plan = {0, FALSE};
static bool32
most_of_entry_is_on_left_side(uint64 total_bytes,
uint64 left_bytes,
uint64 entry_size)
{
return left_bytes + sizeof(table_entry) + entry_size
< (total_bytes + sizeof(table_entry) + entry_size) / 2;
}
/*
* ----------------------------------------------------------------------------
* Figure out how many entries we can put on the left side.
* Basically, we split the node as evenly as possible by bytes.
* The old node had total_bytes of entries (and table entries).
* The new nodes will have as close as possible to total_bytes / 2 bytes.
* We iterate over each entry and, if most of its bytes fall on
* left side of total_bytes / 2, then we can put it on the left side.
*
* Note that the loop is split into two (see build_leaf_splitting_plan)
* so we can handle the entry for the key being inserted specially.
* Specifically, if the key being inserted replaces an existing key,
* then we need to skip over the entry for the existing key.
* ----------------------------------------------------------------------------
*/
static uint64
plan_move_more_entries_to_left(const btree_config *cfg,
const btree_hdr *hdr,
uint64 max_entries,
uint64 total_bytes,
uint64 left_bytes,
leaf_splitting_plan *plan) // IN/OUT
{
leaf_entry *entry;
while (plan->split_idx < max_entries
&& (entry = btree_get_leaf_entry(cfg, hdr, plan->split_idx))
&& most_of_entry_is_on_left_side(
total_bytes, left_bytes, sizeof_leaf_entry(entry)))
{
left_bytes += sizeof(table_entry) + sizeof_leaf_entry(entry);
plan->split_idx++;
}
return left_bytes;
}
/*
* ----------------------------------------------------------------------------
* Choose a splitting point so that we are guaranteed to be able to
* insert the given key-message pair into the correct node after the
* split. Assumes all leaf entries are at most half the total free
* space in an empty leaf.
* ----------------------------------------------------------------------------
*/
leaf_splitting_plan
btree_build_leaf_splitting_plan(const btree_config *cfg, // IN
const btree_hdr *hdr,
const leaf_incorporate_spec *spec) // IN
{
/* Split the content by bytes -- roughly half the bytes go to the
* right node. So count the bytes, including the new entry to be
* inserted.
*/
uint64 num_entries = btree_num_entries(hdr);
uint64 entry_size =
leaf_entry_required_capacity(spec->tuple_key, spec_message(spec));
uint64 total_bytes = entry_size;
for (uint64 i = 0; i < num_entries; i++) {
if (i != spec->idx || spec->old_entry_state != ENTRY_STILL_EXISTS) {
leaf_entry *entry = btree_get_leaf_entry(cfg, hdr, i);
total_bytes += sizeof_leaf_entry(entry);
}
}
uint64 new_num_entries = num_entries;
new_num_entries += spec->old_entry_state == ENTRY_STILL_EXISTS ? 0 : 1;
total_bytes += new_num_entries * sizeof(table_entry);
/* Now figure out the number of entries to move, and figure out how
* much free space will be created in the left_hdr by the split.
*/
uint64 left_bytes = 0;
leaf_splitting_plan plan = initial_plan;
/* Figure out how many of the items to the left of spec.idx can be
* put into the left node.
*/
left_bytes = plan_move_more_entries_to_left(
cfg, hdr, spec->idx, total_bytes, left_bytes, &plan);
/* Figure out whether our new entry can go into the left node. If it
* can't, then no subsequent entries can, either, so we're done.
*/
if (plan.split_idx == spec->idx
&& most_of_entry_is_on_left_side(total_bytes, left_bytes, entry_size))
{
left_bytes += sizeof(table_entry) + entry_size;
plan.insertion_goes_left = TRUE;
} else {
return plan;
}
if (spec->old_entry_state == ENTRY_STILL_EXISTS) {
/* If our new entry is replacing an existing entry, then skip
* that entry in our planning.
*/
plan.split_idx++;
}
/* Figure out how many more entries after spec.idx can go into the
* left node.
*/
plan_move_more_entries_to_left(
cfg, hdr, num_entries, total_bytes, left_bytes, &plan);
return plan;
}
static inline key
btree_splitting_pivot(const btree_config *cfg, // IN
const btree_hdr *hdr,
const leaf_incorporate_spec *spec,
leaf_splitting_plan plan)
{
if (plan.split_idx == spec->idx
&& spec->old_entry_state != ENTRY_STILL_EXISTS
&& !plan.insertion_goes_left)
{
return spec->tuple_key;
} else {
return btree_get_tuple_key(cfg, hdr, plan.split_idx);
}
}
static inline void
btree_split_leaf_build_right_node(const btree_config *cfg, // IN
const btree_hdr *left_hdr, // IN
uint64 left_addr, // IN
leaf_incorporate_spec *spec, // IN
leaf_splitting_plan plan, // IN
btree_hdr *right_hdr,
uint64 *generation) // IN/OUT
{
/* Build the right node. */
memmove(right_hdr, left_hdr, sizeof(*right_hdr));
right_hdr->generation++;
right_hdr->prev_addr = left_addr;
btree_reset_node_entries(cfg, right_hdr);
uint64 num_left_entries = btree_num_entries(left_hdr);
uint64 dst_idx = 0;
for (uint64 i = plan.split_idx; i < num_left_entries; i++) {
if (spec->old_entry_state == ENTRY_STILL_EXISTS && i == spec->idx) {
spec->old_entry_state = ENTRY_HAS_BEEN_REMOVED;
} else {
leaf_entry *entry = btree_get_leaf_entry(cfg, left_hdr, i);
btree_copy_leaf_entry(cfg, right_hdr, dst_idx, entry);
dst_idx++;
}
}
if (!plan.insertion_goes_left) {
spec->idx -= plan.split_idx;
bool32 incorporated = btree_try_perform_leaf_incorporate_spec(
cfg, right_hdr, spec, generation);
platform_assert(incorporated);
}
}