forked from spamhaus/rbldnsd
-
Notifications
You must be signed in to change notification settings - Fork 0
/
btrie.c
2676 lines (2360 loc) · 80.4 KB
/
btrie.c
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
/* Level-Compressed Tree Bitmap (LC-TBM) Trie implementation
*
* Contributed by Geoffrey T. Dairiki <dairiki@dairiki.org>
*
* This file is released under a "Three-clause BSD License".
*
* Copyright (c) 2013, Geoffrey T. Dairiki
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
*
* * Neither the name of Geoffrey T. Dairiki nor the names of other
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GEOFFREY
* T. DAIRIKI BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*/
/*****************************************************************
*
* This code implements a routing table conceptually based on a binary
* trie structure. Internally, the trie is represented by two types
* of compound nodes: "multibit nodes", which contain the top few
* levels of an entire binary subtree; and "level compression" (LC)
* nodes which represent a (potentially long) chain of out-degree one
* (single child) binary nodes (possibly ending at a terminal node).
*
* The multibit nodes are represented using a "Tree Bitmap" structure
* (more on this below), which is very efficient --- both in terms of
* memory usage and lookup speed --- at representing densely branching
* parts of the trie. The LC nodes can efficiently represent long
* non-branching chains of binary trie nodes. Using both node types
* together results in efficient representation of both the sparse and
* dense parts of a binary trie.
*
* Graphically, here's the rough idea:
*
* ........
* .LC o .
* . / . LC nodes can
* . o . <= represent long chains
* . \ . of (non-branching) binary
* . o . trie nodes
* . / .
* . o .
* ......../.....
* .TBM o .
* . / \ . TBM nodes can represent
* . o * . <= several levels of densely
* . / \ . branching binary trie nodes
* . o o .
* ......./.....\.......
* .TBM o .. o LC.
* . / \ .. \ .
* . o o .. o .
* . / / \ .. \ .
* . * o *.. o .
* ...../....... / .
* . o LC. . o .
* . \ . .....\......
* . * . . o TBM.
* ........ . / \ .
* . o o .
* . / \ \ .
* .* * *.
* ...........
*
* Terminology
* -----------
*
* node
* Usually, in the comments below, "node" will be used to refer to
* a compound node: either a multibit (TBM) node or an LC node.
*
* "internal node" or "prefix"
* The terms "prefix" or "internal node" are used to refer to
* a node in the binary trie which is internal to a multibit (TBM)
* node.
*
* ----------------------------------------------------------------
*
* Internal Representation of the Nodes
* ====================================
*
* Multibit (TBM) Nodes
* ~~~~~~~~~~~~~~~~~~~~
*
* The multibit nodes are represented using a "Tree Bitmap" (TBM)
* structure as described by Eatherton, Dittia and Varghese[1]. See
* the paper referenced below for basic details.
*
* A multibit node, represents several levels of a binary trie.
* For example, here is a multibit node of stride 2 (which represent
* two levels of a binary trie.
*
* +------- | ------+
* | multi o |
* | bit / \ |
* | node / \ |
* | o * |
* +--- / \ - / \ --+
* O
*
* Note that, for a multibit node of stride S, there are 2^S - 1 internal
* nodes, each of which may have data (or not) associated with them, and
* 2^S "external paths" leading to other (possibly compound nodes).
* (In the diagram above, one of three internal node (the one denoted by "*")
* has data, and one of four extending paths leads to an external node
* (denoted by the 'O').)
*
* The TBM structure can represent these bitmaps in a very memory-efficient
* manner.
*
* Each TBM node consists of two bitmaps --- the "internal bitmap" and the
* "extending paths bitmap" --- and a pointer which points to an array
* which contains both the extending path ("child") nodes and any
* internal prefix data for the TBM node.
*
* +--------+--------+
* TBM | ext bm | int bm |
* Node +--------+--------+
* | pointer |----+
* +-----------------+ |
* |
* |
* +-----------------+ |
* | extending path | |
* | node[N-1] | |
* +-----------------+ |
* / ... / |
* / ... / |
* +-----------------+ |
* | extending path | |
* | node[0] | |
* +-----------------+<---+
* | int. data[M-1] |
* +-----------------+
* / ... /
* +-----------------+
* | int. data[0] |
* +-----------------+
*
* The extending paths bitmap (or "ext bitmap") has one bit for each
* possible "extending path" from the bottom of the multibit node. To
* check if a particular extending path is present, one checks to see if
* the corresponding bit is set in the ext bitmap. The index into the
* array of children for that path can be found by counting the number
* of set bits to the left of that bit.
*
* Similary, the internal bitmap has one bit for each binary node
* which is internal to the multibit node. To determine whether there
* is data stored for an internal prefix, one checks the corresponding
* bit in the internal bitmap. As for extending paths, the index into
* the array of internal data is found by counting the number of set
* bits to the left of that bit.
*
* To save space in the node structure, the node data array is stored
* contiguously with the node extending path array. The single
* ("children") pointer in the TBM structure points to the beginning
* of the array of extending path nodes and to (one past) the end of
* the the internal data array.
*
* The multibit stride is chosen so that the entire TBM node structure fits
* in the space of two pointers. On 32 bit machines this means the stride
* is four (each of the two bitmaps is 16 bits); on 32 bit machines the
* stride is five.
*
* Note that there are only 2^stride - 1 internal prefixes in a TBM
* node. That means there is one unused bit in the internal bitmap.
* We require that that bit must always be clear for a TBM node. (If
* set, it indicates that the structure represents, instead, an LC
* node. See below.)
*
* ----------------------------------------------------------------
*
* Level Compression (LC) Nodes
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*
* LC nodes are used to represent a chain of out-degree-one (single
* child) prefixes in the binary trie. The are represented by a bit
* string (the "relative prefix") along with its length and a pointer
* to the extending path (the next node past the LC node.)
*
*
* Non-Terminal LC Node:
*
* +------------------+-------+
* | relative prefix |1|0|len|
* +------------------+-------+
* | ptr.child |--+
* +--------------------------+ |
* |
* |
* +--------------------------+ |
* | Next node - | |
* | either LC or TBM | |
* | | |
* +--------------------------+<-+
*
* The Relative Prefix
* -------------------
*
* The maximum relative prefix per LC node is selected so that (again)
* the entire node structure fits in the space of two pointers. On 32 bit
* machines, the maximum relative prefix is 24 bits; on 62 bit machines
* the limit is 56 bits.
*
* In the LC node structure, the relative prefix is stored as an array
* of bytes. To avoid some bit-shifting during tree searches, these
* bytes are byte-aligned with the global prefix. In other words, in
* general there are (pos % 8) "pad" bits at the beginning of the
* relative prefix --- where pos "starting bit" (or depth in the
* binary tree) of the LC node --- which really belong to the parent
* node(s) of the LC node. For efficiency (so that we don't have to
* mask them out when matching) we require that these pad bits be
* correct --- they must match the path which leads to the LC node.
*
* The relative prefix length stored in the LC node structure does not
* count the pad bits.
*
* Terminal Node Compression
* -------------------------
*
* For memory efficiency, we also support "terminal LC" nodes. When
* the extension path from an LC node consists a single terminal node,
* we store that terminal nodes data directly in the parent LC node.
*
* Instead of this:
*
* +------------------+-------+
* | relative prefix |1|0|len|
* +------------------+-------+
* | ptr.child |--+
* +--------------------------+ |
* |
* +--------------------------+ |
* | Terminal Node (TBM node, | |
* | empty except for the | |
* +--| root internal node.) | |
* | +--------------------------+<-+
* |
* +->+--------------------------+
* | terminal node data |
* +--------------------------+
*
* We can do this:
*
* +------------------+-------+
* | relative prefix |1|1|len|
* +------------------+-------+
* | terminal node data |
* +--------------------------+
*
* Terminal LC nodes are differentiated from non-terminal LC nodes
* by the setting of the is_terminal flag.
*
* Node Structure Packing Details
* ------------------------------
*
* The LC and TBM node structures are carefully packed so that the
* "is_lc" flag (which indicates that a node is an LC node)
* corresponds to the one unused bit in the internal bitmap of the TBM
* node structure (which we require to be zero for TBM nodes).
*
* ----------------------------------------------------------------
*
* References
* ==========
*
* [1] Will Eatherton, George Varghese, and Zubin Dittia. 2004. Tree
* bitmap: hardware/software IP lookups with incremental
* updates. SIGCOMM Comput. Commun. Rev. 34, 2 (April 2004),
* 97-122. DOI=10.1145/997150.997160
* http://doi.acm.org/10.1145/997150.997160
* http://comnet.kaist.ac.kr/yhlee/CN_2008_Spring/readings/Eath-04-tree_bitmap.pdf
*
****************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <setjmp.h>
#if defined(TEST) && defined(NDEBUG)
# warning undefining NDEBUG for TEST build
# undef NDEBUG
#endif
#include <assert.h>
#include "btrie.h"
#include "mempool.h"
#if __SIZEOF_POINTER__ == 4
# define TBM_STRIDE 4
#elif __SIZEOF_POINTER__ == 8
# define TBM_STRIDE 5
#else
# error "Unsupported word size"
#endif
#ifndef NO_STDINT_H
# if TBM_STRIDE == 4
typedef uint16_t tbm_bitmap_t;
# else
typedef uint32_t tbm_bitmap_t;
# endif
#else /* NO_STDINT_H */
# if TBM_STRIDE == 4
# if SIZEOF_SHORT == 2
typedef short unsigned tbm_bitmap_t;
# else
# error "can not determine type for 16 bit unsigned int"
# endif
# else /* TBM_STRIDE == 5 */
# if SIZEOF_INT == 4
typedef unsigned tbm_bitmap_t;
# elif SIZEOF_LONG == 4
typedef long unsigned tbm_bitmap_t;
# else
# error "can not determine type for 32 bit unsigned int"
# endif
# endif
#endif
#define TBM_FANOUT (1U << TBM_STRIDE)
#define LC_BYTES_PER_NODE (__SIZEOF_POINTER__ - 1)
typedef union node_u node_t;
/* The tbm_node and lc_node structs must be packed so that the the
* high bit (LC_FLAGS_IS_LC) of lc_flags in the the lc_node struct
* coincides with bit zero (the most significant bit) of tbm_node's
* int_bm. (This bit is how we differentiate between the two node
* types. It is always clear for a tbm_node and always set for an
* lc_node.)
*/
struct tbm_node {
#ifdef WORDS_BIGENDIAN
tbm_bitmap_t int_bm; /* the internal bitmap */
tbm_bitmap_t ext_bm; /* extending path ("external") bitmap */
#else
tbm_bitmap_t ext_bm; /* extending path ("external") bitmap */
tbm_bitmap_t int_bm; /* the internal bitmap */
#endif
union {
node_t *children; /* pointer to array of children */
const void **data_end; /* one past end of internal prefix data array */
} ptr;
};
struct lc_node {
/* lc_flags contains the LC prefix length and a couple of bit flags
* (apparently char-sized bit fields are a gcc extension)
*/
# define LC_FLAGS_IS_LC 0x80
# define LC_FLAGS_IS_TERMINAL 0x40
# define LC_FLAGS_LEN_MASK 0x3f
#ifdef WORDS_BIGENDIAN
btrie_oct_t lc_flags;
btrie_oct_t prefix[LC_BYTES_PER_NODE];
#else
btrie_oct_t prefix[LC_BYTES_PER_NODE];
btrie_oct_t lc_flags;
#endif
union {
node_t *child; /* pointer to child (if !is_terminal) */
const void *data; /* the prefix data (if is_terminal) */
} ptr;
};
union node_u {
struct tbm_node tbm_node;
struct lc_node lc_node;
};
struct free_hunk {
struct free_hunk *next;
};
#define MAX_CHILD_ARRAY_LEN (TBM_FANOUT + TBM_FANOUT / 2)
struct btrie {
node_t root;
struct mempool *mp;
struct free_hunk *free_list[MAX_CHILD_ARRAY_LEN];
jmp_buf exception;
/* mem mgmt stats */
size_t alloc_total; /* total bytes allocated from mempool */
size_t alloc_data; /* bytes allocated for TBM node int. prefix data */
size_t alloc_waste; /* bytes wasted by rounding of data array size */
#ifdef BTRIE_DEBUG_ALLOC
size_t alloc_hist[MAX_CHILD_ARRAY_LEN * 2]; /* histogram of alloc sizes */
#endif
/* trie stats */
size_t n_entries; /* number of entries */
size_t n_tbm_nodes; /* total number of TBM nodes in tree */
size_t n_lc_nodes; /* total number of LC nodes in tree */
};
/****************************************************************
*
* Memory management
*
* We will need to frequently resize child/data arrays. The current
* mempool implementation does not support resizing/freeing, so here
* we roll our own.
*/
static inline void
_free_hunk(struct btrie *btrie, void *buf, unsigned n_nodes)
{
struct free_hunk *hunk = buf;
hunk->next = btrie->free_list[n_nodes - 1];
btrie->free_list[n_nodes - 1] = hunk;
}
static inline void *
_get_hunk(struct btrie *btrie, unsigned n_nodes)
{
struct free_hunk *hunk = btrie->free_list[n_nodes - 1];
if (hunk != NULL)
btrie->free_list[n_nodes - 1] = hunk->next;
return hunk;
}
/* Get pointer to uninitialized child/data array.
*
* Allocates memory for an array of NDATA (void *)s followed by an
* array of NCHILDREN (node_t)s. The returned pointer points to to
* beginning of the children array (i.e. it points to (one past) the
* end of the data array.)
*/
static node_t *
alloc_nodes(struct btrie *btrie, unsigned nchildren, unsigned ndata)
{
size_t n_nodes = nchildren + (ndata + 1) / 2;
node_t *hunk;
assert(n_nodes > 0 && n_nodes <= MAX_CHILD_ARRAY_LEN);
hunk = _get_hunk(btrie, n_nodes);
if (hunk == NULL) {
/* Do not have free hunk of exactly the requested size, look for a
* larger hunk. (The funny order in which we scan the buckets is
* heuristically selected in an attempt to minimize unnecessary
* creation of small fragments)
*/
size_t n, skip = n_nodes > 4 ? 4 : n_nodes;
for (n = n_nodes + skip; n <= MAX_CHILD_ARRAY_LEN; n++) {
if ((hunk = _get_hunk(btrie, n)) != NULL) {
_free_hunk(btrie, hunk + n_nodes, n - n_nodes);
goto DONE;
}
}
for (n = n_nodes + 1; n < n_nodes + skip && n <= MAX_CHILD_ARRAY_LEN; n++) {
if ((hunk = _get_hunk(btrie, n)) != NULL) {
_free_hunk(btrie, hunk + n_nodes, n - n_nodes);
goto DONE;
}
}
/* failed to find free hunk, allocate a fresh one */
hunk = mp_alloc(btrie->mp, n_nodes * sizeof(node_t), 1);
if (hunk == NULL)
longjmp(btrie->exception, BTRIE_ALLOC_FAILED);
btrie->alloc_total += n_nodes * sizeof(node_t);
}
DONE:
btrie->alloc_data += ndata * sizeof(void *);
btrie->alloc_waste += (ndata % 2) * sizeof(void *);
#ifdef BTRIE_DEBUG_ALLOC
btrie->alloc_hist[2 * nchildren + ndata]++;
#endif
/* adjust pointer to allow room for data array before child array */
return hunk + (ndata + 1) / 2;
}
/* Free memory allocated by alloc_nodes */
static void
free_nodes(struct btrie *btrie, node_t *buf, unsigned nchildren, unsigned ndata)
{
size_t n_nodes = nchildren + (ndata + 1) / 2;
assert(n_nodes > 0 && n_nodes <= MAX_CHILD_ARRAY_LEN);
_free_hunk(btrie, buf - (ndata + 1) / 2, n_nodes);
btrie->alloc_data -= ndata * sizeof(void *);
btrie->alloc_waste -= (ndata % 2) * sizeof(void *);
#ifdef BTRIE_DEBUG_ALLOC
btrie->alloc_hist[2 * nchildren + ndata]--;
#endif
}
/* Debugging/development only: */
#ifdef BTRIE_DEBUG_ALLOC
static void
dump_alloc_hist(const struct btrie *btrie)
{
unsigned bin;
size_t total_alloc = 0;
size_t total_free = 0;
size_t total_bytes = 0;
size_t total_waste = 0;
size_t total_free_bytes = 0;
puts("hunk alloc free alloc wasted free");
puts("size hunks hunks bytes bytes bytes");
puts("==== ====== ====== ======== ======== ========");
for (bin = 1; bin < 2 * MAX_CHILD_ARRAY_LEN; bin++) {
size_t n_alloc = btrie->alloc_hist[bin];
size_t bytes = n_alloc * bin * sizeof(void *);
size_t waste_bytes = (bin % 2) * n_alloc * sizeof(void *);
size_t n_free = 0, free_bytes;
if (bin % 2 == 0) {
const struct free_hunk *hunk;
for (hunk = btrie->free_list[bin / 2 - 1]; hunk; hunk = hunk->next)
n_free++;
}
free_bytes = n_free * bin * sizeof(void *);
printf("%3zu: %6zu %6zu %8zu %8zu %8zu\n", bin * sizeof(void *),
n_alloc, n_free, bytes, waste_bytes, free_bytes);
total_alloc += n_alloc;
total_free += n_free;
total_bytes += bytes;
total_waste += waste_bytes;
total_free_bytes += free_bytes;
}
puts("---- ------ ------ -------- -------- --------");
printf("SUM: %6zu %6zu %8zu %8zu %8zu\n",
total_alloc, total_free, total_bytes, total_waste, total_free_bytes);
}
#endif
/****************************************************************
*
* Bit twiddling
*
*/
static inline tbm_bitmap_t
bit(unsigned b)
{
return 1U << ((1 << TBM_STRIDE) - 1 - b);
}
/* count the number of set bits in bitmap
*
* algorithm from
* http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
*/
static inline unsigned
count_bits(tbm_bitmap_t v)
{
/* Count set bits in parallel. */
/* v = (v & 0x5555...) + ((v >> 1) & 0x5555...); */
v -= (v >> 1) & (tbm_bitmap_t)~0UL/3;
/* v = (v & 0x3333...) + ((v >> 2) & 0x3333...); */
v = (v & (tbm_bitmap_t)~0UL/5) + ((v >> 2) & (tbm_bitmap_t)~0UL/5);
/* v = (v & 0x0f0f...) + ((v >> 4) & 0x0f0f...); */
v = (v + (v >> 4)) & (tbm_bitmap_t)~0UL/17;
/* v = v % 255; */
#if TBM_STRIDE == 4
/* tbm_bitmap_t is uint16_t, avoid the multiply */
return (v + (v >> 8)) & 0x0ff;
#else
return (v * (tbm_bitmap_t)(~0UL/255)) >> ((sizeof(tbm_bitmap_t) - 1) * 8);
#endif
}
static inline unsigned
count_bits_before(tbm_bitmap_t bm, int b)
{
return b ? count_bits(bm >> ((1 << TBM_STRIDE) - b)) : 0;
}
static inline unsigned
count_bits_from(tbm_bitmap_t bm, int b)
{
return count_bits(bm << b);
}
/* extracts a few bits from bitstring, returning them as an integer */
static inline btrie_oct_t
extract_bits(const btrie_oct_t *prefix, unsigned pos, unsigned nbits)
{
if (nbits == 0)
return 0;
else {
unsigned v = (prefix[pos / 8] << 8) + prefix[pos / 8 + 1];
return (v >> (16 - nbits - pos % 8)) & ((1U << nbits) - 1);
}
}
static inline unsigned
extract_bit(const btrie_oct_t *prefix, int pos)
{
return (prefix[pos / 8] >> (7 - pos % 8)) & 0x01;
}
/* get mask for high n bits of a byte */
static inline btrie_oct_t
high_bits(unsigned n)
{
return (btrie_oct_t) -(1U << (8 - n));
}
/* determine whether two prefixes are equal */
static inline int
prefixes_equal(const btrie_oct_t *pfx1, const btrie_oct_t *pfx2, unsigned len)
{
return (memcmp(pfx1, pfx2, len / 8) == 0
&& ((pfx1[len / 8] ^ pfx2[len / 8]) & high_bits(len % 8)) == 0);
}
/* determine length of longest common subprefix */
static inline unsigned
common_prefix(const btrie_oct_t *pfx1, const btrie_oct_t *pfx2, unsigned len)
{
/* algorithm adapted from
* http://graphics.stanford.edu/~seander/bithacks.html#IntegerLogLookup
*/
static btrie_oct_t leading_zeros[] = {
8, 7, 6, 6, 5, 5, 5, 5, 4, 4, 4, 4, 4, 4, 4, 4,
3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
};
unsigned nb;
for (nb = 0; nb < len / 8; nb++) {
unsigned diff = *pfx1++ ^ *pfx2++;
if (diff != 0)
return 8 * nb + leading_zeros[diff];
}
if (len % 8) {
unsigned n = leading_zeros[*pfx1 ^ *pfx2];
if (n < len % 8)
return 8 * nb + n;
}
return len;
}
/****************************************************************
*/
static inline int
is_empty_node(const node_t *node)
{
return node->tbm_node.ext_bm == 0 && node->tbm_node.int_bm == 0;
}
static inline int
is_lc_node(const node_t *node)
{
return (node->lc_node.lc_flags & LC_FLAGS_IS_LC) != 0;
}
static inline int
is_tbm_node(const node_t *node)
{
return !is_lc_node(node);
}
/* is node a TBM node with internal data? */
static inline int
has_data(const node_t *node)
{
return is_tbm_node(node) && node->tbm_node.int_bm != 0;
}
static inline unsigned
base_index(unsigned pfx, unsigned plen)
{
assert(plen < TBM_STRIDE);
assert(pfx < (1U << plen));
return pfx | (1U << plen);
}
/* initialize node to an empty TBM node */
static inline void
init_empty_node(struct btrie *btrie, node_t *node)
{
memset(node, 0, sizeof(*node));
btrie->n_tbm_nodes++;
}
/* get pointer to TBM internal prefix data */
static inline const void **
tbm_data_p(const struct tbm_node *node, unsigned pfx, unsigned plen)
{
unsigned bi = base_index(pfx, plen);
if ((node->int_bm & bit(bi)) == 0)
return NULL; /* no data */
else {
return &node->ptr.data_end[ -(int)count_bits_from(node->int_bm, bi) ];
}
}
/* add an element to the internal data array */
static void
tbm_insert_data(struct btrie *btrie, struct tbm_node *node,
unsigned pfx, unsigned plen, const void *data)
{
/* XXX: don't realloc if already big enough? */
unsigned bi = base_index(pfx, plen);
unsigned nchildren = count_bits(node->ext_bm);
int ndata = count_bits(node->int_bm);
unsigned di = count_bits_before(node->int_bm, bi);
node_t *old_children = node->ptr.children;
const void **old_data_beg = node->ptr.data_end - ndata;
const void **data_beg;
assert((node->int_bm & bit(bi)) == 0);
node->ptr.children = alloc_nodes(btrie, nchildren, ndata + 1);
data_beg = node->ptr.data_end - (ndata + 1);
data_beg[di] = data;
node->int_bm |= bit(bi);
if (nchildren != 0 || ndata != 0) {
memcpy(data_beg, old_data_beg, di * sizeof(data_beg[0]));
memcpy(&data_beg[di + 1], &old_data_beg[di],
(ndata - di) * sizeof(data_beg[0]) + nchildren * sizeof(node_t));
free_nodes(btrie, old_children, nchildren, ndata);
}
}
/* determine whether TBM has internal prefix data for pfx/plen or ancestors */
static inline int
has_internal_data(const struct tbm_node *node, unsigned pfx, unsigned plen)
{
# define BIT(n) (1U << ((1 << TBM_STRIDE) - 1 - (n)))
# define B0() BIT(1) /* the bit for 0/0 */
# define B1(n) (BIT((n) + 2) | B0()) /* the bits for n/1 and its ancestors */
# define B2(n) (BIT((n) + 4) | B1(n >> 1)) /* the bits for n/2 and ancestors */
# define B3(n) (BIT((n) + 8) | B2(n >> 1)) /* the bits for n/3 and ancestors */
# define B4(n) (BIT((n) + 16) | B3(n >> 1)) /* the bits for n/4 and ancestors */
static tbm_bitmap_t ancestors[] = {
0, B0(),
B1(0), B1(1),
B2(0), B2(1), B2(2), B2(3),
B3(0), B3(1), B3(2), B3(3), B3(4), B3(5), B3(6), B3(7),
# if TBM_STRIDE == 5
B4(0), B4(1), B4(2), B4(3), B4(4), B4(5), B4(6), B4(7),
B4(8), B4(9), B4(10), B4(11), B4(12), B4(13), B4(14), B4(15),
# elif TBM_STRIDE != 4
# error "unsupported TBM_STRIDE"
# endif
};
# undef B4
# undef B3
# undef B2
# undef B1
# undef B0
# undef BIT
return (node->int_bm & ancestors[base_index(pfx, plen)]) != 0;
}
/* get pointer to TBM extending path */
static inline node_t *
tbm_ext_path(const struct tbm_node *node, unsigned pfx)
{
if ((node->ext_bm & bit(pfx)) == 0)
return NULL;
else
return &node->ptr.children[count_bits_before(node->ext_bm, pfx)];
}
/* resize TBM node child array to make space for new child node */
static node_t *
tbm_insert_ext_path(struct btrie *btrie, struct tbm_node *node, unsigned pfx)
{
unsigned nchildren = count_bits(node->ext_bm);
unsigned ci = count_bits_before(node->ext_bm, pfx);
int ndata = count_bits(node->int_bm);
node_t *old_children = node->ptr.children;
const void **old_data_beg = node->ptr.data_end - ndata;
assert ((node->ext_bm & bit(pfx)) == 0);
node->ptr.children = alloc_nodes(btrie, nchildren + 1, ndata);
init_empty_node(btrie, &node->ptr.children[ci]);
node->ext_bm |= bit(pfx);
if (nchildren != 0 || ndata != 0) {
const void **data_beg = node->ptr.data_end - ndata;
memcpy(data_beg, old_data_beg,
ndata * sizeof(data_beg[0]) + ci * sizeof(node_t));
memcpy(&node->ptr.children[ci + 1], &old_children[ci],
(nchildren - ci) * sizeof(old_children[0]));
free_nodes(btrie, old_children, nchildren, ndata);
}
return &node->ptr.children[ci];
}
static inline int
lc_is_terminal(const struct lc_node *node)
{
return (node->lc_flags & LC_FLAGS_IS_TERMINAL) != 0;
}
static inline unsigned
lc_len(const struct lc_node *node)
{
return node->lc_flags & LC_FLAGS_LEN_MASK;
}
static inline void
lc_init_flags(struct lc_node *node, int is_terminal, unsigned len)
{
assert((len & ~LC_FLAGS_LEN_MASK) == 0);
node->lc_flags = LC_FLAGS_IS_LC | len;
if (is_terminal)
node->lc_flags |= LC_FLAGS_IS_TERMINAL;
}
static inline void
lc_add_to_len(struct lc_node *node, int increment)
{
unsigned new_len = lc_len(node) + increment;
assert((new_len & ~LC_FLAGS_LEN_MASK) == 0);
node->lc_flags = (node->lc_flags & ~LC_FLAGS_LEN_MASK) | new_len;
}
static inline unsigned
lc_shift(unsigned pos)
{
return pos / 8;
}
static inline unsigned
lc_base(unsigned pos)
{
return 8 * lc_shift(pos);
}
static inline unsigned
lc_bits(const struct lc_node *node, unsigned pos)
{
return pos % 8 + lc_len(node);
}
static inline unsigned
lc_bytes(const struct lc_node *node, unsigned pos)
{
return (lc_bits(node, pos) + 7) / 8;
}
static inline unsigned
lc_leading_bits(const struct lc_node *node, unsigned pos, unsigned nbits)
{
return extract_bits(node->prefix, pos % 8, nbits);
}
/* Initialize a new terminal LC node
*
* If prefix is too long to fit in a single LC node, then a chain
* of LC nodes will be created.
*/
static void
init_terminal_node(struct btrie *btrie, node_t *dst, unsigned pos,
const btrie_oct_t *prefix, unsigned len, const void *data)
{
struct lc_node *node = &dst->lc_node;
unsigned nbytes = (len + 7) / 8;
while (nbytes - lc_shift(pos) > LC_BYTES_PER_NODE) {
memcpy(node->prefix, prefix + lc_shift(pos), LC_BYTES_PER_NODE);
lc_init_flags(node, 0, 8 * LC_BYTES_PER_NODE - pos % 8);
node->ptr.child = alloc_nodes(btrie, 1, 0);
pos += lc_len(node);
node = &node->ptr.child->lc_node;
btrie->n_lc_nodes++;
}
memcpy(node->prefix, prefix + lc_shift(pos), nbytes - lc_shift(pos));
lc_init_flags(node, 1, len - pos);
node->ptr.data = data;
btrie->n_lc_nodes++;
}
/* merge chains of multiple LC nodes into a single LC node, if possible.
*
* also ensure that the leading nodes in the LC chain have maximum length.
*/
static void
coalesce_lc_node(struct btrie *btrie, struct lc_node *node, unsigned pos)
{
while (! lc_is_terminal(node)
&& lc_bits(node, pos) < 8 * LC_BYTES_PER_NODE
&& is_lc_node(node->ptr.child)) {
struct lc_node *child = &node->ptr.child->lc_node;
unsigned spare_bits = 8 * LC_BYTES_PER_NODE - lc_bits(node, pos);
unsigned end = pos + lc_len(node);
unsigned shift = lc_shift(end) - lc_shift(pos);
if (lc_len(child) <= spare_bits) {
/* node plus child will fit in single node - merge */
memcpy(node->prefix + shift, child->prefix,
lc_bytes(child, end));
lc_init_flags(node, lc_is_terminal(child), lc_len(node) + lc_len(child));
node->ptr = child->ptr;
free_nodes(btrie, (node_t *)child, 1, 0);
btrie->n_lc_nodes--;
}
else {
/* can't merge, but can take some of childs bits */
unsigned cshift = lc_shift(end + spare_bits) - lc_shift(end);
memcpy(node->prefix + shift, child->prefix, LC_BYTES_PER_NODE - shift);
lc_add_to_len(node, spare_bits);
if (cshift)
memmove(child->prefix, child->prefix + cshift,
lc_bytes(child, end) - cshift);
assert(lc_len(child) > spare_bits);
lc_add_to_len(child, -spare_bits);
pos += lc_len(node);
node = child;
}
}
}
static void init_tbm_node(struct btrie *btrie, node_t *node, unsigned pos,
const btrie_oct_t pbyte,
const void **root_data_p,
node_t *left, node_t *right);
/* given an LC node at orig_pos, create a new (shorter) node at pos */
static void
shorten_lc_node(struct btrie *btrie, node_t *dst, unsigned pos,
struct lc_node *src, unsigned orig_pos)
{
assert(orig_pos < pos);
assert(lc_len(src) >= pos - orig_pos);
assert(dst != (node_t *)src);
if (lc_len(src) == pos - orig_pos && !lc_is_terminal(src)) {
/* just steal the child */
node_t *child = src->ptr.child;
*dst = *child;
free_nodes(btrie, child, 1, 0);
btrie->n_lc_nodes--;
}