blob: 77813c1e829498a7a2521b27584c86ef1013e5d3 [file] [log] [blame]
Willy Tarreauc2186022009-10-26 19:48:54 +01001/*
2 * Elastic Binary Trees - generic macros and structures.
3 * Version 5.0
4 * (C) 2002-2009 - Willy Tarreau <w@1wt.eu>
5 *
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
19 *
20 *
21 * Short history :
22 *
23 * 2007/09/28: full support for the duplicates tree => v3
24 * 2007/07/08: merge back cleanups from kernel version.
25 * 2007/07/01: merge into Linux Kernel (try 1).
26 * 2007/05/27: version 2: compact everything into one single struct
27 * 2007/05/18: adapted the structure to support embedded nodes
28 * 2007/05/13: adapted to mempools v2.
29 */
30
31
32
33/*
34 General idea:
35 -------------
36 In a radix binary tree, we may have up to 2N-1 nodes for N keys if all of
37 them are leaves. If we find a way to differentiate intermediate nodes (later
38 called "nodes") and final nodes (later called "leaves"), and we associate
39 them by two, it is possible to build sort of a self-contained radix tree with
40 intermediate nodes always present. It will not be as cheap as the ultree for
41 optimal cases as shown below, but the optimal case almost never happens :
42
43 Eg, to store 8, 10, 12, 13, 14 :
44
45 ultree this theorical tree
46
47 8 8
48 / \ / \
49 10 12 10 12
50 / \ / \
51 13 14 12 14
52 / \
53 12 13
54
55 Note that on real-world tests (with a scheduler), is was verified that the
56 case with data on an intermediate node never happens. This is because the
57 data spectrum is too large for such coincidences to happen. It would require
58 for instance that a task has its expiration time at an exact second, with
59 other tasks sharing that second. This is too rare to try to optimize for it.
60
61 What is interesting is that the node will only be added above the leaf when
62 necessary, which implies that it will always remain somewhere above it. So
63 both the leaf and the node can share the exact value of the leaf, because
64 when going down the node, the bit mask will be applied to comparisons. So we
65 are tempted to have one single key shared between the node and the leaf.
66
67 The bit only serves the nodes, and the dups only serve the leaves. So we can
68 put a lot of information in common. This results in one single entity with
69 two branch pointers and two parent pointers, one for the node part, and one
70 for the leaf part :
71
72 node's leaf's
73 parent parent
74 | |
75 [node] [leaf]
76 / \
77 left right
78 branch branch
79
80 The node may very well refer to its leaf counterpart in one of its branches,
81 indicating that its own leaf is just below it :
82
83 node's
84 parent
85 |
86 [node]
87 / \
88 left [leaf]
89 branch
90
91 Adding keys in such a tree simply consists in inserting nodes between
92 other nodes and/or leaves :
93
94 [root]
95 |
96 [node2]
97 / \
98 [leaf1] [node3]
99 / \
100 [leaf2] [leaf3]
101
102 On this diagram, we notice that [node2] and [leaf2] have been pulled away
103 from each other due to the insertion of [node3], just as if there would be
104 an elastic between both parts. This elastic-like behaviour gave its name to
105 the tree : "Elastic Binary Tree", or "EBtree". The entity which associates a
106 node part and a leaf part will be called an "EB node".
107
108 We also notice on the diagram that there is a root entity required to attach
109 the tree. It only contains two branches and there is nothing above it. This
110 is an "EB root". Some will note that [leaf1] has no [node1]. One property of
111 the EBtree is that all nodes have their branches filled, and that if a node
112 has only one branch, it does not need to exist. Here, [leaf1] was added
113 below [root] and did not need any node.
114
115 An EB node contains :
116 - a pointer to the node's parent (node_p)
117 - a pointer to the leaf's parent (leaf_p)
118 - two branches pointing to lower nodes or leaves (branches)
119 - a bit position (bit)
120 - an optional key.
121
122 The key here is optional because it's used only during insertion, in order
123 to classify the nodes. Nothing else in the tree structure requires knowledge
124 of the key. This makes it possible to write type-agnostic primitives for
125 everything, and type-specific insertion primitives. This has led to consider
126 two types of EB nodes. The type-agnostic ones will serve as a header for the
127 other ones, and will simply be called "struct eb_node". The other ones will
128 have their type indicated in the structure name. Eg: "struct eb32_node" for
129 nodes carrying 32 bit keys.
130
131 We will also node that the two branches in a node serve exactly the same
132 purpose as an EB root. For this reason, a "struct eb_root" will be used as
133 well inside the struct eb_node. In order to ease pointer manipulation and
134 ROOT detection when walking upwards, all the pointers inside an eb_node will
135 point to the eb_root part of the referenced EB nodes, relying on the same
136 principle as the linked lists in Linux.
137
138 Another important point to note, is that when walking inside a tree, it is
139 very convenient to know where a node is attached in its parent, and what
140 type of branch it has below it (leaf or node). In order to simplify the
141 operations and to speed up the processing, it was decided in this specific
142 implementation to use the lowest bit from the pointer to designate the side
143 of the upper pointers (left/right) and the type of a branch (leaf/node).
144 This practise is not mandatory by design, but an implementation-specific
145 optimisation permitted on all platforms on which data must be aligned. All
146 known 32 bit platforms align their integers and pointers to 32 bits, leaving
147 the two lower bits unused. So, we say that the pointers are "tagged". And
148 since they designate pointers to root parts, we simply call them
149 "tagged root pointers", or "eb_troot" in the code.
150
151 Duplicate keys are stored in a special manner. When inserting a key, if
152 the same one is found, then an incremental binary tree is built at this
153 place from these keys. This ensures that no special case has to be written
154 to handle duplicates when walking through the tree or when deleting entries.
155 It also guarantees that duplicates will be walked in the exact same order
156 they were inserted. This is very important when trying to achieve fair
157 processing distribution for instance.
158
159 Algorithmic complexity can be derived from 3 variables :
160 - the number of possible different keys in the tree : P
161 - the number of entries in the tree : N
162 - the number of duplicates for one key : D
163
164 Note that this tree is deliberately NOT balanced. For this reason, the worst
165 case may happen with a small tree (eg: 32 distinct keys of one bit). BUT,
166 the operations required to manage such data are so much cheap that they make
167 it worth using it even under such conditions. For instance, a balanced tree
168 may require only 6 levels to store those 32 keys when this tree will
169 require 32. But if per-level operations are 5 times cheaper, it wins.
170
171 Minimal, Maximal and Average times are specified in number of operations.
172 Minimal is given for best condition, Maximal for worst condition, and the
173 average is reported for a tree containing random keys. An operation
174 generally consists in jumping from one node to the other.
175
176 Complexity :
177 - lookup : min=1, max=log(P), avg=log(N)
178 - insertion from root : min=1, max=log(P), avg=log(N)
179 - insertion of dups : min=1, max=log(D), avg=log(D)/2 after lookup
180 - deletion : min=1, max=1, avg=1
181 - prev/next : min=1, max=log(P), avg=2 :
182 N/2 nodes need 1 hop => 1*N/2
183 N/4 nodes need 2 hops => 2*N/4
184 N/8 nodes need 3 hops => 3*N/8
185 ...
186 N/x nodes need log(x) hops => log2(x)*N/x
187 Total cost for all N nodes : sum[i=1..N](log2(i)*N/i) = N*sum[i=1..N](log2(i)/i)
188 Average cost across N nodes = total / N = sum[i=1..N](log2(i)/i) = 2
189
190 This design is currently limited to only two branches per node. Most of the
191 tree descent algorithm would be compatible with more branches (eg: 4, to cut
192 the height in half), but this would probably require more complex operations
193 and the deletion algorithm would be problematic.
194
195 Useful properties :
196 - a node is always added above the leaf it is tied to, and never can get
197 below nor in another branch. This implies that leaves directly attached
198 to the root do not use their node part, which is indicated by a NULL
199 value in node_p. This also enhances the cache efficiency when walking
200 down the tree, because when the leaf is reached, its node part will
201 already have been visited (unless it's the first leaf in the tree).
202
203 - pointers to lower nodes or leaves are stored in "branch" pointers. Only
204 the root node may have a NULL in either branch, it is not possible for
205 other branches. Since the nodes are attached to the left branch of the
206 root, it is not possible to see a NULL left branch when walking up a
207 tree. Thus, an empty tree is immediately identified by a NULL left
208 branch at the root. Conversely, the one and only way to identify the
209 root node is to check that it right branch is NULL. Note that the
210 NULL pointer may have a few low-order bits set.
211
212 - a node connected to its own leaf will have branch[0|1] pointing to
213 itself, and leaf_p pointing to itself.
214
215 - a node can never have node_p pointing to itself.
216
217 - a node is linked in a tree if and only if it has a non-null leaf_p.
218
219 - a node can never have both branches equal, except for the root which can
220 have them both NULL.
221
222 - deletion only applies to leaves. When a leaf is deleted, its parent must
223 be released too (unless it's the root), and its sibling must attach to
224 the grand-parent, replacing the parent. Also, when a leaf is deleted,
225 the node tied to this leaf will be removed and must be released too. If
226 this node is different from the leaf's parent, the freshly released
227 leaf's parent will be used to replace the node which must go. A released
228 node will never be used anymore, so there's no point in tracking it.
229
230 - the bit index in a node indicates the bit position in the key which is
231 represented by the branches. That means that a node with (bit == 0) is
232 just above two leaves. Negative bit values are used to build a duplicate
233 tree. The first node above two identical leaves gets (bit == -1). This
234 value logarithmically decreases as the duplicate tree grows. During
235 duplicate insertion, a node is inserted above the highest bit value (the
236 lowest absolute value) in the tree during the right-sided walk. If bit
237 -1 is not encountered (highest < -1), we insert above last leaf.
238 Otherwise, we insert above the node with the highest value which was not
239 equal to the one of its parent + 1.
240
241 - the "eb_next" primitive walks from left to right, which means from lower
242 to higher keys. It returns duplicates in the order they were inserted.
243 The "eb_first" primitive returns the left-most entry.
244
245 - the "eb_prev" primitive walks from right to left, which means from
246 higher to lower keys. It returns duplicates in the opposite order they
247 were inserted. The "eb_last" primitive returns the right-most entry.
248
249 - a tree which has 1 in the lower bit of its root's right branch is a
250 tree with unique nodes. This means that when a node is inserted with
251 a key which already exists will not be inserted, and the previous
252 entry will be returned.
253
254 */
255
256#ifndef _EBTREE_H
257#define _EBTREE_H
258
259#include <stdlib.h>
260
261/* Note: we never need to run fls on null keys, so we can optimize the fls
262 * function by removing a conditional jump.
263 */
264#if defined(__i386__)
265static inline int flsnz(int x)
266{
267 int r;
268 __asm__("bsrl %1,%0\n"
269 : "=r" (r) : "rm" (x));
270 return r+1;
271}
272#else
273// returns 1 to 32 for 1<<0 to 1<<31. Undefined for 0.
274#define flsnz(___a) ({ \
275 register int ___x, ___bits = 0; \
276 ___x = (___a); \
277 if (___x & 0xffff0000) { ___x &= 0xffff0000; ___bits += 16;} \
278 if (___x & 0xff00ff00) { ___x &= 0xff00ff00; ___bits += 8;} \
279 if (___x & 0xf0f0f0f0) { ___x &= 0xf0f0f0f0; ___bits += 4;} \
280 if (___x & 0xcccccccc) { ___x &= 0xcccccccc; ___bits += 2;} \
281 if (___x & 0xaaaaaaaa) { ___x &= 0xaaaaaaaa; ___bits += 1;} \
282 ___bits + 1; \
283 })
284#endif
285
286static inline int fls64(unsigned long long x)
287{
288 unsigned int h;
289 unsigned int bits = 32;
290
291 h = x >> 32;
292 if (!h) {
293 h = x;
294 bits = 0;
295 }
296 return flsnz(h) + bits;
297}
298
299#define fls_auto(x) ((sizeof(x) > 4) ? fls64(x) : flsnz(x))
300
301/* Linux-like "container_of". It returns a pointer to the structure of type
302 * <type> which has its member <name> stored at address <ptr>.
303 */
304#ifndef container_of
305#define container_of(ptr, type, name) ((type *)(((void *)(ptr)) - ((long)&((type *)0)->name)))
306#endif
307
308/*
309 * Gcc >= 3 provides the ability for the program to give hints to the compiler
310 * about what branch of an if is most likely to be taken. This helps the
311 * compiler produce the most compact critical paths, which is generally better
312 * for the cache and to reduce the number of jumps. Be very careful not to use
313 * this in inline functions, because the code reordering it causes very often
314 * has a negative impact on the calling functions.
315 */
316#if !defined(likely)
317#if __GNUC__ < 3
318#define __builtin_expect(x,y) (x)
319#define likely(x) (x)
320#define unlikely(x) (x)
321#elif __GNUC__ < 4
322/* gcc 3.x does the best job at this */
323#define likely(x) (__builtin_expect((x) != 0, 1))
324#define unlikely(x) (__builtin_expect((x) != 0, 0))
325#else
326/* GCC 4.x is stupid, it performs the comparison then compares it to 1,
327 * so we cheat in a dirty way to prevent it from doing this. This will
328 * only work with ints and booleans though.
329 */
330#define likely(x) (x)
331#define unlikely(x) (__builtin_expect((unsigned long)(x), 0))
332#endif
333#endif
334
335/* By default, gcc does not inline large chunks of code, but we want it to
336 * respect our choices.
337 */
338#if !defined(forceinline)
339#if __GNUC__ < 3
340#define forceinline inline
341#else
342#define forceinline inline __attribute__((always_inline))
343#endif
344#endif
345
346/* Support passing function parameters in registers. For this, the
347 * CONFIG_EBTREE_REGPARM macro has to be set to the maximal number of registers
348 * allowed. Some functions have intentionally received a regparm lower than
349 * their parameter count, it is in order to avoid register clobbering where
350 * they are called.
351 */
352#ifndef REGPRM1
353#if CONFIG_EBTREE_REGPARM >= 1
354#define REGPRM1 __attribute__((regparm(1)))
355#else
356#define REGPRM1
357#endif
358#endif
359
360#ifndef REGPRM2
361#if CONFIG_EBTREE_REGPARM >= 2
362#define REGPRM2 __attribute__((regparm(2)))
363#else
364#define REGPRM2 REGPRM1
365#endif
366#endif
367
368#ifndef REGPRM3
369#if CONFIG_EBTREE_REGPARM >= 3
370#define REGPRM3 __attribute__((regparm(3)))
371#else
372#define REGPRM3 REGPRM2
373#endif
374#endif
375
376/* Number of bits per node, and number of leaves per node */
377#define EB_NODE_BITS 1
378#define EB_NODE_BRANCHES (1 << EB_NODE_BITS)
379#define EB_NODE_BRANCH_MASK (EB_NODE_BRANCHES - 1)
380
381/* Be careful not to tweak those values. The walking code is optimized for NULL
382 * detection on the assumption that the following values are intact.
383 */
384#define EB_LEFT 0
385#define EB_RGHT 1
386#define EB_LEAF 0
387#define EB_NODE 1
388
389/* Tags to set in root->b[EB_RGHT] :
390 * - EB_NORMAL is a normal tree which stores duplicate keys.
391 * - EB_UNIQUE is a tree which stores unique keys.
392 */
393#define EB_NORMAL 0
394#define EB_UNIQUE 1
395
396/* This is the same as an eb_node pointer, except that the lower bit embeds
397 * a tag. See eb_dotag()/eb_untag()/eb_gettag(). This tag has two meanings :
398 * - 0=left, 1=right to designate the parent's branch for leaf_p/node_p
399 * - 0=link, 1=leaf to designate the branch's type for branch[]
400 */
401typedef void eb_troot_t;
402
403/* The eb_root connects the node which contains it, to two nodes below it, one
404 * of which may be the same node. At the top of the tree, we use an eb_root
405 * too, which always has its right branch NULL (+/1 low-order bits).
406 */
407struct eb_root {
408 eb_troot_t *b[EB_NODE_BRANCHES]; /* left and right branches */
409};
410
411/* The eb_node contains the two parts, one for the leaf, which always exists,
412 * and one for the node, which remains unused in the very first node inserted
413 * into the tree. This structure is 20 bytes per node on 32-bit machines. Do
414 * not change the order, benchmarks have shown that it's optimal this way.
415 */
416struct eb_node {
417 struct eb_root branches; /* branches, must be at the beginning */
418 eb_troot_t *node_p; /* link node's parent */
419 eb_troot_t *leaf_p; /* leaf node's parent */
420 int bit; /* link's bit position. */
421};
422
423/* Return the structure of type <type> whose member <member> points to <ptr> */
424#define eb_entry(ptr, type, member) container_of(ptr, type, member)
425
426/* The root of a tree is an eb_root initialized with both pointers NULL.
427 * During its life, only the left pointer will change. The right one will
428 * always remain NULL, which is the way we detect it.
429 */
430#define EB_ROOT \
431 (struct eb_root) { \
432 .b = {[0] = NULL, [1] = NULL }, \
433 }
434
435#define EB_ROOT_UNIQUE \
436 (struct eb_root) { \
437 .b = {[0] = NULL, [1] = (void *)1 }, \
438 }
439
440#define EB_TREE_HEAD(name) \
441 struct eb_root name = EB_ROOT
442
443
444/***************************************\
445 * Private functions. Not for end-user *
446\***************************************/
447
448/* Converts a root pointer to its equivalent eb_troot_t pointer,
449 * ready to be stored in ->branch[], leaf_p or node_p. NULL is not
450 * conserved. To be used with EB_LEAF, EB_NODE, EB_LEFT or EB_RGHT in <tag>.
451 */
452static inline eb_troot_t *eb_dotag(const struct eb_root *root, const int tag)
453{
454 return (eb_troot_t *)((void *)root + tag);
455}
456
457/* Converts an eb_troot_t pointer pointer to its equivalent eb_root pointer,
458 * for use with pointers from ->branch[], leaf_p or node_p. NULL is conserved
459 * as long as the tree is not corrupted. To be used with EB_LEAF, EB_NODE,
460 * EB_LEFT or EB_RGHT in <tag>.
461 */
462static inline struct eb_root *eb_untag(const eb_troot_t *troot, const int tag)
463{
464 return (struct eb_root *)((void *)troot - tag);
465}
466
467/* returns the tag associated with an eb_troot_t pointer */
468static inline int eb_gettag(eb_troot_t *troot)
469{
470 return (unsigned long)troot & 1;
471}
472
473/* Converts a root pointer to its equivalent eb_troot_t pointer and clears the
474 * tag, no matter what its value was.
475 */
476static inline struct eb_root *eb_clrtag(const eb_troot_t *troot)
477{
478 return (struct eb_root *)((unsigned long)troot & ~1UL);
479}
480
481/* Returns a pointer to the eb_node holding <root> */
482static inline struct eb_node *eb_root_to_node(struct eb_root *root)
483{
484 return container_of(root, struct eb_node, branches);
485}
486
487/* Walks down starting at root pointer <start>, and always walking on side
488 * <side>. It either returns the node hosting the first leaf on that side,
489 * or NULL if no leaf is found. <start> may either be NULL or a branch pointer.
490 * The pointer to the leaf (or NULL) is returned.
491 */
492static inline struct eb_node *eb_walk_down(eb_troot_t *start, unsigned int side)
493{
494 /* A NULL pointer on an empty tree root will be returned as-is */
495 while (eb_gettag(start) == EB_NODE)
496 start = (eb_untag(start, EB_NODE))->b[side];
497 /* NULL is left untouched (root==eb_node, EB_LEAF==0) */
498 return eb_root_to_node(eb_untag(start, EB_LEAF));
499}
500
501/* This function is used to build a tree of duplicates by adding a new node to
502 * a subtree of at least 2 entries. It will probably never be needed inlined,
503 * and it is not for end-user.
504 */
505static forceinline struct eb_node *
506__eb_insert_dup(struct eb_node *sub, struct eb_node *new)
507{
508 struct eb_node *head = sub;
509
510 struct eb_troot *new_left = eb_dotag(&new->branches, EB_LEFT);
511 struct eb_troot *new_rght = eb_dotag(&new->branches, EB_RGHT);
512 struct eb_troot *new_leaf = eb_dotag(&new->branches, EB_LEAF);
513
514 /* first, identify the deepest hole on the right branch */
515 while (eb_gettag(head->branches.b[EB_RGHT]) != EB_LEAF) {
516 struct eb_node *last = head;
517 head = container_of(eb_untag(head->branches.b[EB_RGHT], EB_NODE),
518 struct eb_node, branches);
519 if (head->bit > last->bit + 1)
520 sub = head; /* there's a hole here */
521 }
522
523 /* Here we have a leaf attached to (head)->b[EB_RGHT] */
524 if (head->bit < -1) {
525 /* A hole exists just before the leaf, we insert there */
526 new->bit = -1;
527 sub = container_of(eb_untag(head->branches.b[EB_RGHT], EB_LEAF),
528 struct eb_node, branches);
529 head->branches.b[EB_RGHT] = eb_dotag(&new->branches, EB_NODE);
530
531 new->node_p = sub->leaf_p;
532 new->leaf_p = new_rght;
533 sub->leaf_p = new_left;
534 new->branches.b[EB_LEFT] = eb_dotag(&sub->branches, EB_LEAF);
535 new->branches.b[EB_RGHT] = new_leaf;
536 return new;
537 } else {
538 int side;
539 /* No hole was found before a leaf. We have to insert above
540 * <sub>. Note that we cannot be certain that <sub> is attached
541 * to the right of its parent, as this is only true if <sub>
542 * is inside the dup tree, not at the head.
543 */
544 new->bit = sub->bit - 1; /* install at the lowest level */
545 side = eb_gettag(sub->node_p);
546 head = container_of(eb_untag(sub->node_p, side), struct eb_node, branches);
547 head->branches.b[side] = eb_dotag(&new->branches, EB_NODE);
548
549 new->node_p = sub->node_p;
550 new->leaf_p = new_rght;
551 sub->node_p = new_left;
552 new->branches.b[EB_LEFT] = eb_dotag(&sub->branches, EB_NODE);
553 new->branches.b[EB_RGHT] = new_leaf;
554 return new;
555 }
556}
557
558
559/**************************************\
560 * Public functions, for the end-user *
561\**************************************/
562
563/* Return the first leaf in the tree starting at <root>, or NULL if none */
564static inline struct eb_node *eb_first(struct eb_root *root)
565{
566 return eb_walk_down(root->b[0], EB_LEFT);
567}
568
569/* Return the last leaf in the tree starting at <root>, or NULL if none */
570static inline struct eb_node *eb_last(struct eb_root *root)
571{
572 return eb_walk_down(root->b[0], EB_RGHT);
573}
574
575/* Return previous leaf node before an existing leaf node, or NULL if none. */
576static inline struct eb_node *eb_prev(struct eb_node *node)
577{
578 eb_troot_t *t = node->leaf_p;
579
580 while (eb_gettag(t) == EB_LEFT) {
581 /* Walking up from left branch. We must ensure that we never
582 * walk beyond root.
583 */
584 if (unlikely(eb_clrtag((eb_untag(t, EB_LEFT))->b[EB_RGHT]) == NULL))
585 return NULL;
586 t = (eb_root_to_node(eb_untag(t, EB_LEFT)))->node_p;
587 }
588 /* Note that <t> cannot be NULL at this stage */
589 t = (eb_untag(t, EB_RGHT))->b[EB_LEFT];
590 return eb_walk_down(t, EB_RGHT);
591}
592
593/* Return next leaf node after an existing leaf node, or NULL if none. */
594static inline struct eb_node *eb_next(struct eb_node *node)
595{
596 eb_troot_t *t = node->leaf_p;
597
598 while (eb_gettag(t) != EB_LEFT)
599 /* Walking up from right branch, so we cannot be below root */
600 t = (eb_root_to_node(eb_untag(t, EB_RGHT)))->node_p;
601
602 /* Note that <t> cannot be NULL at this stage */
603 t = (eb_untag(t, EB_LEFT))->b[EB_RGHT];
604 if (eb_clrtag(t) == NULL)
605 return NULL;
606 return eb_walk_down(t, EB_LEFT);
607}
608
609/* Return previous leaf node before an existing leaf node, skipping duplicates,
610 * or NULL if none. */
611static inline struct eb_node *eb_prev_unique(struct eb_node *node)
612{
613 eb_troot_t *t = node->leaf_p;
614
615 while (1) {
616 if (eb_gettag(t) != EB_LEFT) {
617 node = eb_root_to_node(eb_untag(t, EB_RGHT));
618 /* if we're right and not in duplicates, stop here */
619 if (node->bit >= 0)
620 break;
621 t = node->node_p;
622 }
623 else {
624 /* Walking up from left branch. We must ensure that we never
625 * walk beyond root.
626 */
627 if (unlikely(eb_clrtag((eb_untag(t, EB_LEFT))->b[EB_RGHT]) == NULL))
628 return NULL;
629 t = (eb_root_to_node(eb_untag(t, EB_LEFT)))->node_p;
630 }
631 }
632 /* Note that <t> cannot be NULL at this stage */
633 t = (eb_untag(t, EB_RGHT))->b[EB_LEFT];
634 return eb_walk_down(t, EB_RGHT);
635}
636
637/* Return next leaf node after an existing leaf node, skipping duplicates, or
638 * NULL if none.
639 */
640static inline struct eb_node *eb_next_unique(struct eb_node *node)
641{
642 eb_troot_t *t = node->leaf_p;
643
644 while (1) {
645 if (eb_gettag(t) == EB_LEFT) {
646 if (unlikely(eb_clrtag((eb_untag(t, EB_LEFT))->b[EB_RGHT]) == NULL))
647 return NULL; /* we reached root */
648 node = eb_root_to_node(eb_untag(t, EB_LEFT));
649 /* if we're left and not in duplicates, stop here */
650 if (node->bit >= 0)
651 break;
652 t = node->node_p;
653 }
654 else {
655 /* Walking up from right branch, so we cannot be below root */
656 t = (eb_root_to_node(eb_untag(t, EB_RGHT)))->node_p;
657 }
658 }
659
660 /* Note that <t> cannot be NULL at this stage */
661 t = (eb_untag(t, EB_LEFT))->b[EB_RGHT];
662 if (eb_clrtag(t) == NULL)
663 return NULL;
664 return eb_walk_down(t, EB_LEFT);
665}
666
667
668/* Removes a leaf node from the tree if it was still in it. Marks the node
669 * as unlinked.
670 */
671static forceinline void __eb_delete(struct eb_node *node)
672{
673 __label__ delete_unlink;
674 unsigned int pside, gpside, sibtype;
675 struct eb_node *parent;
676 struct eb_root *gparent;
677
678 if (!node->leaf_p)
679 return;
680
681 /* we need the parent, our side, and the grand parent */
682 pside = eb_gettag(node->leaf_p);
683 parent = eb_root_to_node(eb_untag(node->leaf_p, pside));
684
685 /* We likely have to release the parent link, unless it's the root,
686 * in which case we only set our branch to NULL. Note that we can
687 * only be attached to the root by its left branch.
688 */
689
690 if (eb_clrtag(parent->branches.b[EB_RGHT]) == NULL) {
691 /* we're just below the root, it's trivial. */
692 parent->branches.b[EB_LEFT] = NULL;
693 goto delete_unlink;
694 }
695
696 /* To release our parent, we have to identify our sibling, and reparent
697 * it directly to/from the grand parent. Note that the sibling can
698 * either be a link or a leaf.
699 */
700
701 gpside = eb_gettag(parent->node_p);
702 gparent = eb_untag(parent->node_p, gpside);
703
704 gparent->b[gpside] = parent->branches.b[!pside];
705 sibtype = eb_gettag(gparent->b[gpside]);
706
707 if (sibtype == EB_LEAF) {
708 eb_root_to_node(eb_untag(gparent->b[gpside], EB_LEAF))->leaf_p =
709 eb_dotag(gparent, gpside);
710 } else {
711 eb_root_to_node(eb_untag(gparent->b[gpside], EB_NODE))->node_p =
712 eb_dotag(gparent, gpside);
713 }
714 /* Mark the parent unused. Note that we do not check if the parent is
715 * our own node, but that's not a problem because if it is, it will be
716 * marked unused at the same time, which we'll use below to know we can
717 * safely remove it.
718 */
719 parent->node_p = NULL;
720
721 /* The parent node has been detached, and is currently unused. It may
722 * belong to another node, so we cannot remove it that way. Also, our
723 * own node part might still be used. so we can use this spare node
724 * to replace ours if needed.
725 */
726
727 /* If our link part is unused, we can safely exit now */
728 if (!node->node_p)
729 goto delete_unlink;
730
731 /* From now on, <node> and <parent> are necessarily different, and the
732 * <node>'s node part is in use. By definition, <parent> is at least
733 * below <node>, so keeping its key for the bit string is OK.
734 */
735
736 parent->node_p = node->node_p;
737 parent->branches = node->branches;
738 parent->bit = node->bit;
739
740 /* We must now update the new node's parent... */
741 gpside = eb_gettag(parent->node_p);
742 gparent = eb_untag(parent->node_p, gpside);
743 gparent->b[gpside] = eb_dotag(&parent->branches, EB_NODE);
744
745 /* ... and its branches */
746 for (pside = 0; pside <= 1; pside++) {
747 if (eb_gettag(parent->branches.b[pside]) == EB_NODE) {
748 eb_root_to_node(eb_untag(parent->branches.b[pside], EB_NODE))->node_p =
749 eb_dotag(&parent->branches, pside);
750 } else {
751 eb_root_to_node(eb_untag(parent->branches.b[pside], EB_LEAF))->leaf_p =
752 eb_dotag(&parent->branches, pside);
753 }
754 }
755 delete_unlink:
756 /* Now the node has been completely unlinked */
757 node->leaf_p = NULL;
758 return; /* tree is not empty yet */
759}
760
761/* Compare blocks <a> and <b> byte-to-byte, from bit <ignore> to bit <len-1>.
762 * Return the number of equal bits between strings, assuming that the first
763 * <ignore> bits are already identical. It is possible to return slightly more
764 * than <len> bits if <len> does not stop on a byte boundary and we find exact
765 * bytes. Note that parts or all of <ignore> bits may be rechecked. It is only
766 * passed here as a hint to speed up the check.
767 */
768static forceinline unsigned int equal_bits(const unsigned char *a,
769 const unsigned char *b,
770 unsigned int ignore, unsigned int len)
771{
772 unsigned int beg;
773 unsigned int end;
774 unsigned int ret;
775 unsigned char c;
776
777 beg = ignore >> 3;
778 end = (len + 7) >> 3;
779 ret = end << 3;
780
781 do {
782 if (beg >= end)
783 goto out;
784 beg++;
785 c = a[beg-1] ^ b[beg-1];
786 } while (!c);
787
788 /* OK now we know that a and b differ at byte <beg> and that <c> holds
789 * the bit differences. We have to find what bit is differing and report
790 * it as the number of identical bits. Note that low bit numbers are
791 * assigned to high positions in the byte, as we compare them as strings.
792 */
793 ret = beg << 3;
794 if (c & 0xf0) { c >>= 4; ret -= 4; }
795 if (c & 0x0c) { c >>= 2; ret -= 2; }
796 ret -= (c >> 1);
797 ret--;
798 out:
799 return ret;
800}
801
802/* Compare strings <a> and <b> byte-to-byte, from bit <ignore> to the last 0.
803 * Return the number of equal bits between strings, assuming that the first
804 * <ignore> bits are already identical. Note that parts or all of <ignore> bits
805 * may be rechecked. It is only passed here as a hint to speed up the check.
806 * The caller is responsible for not passing an <ignore> value larger than any
807 * of the two strings. However, referencing any bit from the trailing zero is
808 * permitted.
809 */
810static forceinline unsigned int string_equal_bits(const unsigned char *a,
811 const unsigned char *b,
812 unsigned int ignore)
813{
814 unsigned int beg;
815 unsigned char c;
816
817 beg = ignore >> 3;
818
819 /* skip known and identical bits. We stop at the first different byte
820 * or at the first zero we encounter on either side.
821 */
822 while (1) {
823 unsigned char d;
824
825 c = a[beg];
826 d = b[beg];
827 beg++;
828
829 c ^= d;
830 if (c)
831 break;
832 if (!d)
833 break;
834 }
835
836 /* OK now we know that a and b differ at byte <beg>, or that both are zero.
837 * We have to find what bit is differing and report it as the number of
838 * identical bits. Note that low bit numbers are assigned to high positions
839 * in the byte, as we compare them as strings.
840 */
841 beg <<= 3;
842 if (c & 0xf0) { c >>= 4; beg -= 4; }
843 if (c & 0x0c) { c >>= 2; beg -= 2; }
844 beg -= (c >> 1);
845 if (c)
846 beg--;
847
848 return beg;
849}
850
851static forceinline int cmp_bits(const unsigned char *a, const unsigned char *b, unsigned int pos)
852{
853 unsigned int ofs;
854 unsigned char bit_a, bit_b;
855
856 ofs = pos >> 3;
857 pos = ~pos & 7;
858
859 bit_a = (a[ofs] >> pos) & 1;
860 bit_b = (b[ofs] >> pos) & 1;
861
862 return bit_a - bit_b; /* -1: a<b; 0: a=b; 1: a>b */
863}
864
865static forceinline int get_bit(const unsigned char *a, unsigned int pos)
866{
867 unsigned int ofs;
868
869 ofs = pos >> 3;
870 pos = ~pos & 7;
871 return (a[ofs] >> pos) & 1;
872}
873
874/* These functions are declared in ebtree.c */
875void eb_delete(struct eb_node *node);
876REGPRM1 struct eb_node *eb_insert_dup(struct eb_node *sub, struct eb_node *new);
877
878#endif /* _EB_TREE_H */
879
880/*
881 * Local variables:
882 * c-indent-level: 8
883 * c-basic-offset: 8
884 * End:
885 */