-
Notifications
You must be signed in to change notification settings - Fork 3.3k
Expand file tree
/
Copy patherl_db_catree.c
More file actions
2557 lines (2332 loc) · 81.4 KB
/
Copy patherl_db_catree.c
File metadata and controls
2557 lines (2332 loc) · 81.4 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
/*
* %CopyrightBegin%
*
* SPDX-License-Identifier: Apache-2.0
*
* Copyright Kjell Winblad 1998-2025. All Rights Reserved.
* Copyright Ericsson AB 1998-2025. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* %CopyrightEnd%
*/
/*
* Description: Implementation of ETS ordered_set table type with
* fine-grained synchronization.
*
* Author: Kjell Winblad
*
* This implementation is based on the contention adapting search tree
* (CA tree). The CA tree is a concurrent data structure that
* dynamically adapts its synchronization granularity based on how
* much contention is detected in locks. The following publication
* contains a detailed description of CA trees:
*
* A Contention Adapting Approach to Concurrent Ordered Sets
* Journal of Parallel and Distributed Computing, 2018
* Kjell Winblad and Konstantinos Sagonas
* https://doi.org/10.1016/j.jpdc.2017.11.007
*
* The following publication may also be interesting as it discusses
* how the CA tree can be used as an ETS ordered_set table type
* backend:
*
* More Scalable Ordered Set for ETS Using Adaptation
* In Thirteenth ACM SIGPLAN workshop on Erlang (2014)
* Kjell Winblad and Konstantinos Sagonas
* https://doi.org/10.1145/2633448.2633455
*
* This implementation of the ordered_set ETS table type is only
* activated when the options {write_concurrency, true}, public and
* ordered_set are passed to the ets:new/2 function. This
* implementation is expected to scale better than the default
* implementation located in "erl_db_tree.c".
*
* The default implementation has a static stack optimization (see
* get_static_stack in erl_db_tree.c). This implementation does not
* have such an optimization as it induces bad scalability when
* concurrent read operations are frequent (they all try to get hold
* of the same stack). The default implementation may thus perform
* better compared to this implementation in scenarios where the
* static stack optimization is useful. One such scenario is when only
* one process is accessing the table and this process is traversing
* the table with a sequence of next/2 calls.
*/
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
#include "sys.h"
#include "erl_vm.h"
#include "global.h"
#include "erl_process.h"
#include "error.h"
#define ERTS_WANT_DB_INTERNAL__
#include "erl_db.h"
#include "bif.h"
#include "big.h"
#include "erl_binary.h"
#include "erl_db_catree.h"
#include "erl_db_tree.h"
#include "erl_db_tree_util.h"
#include "erl_global_literals.h"
#ifdef DEBUG
# define IF_DEBUG(X) X
#else
# define IF_DEBUG(X)
#endif
/*
** Forward declarations
*/
static SWord do_delete_base_node_cont(DbTableCATree *tb,
DbTableCATreeNode *base_node,
SWord num_left);
/* Method interface functions */
static int db_first_catree(Process *p, DbTable *tbl,
Eterm *ret);
static int db_first_lookup_catree(Process *p, DbTable *tbl,
Eterm *ret);
static int db_next_catree(Process *p, DbTable *tbl,
Eterm key, Eterm *ret);
static int db_next_lookup_catree(Process *p, DbTable *tbl,
Eterm key, Eterm *ret);
static int db_last_catree(Process *p, DbTable *tbl,
Eterm *ret);
static int db_last_lookup_catree(Process *p, DbTable *tbl,
Eterm *ret);
static int db_prev_catree(Process *p, DbTable *tbl,
Eterm key,
Eterm *ret);
static int db_prev_lookup_catree(Process *p, DbTable *tbl,
Eterm key,
Eterm *ret);
static int db_put_catree(DbTable *tbl, Eterm obj, bool key_clash_fail,
SWord *consumed_reds_p);
static int db_get_catree(Process *p, DbTable *tbl,
Eterm key, Eterm *ret);
static int db_member_catree(DbTable *tbl, Eterm key, Eterm *ret);
static int db_get_element_catree(Process *p, DbTable *tbl,
Eterm key,int ndex,
Eterm *ret);
static int db_erase_catree(DbTable *tbl, Eterm key, Eterm *ret);
static int db_erase_object_catree(DbTable *tbl, Eterm object,Eterm *ret);
static int db_slot_catree(Process *p, DbTable *tbl,
Eterm slot_term, Eterm *ret);
static int db_select_catree(Process *p, DbTable *tbl, Eterm tid,
Eterm pattern, int reversed, Eterm *ret,
enum DbIterSafety);
static int db_select_count_catree(Process *p, DbTable *tbl, Eterm tid,
Eterm pattern, Eterm *ret, enum DbIterSafety);
static int db_select_chunk_catree(Process *p, DbTable *tbl, Eterm tid,
Eterm pattern, Sint chunk_size,
int reversed, Eterm *ret, enum DbIterSafety);
static int db_select_continue_catree(Process *p, DbTable *tbl,
Eterm continuation, Eterm *ret,
enum DbIterSafety*);
static int db_select_count_continue_catree(Process *p, DbTable *tbl,
Eterm continuation, Eterm *ret,
enum DbIterSafety*);
static int db_select_delete_catree(Process *p, DbTable *tbl, Eterm tid,
Eterm pattern, Eterm *ret,
enum DbIterSafety);
static int db_select_delete_continue_catree(Process *p, DbTable *tbl,
Eterm continuation, Eterm *ret,
enum DbIterSafety*);
static int db_select_replace_catree(Process *p, DbTable *tbl, Eterm tid,
Eterm pattern, Eterm *ret,
enum DbIterSafety);
static int db_select_replace_continue_catree(Process *p, DbTable *tbl,
Eterm continuation, Eterm *ret,
enum DbIterSafety*);
static int db_take_catree(Process *, DbTable *, Eterm, Eterm *);
static void db_print_catree(fmtfn_t to, void *to_arg,
bool show, DbTable *tbl);
static int db_free_table_catree(DbTable *tbl);
static SWord db_free_table_continue_catree(DbTable *tbl, SWord);
static void db_foreach_offheap_catree(DbTable *,
void (*)(ErlOffHeap *, void *),
void *);
static SWord db_delete_all_objects_catree(Process* p,
DbTable* tbl,
SWord reds,
Eterm* nitems_holder_wb);
static Eterm db_delete_all_objects_get_nitems_from_holder_catree(Process* p,
Eterm nitems_holder);
static bool
db_lookup_dbterm_catree(Process *, DbTable *, Eterm key, Eterm obj,
DbUpdateHandle*);
static void db_finalize_dbterm_catree(int cret, DbUpdateHandle *);
static int db_get_binary_info_catree(Process*, DbTable*, Eterm key, Eterm *ret);
static int db_put_dbterm_catree(DbTable* tbl,
void* obj,
bool key_clash_fail,
SWord *consumed_reds_p);
static void split_catree(DbTableCATree *tb,
DbTableCATreeNode* ERTS_RESTRICT base,
DbTableCATreeNode* ERTS_RESTRICT parent);
static void join_catree(DbTableCATree *tb,
DbTableCATreeNode *thiz,
DbTableCATreeNode *parent);
static ERTS_INLINE
int try_wlock_base_node(DbTableCATreeBaseNode *base_node);
static ERTS_INLINE
void wunlock_base_node(DbTableCATreeNode *base_node);
static ERTS_INLINE
void wlock_base_node_no_stats(DbTableCATreeNode *base_node);
static ERTS_INLINE
void wunlock_adapt_base_node(DbTableCATree* tb,
DbTableCATreeNode* node,
DbTableCATreeNode* parent,
int current_level);
/*
** External interface
*/
DbTableMethod db_catree =
{
db_create_catree,
db_first_catree,
db_next_catree,
db_last_catree,
db_prev_catree,
db_put_catree,
db_get_catree,
db_get_element_catree,
db_member_catree,
db_erase_catree,
db_erase_object_catree,
db_slot_catree,
db_select_chunk_catree,
db_select_catree,
db_select_delete_catree,
db_select_continue_catree,
db_select_delete_continue_catree,
db_select_count_catree,
db_select_count_continue_catree,
db_select_replace_catree,
db_select_replace_continue_catree,
db_take_catree,
db_delete_all_objects_catree,
db_delete_all_objects_get_nitems_from_holder_catree,
db_free_table_catree,
db_free_table_continue_catree,
db_print_catree,
db_foreach_offheap_catree,
db_lookup_dbterm_catree,
db_finalize_dbterm_catree,
db_eterm_to_dbterm_tree_common,
db_dbterm_list_append_tree_common,
db_dbterm_list_remove_first_tree_common,
db_put_dbterm_catree,
db_free_dbterm_tree_common,
db_get_dbterm_key_tree_common,
db_get_binary_info_catree,
db_first_catree, /* raw_first same as first */
db_next_catree, /* raw_next same as next */
db_first_lookup_catree,
db_next_lookup_catree,
db_last_lookup_catree,
db_prev_lookup_catree
};
/*
* Constants
*/
#define ERL_DB_CATREE_LOCK_FAILURE_CONTRIBUTION 250
#define ERL_DB_CATREE_LOCK_SUCCESS_CONTRIBUTION (-1)
#define ERL_DB_CATREE_LOCK_GRAVITY_CONTRIBUTION (-500)
#define ERL_DB_CATREE_LOCK_GRAVITY_PATTERN (0xFF800000)
#define ERL_DB_CATREE_LOCK_MORE_THAN_ONE_CONTRIBUTION (-10)
#define ERL_DB_CATREE_HIGH_CONTENTION_LIMIT 1000
#define ERL_DB_CATREE_LOW_CONTENTION_LIMIT (-1000)
#define ERL_DB_CATREE_MAX_ROUTE_NODE_LAYER_HEIGHT 16
#define ERL_DB_CATREE_LOCK_LOW_NO_CONTRIBUTION_LIMIT (-20000)
#define ERL_DB_CATREE_LOCK_HIGH_NO_CONTRIBUTION_LIMIT (20000)
/*
* Internal CA tree related helper functions and macros
*/
#define GET_ROUTE_NODE_KEY(node) (node->u.route.key.term)
#define GET_BASE_NODE_LOCK(node) (&(node->u.base.lock))
#define GET_ROUTE_NODE_LOCK(node) (&(node->u.route.lock))
/* Helpers for reading and writing shared atomic variables */
/* No memory barrier */
#define GET_ROOT(tb) ((DbTableCATreeNode*)erts_atomic_read_nob(&((tb)->root)))
#define GET_LEFT(ca_tree_route_node) ((DbTableCATreeNode*)erts_atomic_read_nob(&(ca_tree_route_node->u.route.left)))
#define GET_RIGHT(ca_tree_route_node) ((DbTableCATreeNode*)erts_atomic_read_nob(&(ca_tree_route_node->u.route.right)))
#define SET_ROOT(tb, v) erts_atomic_set_nob(&((tb)->root), (erts_aint_t)(v))
#define SET_LEFT(ca_tree_route_node, v) erts_atomic_set_nob(&(ca_tree_route_node->u.route.left), (erts_aint_t)(v));
#define SET_RIGHT(ca_tree_route_node, v) erts_atomic_set_nob(&(ca_tree_route_node->u.route.right), (erts_aint_t)(v));
/* Release or acquire barriers */
#define GET_ROOT_ACQB(tb) ((DbTableCATreeNode*)erts_atomic_read_acqb(&((tb)->root)))
#define GET_LEFT_ACQB(ca_tree_route_node) ((DbTableCATreeNode*)erts_atomic_read_acqb(&(ca_tree_route_node->u.route.left)))
#define GET_RIGHT_ACQB(ca_tree_route_node) ((DbTableCATreeNode*)erts_atomic_read_acqb(&(ca_tree_route_node->u.route.right)))
#define SET_ROOT_RELB(tb, v) erts_atomic_set_relb(&((tb)->root), (erts_aint_t)(v))
#define SET_LEFT_RELB(ca_tree_route_node, v) erts_atomic_set_relb(&(ca_tree_route_node->u.route.left), (erts_aint_t)(v));
#define SET_RIGHT_RELB(ca_tree_route_node, v) erts_atomic_set_relb(&(ca_tree_route_node->u.route.right), (erts_aint_t)(v));
/* Change base node lock statistics */
#define BASE_NODE_STAT_SET(NODE, VALUE) erts_atomic_set_nob(&(NODE)->u.base.lock_statistics, VALUE)
#define BASE_NODE_STAT_READ(NODE) erts_atomic_read_nob(&(NODE)->u.base.lock_statistics)
#define BASE_NODE_STAT_ADD(NODE, VALUE) \
do { \
Sint v = erts_atomic_read_nob(&((NODE)->u.base.lock_statistics)); \
ASSERT(VALUE > 0); \
if(v < ERL_DB_CATREE_LOCK_HIGH_NO_CONTRIBUTION_LIMIT) { \
erts_atomic_set_nob(&(NODE->u.base.lock_statistics), v + VALUE); \
} \
}while(0);
#define BASE_NODE_STAT_SUB(NODE, VALUE) \
do { \
Sint v = erts_atomic_read_nob(&((NODE)->u.base.lock_statistics)); \
ASSERT(VALUE < 0); \
if(v > ERL_DB_CATREE_LOCK_LOW_NO_CONTRIBUTION_LIMIT) { \
erts_atomic_set_nob(&(NODE->u.base.lock_statistics), v + VALUE); \
} \
}while(0);
/* Compares a key to the key in a route node */
static ERTS_INLINE Sint cmp_key_route(Eterm key,
DbTableCATreeNode *obj)
{
return CMP(key, GET_ROUTE_NODE_KEY(obj));
}
/*
* Used by the split_tree function
*/
static ERTS_INLINE
int less_than_two_elements(TreeDbTerm *root)
{
return root == NULL || (root->left == NULL && root->right == NULL);
}
/*
* Inserts a TreeDbTerm into a tree. Returns the new root.
*/
static ERTS_INLINE
TreeDbTerm* insert_TreeDbTerm(DbTableCATree *tb,
TreeDbTerm *insert_to_root,
TreeDbTerm *value_to_insert) {
/* Non recursive insertion in AVL tree, building our own stack */
TreeDbTerm **tstack[STACK_NEED];
int tpos = 0;
int dstack[STACK_NEED+1];
int dpos = 0;
int state = 0;
TreeDbTerm * base = insert_to_root;
TreeDbTerm **this = &base;
Sint c;
Eterm key;
int dir;
TreeDbTerm *p1, *p2, *p;
key = GETKEY(tb, value_to_insert->dbterm.tpl);
dstack[dpos++] = DIR_END;
for (;;)
if (!*this) { /* Found our place */
state = 1;
*this = value_to_insert;
(*this)->balance = 0;
(*this)->left = (*this)->right = NULL;
break;
} else if ((c = cmp_key(&tb->common, key, *this)) < 0) {
/* go lefts */
dstack[dpos++] = DIR_LEFT;
tstack[tpos++] = this;
this = &((*this)->left);
} else { /* go right */
dstack[dpos++] = DIR_RIGHT;
tstack[tpos++] = this;
this = &((*this)->right);
}
while (state && ( dir = dstack[--dpos] ) != DIR_END) {
this = tstack[--tpos];
p = *this;
if (dir == DIR_LEFT) {
switch (p->balance) {
case 1:
p->balance = 0;
state = 0;
break;
case 0:
p->balance = -1;
break;
case -1: /* The icky case */
p1 = p->left;
if (p1->balance == -1) { /* Single LL rotation */
p->left = p1->right;
p1->right = p;
p->balance = 0;
(*this) = p1;
} else { /* Double RR rotation */
ASSERT(p1->right);
p2 = p1->right;
p1->right = p2->left;
p2->left = p1;
p->left = p2->right;
p2->right = p;
p->balance = (p2->balance == -1) ? +1 : 0;
p1->balance = (p2->balance == 1) ? -1 : 0;
(*this) = p2;
}
(*this)->balance = 0;
state = 0;
break;
}
} else { /* dir == DIR_RIGHT */
switch (p->balance) {
case -1:
p->balance = 0;
state = 0;
break;
case 0:
p->balance = 1;
break;
case 1:
p1 = p->right;
if (p1->balance == 1) { /* Single RR rotation */
p->right = p1->left;
p1->left = p;
p->balance = 0;
(*this) = p1;
} else { /* Double RL rotation */
ASSERT(p1->left);
p2 = p1->left;
p1->left = p2->right;
p2->right = p1;
p->right = p2->left;
p2->left = p;
p->balance = (p2->balance == 1) ? -1 : 0;
p1->balance = (p2->balance == -1) ? 1 : 0;
(*this) = p2;
}
(*this)->balance = 0;
state = 0;
break;
}
}
}
return base;
}
/*
* Split an AVL tree into two trees. The function stores the node
* containing the "split key" in the write back parameter
* split_key_wb. The function stores the left tree containing the keys
* that are smaller than the "split key" in the write back parameter
* left_wb and the tree containing the rest of the keys in the write
* back parameter right_wb.
*/
static void split_tree(DbTableCATree *tb,
TreeDbTerm *root,
TreeDbTerm **split_key_node_wb,
TreeDbTerm **left_wb,
TreeDbTerm **right_wb) {
TreeDbTerm * split_node = NULL;
TreeDbTerm * left_root;
TreeDbTerm * right_root;
if (root->left == NULL) { /* To get non empty split */
*right_wb = root->right;
*split_key_node_wb = root->right;
root->right = NULL;
root->balance = 0;
*left_wb = root;
return;
}
split_node = root;
left_root = split_node->left;
split_node->left = NULL;
right_root = split_node->right;
split_node->right = NULL;
right_root = insert_TreeDbTerm(tb, right_root, split_node);
*split_key_node_wb = split_node;
*left_wb = left_root;
*right_wb = right_root;
}
/*
* Used by the join_trees function
*/
static ERTS_INLINE int compute_tree_hight(TreeDbTerm * root)
{
if(root == NULL) {
return 0;
} else {
TreeDbTerm * current_node = root;
int hight_so_far = 1;
while (current_node->left != NULL || current_node->right != NULL) {
if (current_node->balance == -1) {
ASSERT(current_node->left != NULL);
current_node = current_node->left;
} else {
ASSERT(current_node->right != NULL);
current_node = current_node->right;
}
hight_so_far = hight_so_far + 1;
}
return hight_so_far;
}
}
/*
* Used by the join_trees function
*/
static ERTS_INLINE
TreeDbTerm* linkout_min_or_max_tree_node(TreeDbTerm **root, bool is_min)
{
TreeDbTerm **tstack[STACK_NEED];
int tpos = 0;
int dstack[STACK_NEED+1];
int dpos = 0;
int state = 0;
TreeDbTerm **this = root;
int dir;
TreeDbTerm *q = NULL;
dstack[dpos++] = DIR_END;
for (;;) {
if (!*this) { /* Failure */
return NULL;
} else if (is_min && (*this)->left != NULL) {
dstack[dpos++] = DIR_LEFT;
tstack[tpos++] = this;
this = &((*this)->left);
} else if (!is_min && (*this)->right != NULL) {
dstack[dpos++] = DIR_RIGHT;
tstack[tpos++] = this;
this = &((*this)->right);
} else { /* Min value, found the one to splice out */
q = (*this);
if (q->right == NULL) {
(*this) = q->left;
state = 1;
} else if (q->left == NULL) {
(*this) = q->right;
state = 1;
}
break;
}
}
while (state && ( dir = dstack[--dpos] ) != DIR_END) {
this = tstack[--tpos];
if (dir == DIR_LEFT) {
state = tree_balance_left(this);
} else {
state = tree_balance_right(this);
}
}
return q;
}
#define LINKOUT_MIN_TREE_NODE(root) linkout_min_or_max_tree_node(root, true)
#define LINKOUT_MAX_TREE_NODE(root) linkout_min_or_max_tree_node(root, false)
/*
* Joins two AVL trees where all the keys in the left one are smaller
* then the keys in the right one and returns the resulting tree.
*
* The algorithm is described on page 474 in D. E. Knuth. The Art of
* Computer Programming: Sorting and Searching,
* vol. 3. Addison-Wesley, 2nd edition, 1998.
*/
static TreeDbTerm* join_trees(TreeDbTerm *left_root_param,
TreeDbTerm *right_root_param)
{
TreeDbTerm **tstack[STACK_NEED];
int tpos = 0;
int dstack[STACK_NEED+1];
int dpos = 0;
int state = 1;
TreeDbTerm **this;
int dir;
TreeDbTerm *p1, *p2, *p;
TreeDbTerm *left_root = left_root_param;
TreeDbTerm *right_root = right_root_param;
int left_height;
int right_height;
int current_height;
dstack[dpos++] = DIR_END;
if (left_root == NULL) {
return right_root;
} else if (right_root == NULL) {
return left_root;
}
left_height = compute_tree_hight(left_root);
right_height = compute_tree_hight(right_root);
if (left_height >= right_height) {
TreeDbTerm * new_root =
LINKOUT_MIN_TREE_NODE(&right_root);
int new_right_height = compute_tree_hight(right_root);
TreeDbTerm * current_node = left_root;
this = &left_root;
current_height = left_height;
while(current_height > new_right_height + 1) {
if (current_node->balance == -1) {
current_height = current_height - 2;
} else {
current_height = current_height - 1;
}
dstack[dpos++] = DIR_RIGHT;
tstack[tpos++] = this;
this = &((*this)->right);
current_node = current_node->right;
}
new_root->left = current_node;
new_root->right = right_root;
new_root->balance = new_right_height - current_height;
*this = new_root;
} else {
/* This case is symmetric to the previous case */
TreeDbTerm * new_root =
LINKOUT_MAX_TREE_NODE(&left_root);
int new_left_height = compute_tree_hight(left_root);
TreeDbTerm * current_node = right_root;
this = &right_root;
current_height = right_height;
while (current_height > new_left_height + 1) {
if (current_node->balance == 1) {
current_height = current_height - 2;
} else {
current_height = current_height - 1;
}
dstack[dpos++] = DIR_LEFT;
tstack[tpos++] = this;
this = &((*this)->left);
current_node = current_node->left;
}
new_root->right = current_node;
new_root->left = left_root;
new_root->balance = current_height - new_left_height;
*this = new_root;
}
/* Now we need to continue as if this was during the insert */
while (state && ( dir = dstack[--dpos] ) != DIR_END) {
this = tstack[--tpos];
p = *this;
if (dir == DIR_LEFT) {
switch (p->balance) {
case 1:
p->balance = 0;
state = 0;
break;
case 0:
p->balance = -1;
break;
case -1: /* The icky case */
p1 = p->left;
if (p1->balance == -1) { /* Single LL rotation */
p->left = p1->right;
p1->right = p;
p->balance = 0;
(*this) = p1;
} else { /* Double RR rotation */
ASSERT(p1->right);
p2 = p1->right;
p1->right = p2->left;
p2->left = p1;
p->left = p2->right;
p2->right = p;
p->balance = (p2->balance == -1) ? +1 : 0;
p1->balance = (p2->balance == 1) ? -1 : 0;
(*this) = p2;
}
(*this)->balance = 0;
state = 0;
break;
}
} else { /* dir == DIR_RIGHT */
switch (p->balance) {
case -1:
p->balance = 0;
state = 0;
break;
case 0:
p->balance = 1;
break;
case 1:
p1 = p->right;
if (p1->balance == 1) { /* Single RR rotation */
p->right = p1->left;
p1->left = p;
p->balance = 0;
(*this) = p1;
} else { /* Double RL rotation */
ASSERT(p1->left);
p2 = p1->left;
p1->left = p2->right;
p2->right = p1;
p->right = p2->left;
p2->left = p;
p->balance = (p2->balance == 1) ? -1 : 0;
p1->balance = (p2->balance == -1) ? 1 : 0;
(*this) = p2;
}
(*this)->balance = 0;
state = 0;
break;
}
}
}
/* Return the joined tree */
if (left_height >= right_height) {
return left_root;
} else {
return right_root;
}
}
#ifdef DEBUG
# define PROVOKE_RANDOM_SPLIT_JOIN
#endif
#ifdef PROVOKE_RANDOM_SPLIT_JOIN
static int dbg_fastrand(void)
{
static int g_seed = 648835;
g_seed = (214013*g_seed+2531011);
return (g_seed>>16)&0x7FFF;
}
static void dbg_provoke_random_splitjoin(DbTableCATree* tb,
DbTableCATreeNode* base_node)
{
if (tb->common.status & DB_CATREE_FORCE_SPLIT ||
!(tb->common.status & DB_CATREE_DEBUG_RANDOM_SPLIT_JOIN))
return;
switch (dbg_fastrand() % 8) {
case 1:
BASE_NODE_STAT_ADD(base_node, 1+ERL_DB_CATREE_HIGH_CONTENTION_LIMIT);
break;
case 2:
BASE_NODE_STAT_SUB(base_node, -1+ERL_DB_CATREE_LOW_CONTENTION_LIMIT);
break;
}
}
#else
# define dbg_provoke_random_splitjoin(T,N)
#endif /* PROVOKE_RANDOM_SPLIT_JOIN */
static ERTS_NOINLINE
void do_random_join(DbTableCATree* tb, Uint rand)
{
DbTableCATreeNode* node = GET_ROOT_ACQB(tb);
DbTableCATreeNode* parent = NULL;
int level = 0;
Sint stat;
while (!node->is_base_node) {
parent = node;
if ((rand & (1 << level)) == 0) {
node = GET_LEFT_ACQB(node);
} else {
node = GET_RIGHT_ACQB(node);
}
level++;
}
BASE_NODE_STAT_SUB(node, ERL_DB_CATREE_LOCK_GRAVITY_CONTRIBUTION);
stat = BASE_NODE_STAT_READ(node);
if (stat >= ERL_DB_CATREE_LOW_CONTENTION_LIMIT &&
stat <= ERL_DB_CATREE_HIGH_CONTENTION_LIMIT) {
return; /* No adaptation */
}
if (parent != NULL && !try_wlock_base_node(&node->u.base)) {
if (!node->is_valid) {
wunlock_base_node(node);
return;
}
wunlock_adapt_base_node(tb, node, parent, level);
}
}
static ERTS_INLINE
void do_random_join_with_low_probability(DbTableCATree* tb, Uint seed)
{
#ifndef ERTS_DB_CA_TREE_NO_RANDOM_JOIN_WITH_LOW_PROBABILITY
Uint32 rand = erts_sched_local_random(seed);
if (((rand & ERL_DB_CATREE_LOCK_GRAVITY_PATTERN)) == 0) {
do_random_join(tb, rand);
}
#endif
}
static ERTS_INLINE
int try_wlock_base_node(DbTableCATreeBaseNode *base_node)
{
return EBUSY == erts_rwmtx_tryrwlock(&base_node->lock);
}
/*
* Locks a base node without adjusting the lock statistics
*/
static ERTS_INLINE
void wlock_base_node_no_stats(DbTableCATreeNode *base_node)
{
ASSERT(base_node->is_base_node);
erts_rwmtx_rwlock(&base_node->u.base.lock);
}
/*
* Locks a base node and adjusts the lock statistics according to if
* the lock was contended or not
*/
static ERTS_INLINE
void wlock_base_node(DbTableCATreeNode *base_node)
{
ASSERT(base_node->is_base_node);
if (try_wlock_base_node(&base_node->u.base)) {
/* The lock is contended */
wlock_base_node_no_stats(base_node);
BASE_NODE_STAT_ADD(base_node, ERL_DB_CATREE_LOCK_FAILURE_CONTRIBUTION);
} else {
BASE_NODE_STAT_SUB(base_node, ERL_DB_CATREE_LOCK_SUCCESS_CONTRIBUTION);
}
}
static ERTS_INLINE
void wunlock_base_node(DbTableCATreeNode *base_node)
{
erts_rwmtx_rwunlock(&base_node->u.base.lock);
}
static ERTS_INLINE
void wunlock_adapt_base_node(DbTableCATree* tb,
DbTableCATreeNode* node,
DbTableCATreeNode* parent,
int current_level)
{
Sint base_node_lock_stat = BASE_NODE_STAT_READ(node);
dbg_provoke_random_splitjoin(tb,node);
if ((!node->u.base.root && parent && !(tb->common.status
& DB_CATREE_FORCE_SPLIT))
|| base_node_lock_stat < ERL_DB_CATREE_LOW_CONTENTION_LIMIT) {
join_catree(tb, node, parent);
}
else if (base_node_lock_stat > ERL_DB_CATREE_HIGH_CONTENTION_LIMIT
&& current_level < ERL_DB_CATREE_MAX_ROUTE_NODE_LAYER_HEIGHT) {
split_catree(tb, node, parent);
}
else {
wunlock_base_node(node);
}
}
static ERTS_INLINE
void rlock_base_node(DbTableCATreeNode *base_node)
{
ASSERT(base_node->is_base_node);
if (EBUSY == erts_rwmtx_tryrlock(&base_node->u.base.lock)) {
/* The lock is contended */
BASE_NODE_STAT_ADD(base_node, ERL_DB_CATREE_LOCK_FAILURE_CONTRIBUTION);
erts_rwmtx_rlock(&base_node->u.base.lock);
}
}
static ERTS_INLINE
void runlock_base_node(DbTableCATreeNode *base_node, DbTableCATree* tb)
{
ASSERT(base_node->is_base_node);
erts_rwmtx_runlock(&base_node->u.base.lock);
do_random_join_with_low_probability(tb, (Uint)base_node);
}
static ERTS_INLINE
void runlock_base_node_no_rand(DbTableCATreeNode *base_node)
{
ASSERT(base_node->is_base_node);
erts_rwmtx_runlock(&base_node->u.base.lock);
}
static ERTS_INLINE
void lock_route_node(DbTableCATreeNode *route_node)
{
ASSERT(!route_node->is_base_node);
erts_mtx_lock(&route_node->u.route.lock);
}
static ERTS_INLINE
void unlock_route_node(DbTableCATreeNode *route_node)
{
ASSERT(!route_node->is_base_node);
erts_mtx_unlock(&route_node->u.route.lock);
}
static ERTS_INLINE
Eterm copy_route_key(DbRouteKey* dst, Eterm key, Uint key_size)
{
dst->size = key_size;
if (key_size != 0) {
Eterm* hp = &dst->heap[0];
ErlOffHeap tmp_offheap;
tmp_offheap.first = NULL;
dst->term = copy_struct(key, key_size, &hp, &tmp_offheap);
dst->oh = tmp_offheap.first;
}
else {
ASSERT(is_immed(key) ||
key == ERTS_GLOBAL_LIT_EMPTY_TUPLE);
dst->term = key;
dst->oh = NULL;
}
return dst->term;
}
static ERTS_INLINE
void destroy_route_key(DbRouteKey* key)
{
if (key->oh) {
ErlOffHeap oh;
oh.first = key->oh;
erts_cleanup_offheap(&oh);
}
}
static ERTS_INLINE
void init_root_iterator(DbTableCATree* tb, CATreeRootIterator* iter,
bool read_only)
{
iter->tb = tb;
iter->read_only = read_only;
iter->locked_bnode = NULL;
iter->next_route_key = THE_NON_VALUE;
iter->search_key = NULL;
}
static ERTS_INLINE
void lock_iter_base_node(CATreeRootIterator* iter,
DbTableCATreeNode *base_node,
DbTableCATreeNode *parent,
int current_level)
{
ASSERT(!iter->locked_bnode);
if (iter->read_only)
rlock_base_node(base_node);
else {
wlock_base_node(base_node);
iter->bnode_parent = parent;
iter->bnode_level = current_level;
}
iter->locked_bnode = base_node;
}
static ERTS_INLINE
void unlock_iter_base_node(CATreeRootIterator* iter)
{
ASSERT(iter->locked_bnode);
if (iter->read_only)
runlock_base_node(iter->locked_bnode, iter->tb);
else if (iter->locked_bnode->is_valid) {
wunlock_adapt_base_node(iter->tb, iter->locked_bnode,
iter->bnode_parent, iter->bnode_level);
} else
wunlock_base_node(iter->locked_bnode);
iter->locked_bnode = NULL;
}
static ERTS_INLINE
void destroy_root_iterator(CATreeRootIterator* iter)
{
if (iter->locked_bnode)
unlock_iter_base_node(iter);
if (iter->search_key) {
destroy_route_key(iter->search_key);
erts_free(ERTS_ALC_T_DB_TMP, iter->search_key);
}
}
typedef struct
{
DbTableCATreeNode *parent;
int current_level;
} FindBaseNode;
static ERTS_INLINE
DbTableCATreeNode* find_base_node(DbTableCATree* tb, Eterm key,
FindBaseNode* fbn)
{
DbTableCATreeNode* ERTS_RESTRICT node = GET_ROOT_ACQB(tb);
if (fbn) {
fbn->parent = NULL;
fbn->current_level = 0;
}
while (!node->is_base_node) {
if (fbn) {
fbn->current_level++;
fbn->parent = node;
}
if (cmp_key_route(key, node) < 0) {
node = GET_LEFT_ACQB(node);
} else {
node = GET_RIGHT_ACQB(node);
}
}
return node;
}
static ERTS_INLINE
DbTableCATreeNode* find_rlock_valid_base_node(DbTableCATree* tb, Eterm key)
{
DbTableCATreeNode* base_node;
while (1) {
base_node = find_base_node(tb, key, NULL);
rlock_base_node(base_node);