2 * Copyright (c) 1988, 1989, 1993
3 * The Regents of the University of California. All rights reserved.
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution.
13 * 4. Neither the name of the University nor the names of its contributors
14 * may be used to endorse or promote products derived from this software
15 * without specific prior written permission.
17 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
18 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
21 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29 * @(#)radix.c 8.4 (Berkeley) 11/2/94
35 * Routines to build and maintain radix trees for routing lookups.
42 #elif defined(__FreeBSD__)
45 __RCSID("$Revision: 2.23 $");
46 #ident "$Revision: 2.23 $"
49 #define log(x, msg) syslog(x, msg)
50 #define panic(s) {log(LOG_ERR,s); exit(1);}
51 #define min(a,b) (((a)<(b))?(a):(b))
54 static struct radix_mask *rn_mkfreelist;
55 static struct radix_node_head *mask_rnhead;
56 static char *addmask_key;
57 static const uint8_t normal_chars[] =
58 { 0, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe, 0xff};
59 static char *rn_zeros, *rn_ones;
61 #define rn_masktop (mask_rnhead->rnh_treetop)
62 #define Bcmp(a, b, l) (l == 0 ? 0 \
63 : memcmp((caddr_t)(a), (caddr_t)(b), (size_t)l))
65 static int rn_satisfies_leaf(char *, struct radix_node *, int);
66 static struct radix_node *rn_addmask(void *n_arg, int search, int skip);
67 static struct radix_node *rn_addroute(void *v_arg, void *n_arg,
68 struct radix_node_head *head, struct radix_node treenodes[2]);
69 static struct radix_node *rn_match(void *v_arg, struct radix_node_head *head);
72 * The data structure for the keys is a radix tree with one way
73 * branching removed. The index rn_b at an internal node n represents a bit
74 * position to be tested. The tree is arranged so that all descendants
75 * of a node n have keys whose bits all agree up to position rn_b - 1.
76 * (We say the index of n is rn_b.)
78 * There is at least one descendant which has a one bit at position rn_b,
79 * and at least one with a zero there.
81 * A route is determined by a pair of key and mask. We require that the
82 * bit-wise logical and of the key and mask to be the key.
83 * We define the index of a route to associated with the mask to be
84 * the first bit number in the mask where 0 occurs (with bit number 0
85 * representing the highest order bit).
87 * We say a mask is normal if every bit is 0, past the index of the mask.
88 * If a node n has a descendant (k, m) with index(m) == index(n) == rn_b,
89 * and m is a normal mask, then the route applies to every descendant of n.
90 * If the index(m) < rn_b, this implies the trailing last few bits of k
91 * before bit b are all 0, (and hence consequently true of every descendant
92 * of n), so the route applies to all descendants of the node as well.
94 * Similar logic shows that a non-normal mask m such that
95 * index(m) <= index(n) could potentially apply to many children of n.
96 * Thus, for each non-host route, we attach its mask to a list at an internal
97 * node as high in the tree as we can go.
99 * The present version of the code makes use of normal routes in short-
100 * circuiting an explicit mask and compare operation when testing whether
101 * a key satisfies a normal route, and also in remembering the unique leaf
102 * that governs a subtree.
105 static struct radix_node *
106 rn_search(void *v_arg,
107 struct radix_node *head)
109 struct radix_node *x;
112 for (x = head, v = v_arg; x->rn_b >= 0;) {
113 if (x->rn_bmask & v[x->rn_off])
121 static struct radix_node *
122 rn_search_m(void *v_arg,
123 struct radix_node *head,
126 struct radix_node *x;
127 caddr_t v = v_arg, m = m_arg;
129 for (x = head; x->rn_b >= 0;) {
130 if ((x->rn_bmask & m[x->rn_off]) &&
131 (x->rn_bmask & v[x->rn_off]))
140 rn_refines(void* m_arg, void *n_arg)
142 caddr_t m = m_arg, n = n_arg;
143 caddr_t lim, lim2 = lim = n + *(u_char *)n;
144 int longer = (*(u_char *)n++) - (int)(*(u_char *)m++);
145 int masks_are_equal = 1;
158 if (masks_are_equal && (longer < 0))
159 for (lim2 = m - longer; m < lim2; )
162 return (!masks_are_equal);
165 static struct radix_node *
166 rn_lookup(void *v_arg, void *m_arg, struct radix_node_head *head)
168 struct radix_node *x;
172 if ((x = rn_addmask(m_arg, 1,
173 head->rnh_treetop->rn_off)) == NULL)
177 x = rn_match(v_arg, head);
179 while (x && x->rn_mask != netmask)
186 rn_satisfies_leaf(char *trial,
187 struct radix_node *leaf,
190 char *cp = trial, *cp2 = leaf->rn_key, *cp3 = leaf->rn_mask;
192 int length = min(*(u_char *)cp, *(u_char *)cp2);
197 length = min(length, *(u_char *)cp3);
198 cplim = cp + length; cp3 += skip; cp2 += skip;
199 for (cp += skip; cp < cplim; cp++, cp2++, cp3++)
200 if ((*cp ^ *cp2) & *cp3)
205 static struct radix_node *
206 rn_match(void *v_arg,
207 struct radix_node_head *head)
210 struct radix_node *t = head->rnh_treetop, *x;
213 struct radix_node *saved_t, *top = t;
214 int off = t->rn_off, vlen = *(u_char *)cp, matched_off;
218 * Open code rn_search(v, top) to avoid overhead of extra
221 for (; t->rn_b >= 0; ) {
222 if (t->rn_bmask & cp[t->rn_off])
228 * See if we match exactly as a host destination
229 * or at least learn how many bits match, for normal mask finesse.
231 * It doesn't hurt us to limit how many bytes to check
232 * to the length of the mask, since if it matches we had a genuine
233 * match and the leaf we have is the most specific one anyway;
234 * if it didn't match with a shorter length it would fail
235 * with a long one. This wins big for class B&C netmasks which
236 * are probably the most common case...
239 vlen = *(u_char *)t->rn_mask;
240 cp += off; cp2 = t->rn_key + off; cplim = v + vlen;
241 for (; cp < cplim; cp++, cp2++)
245 * This extra grot is in case we are explicitly asked
246 * to look up the default. Ugh!
249 * In this case, we have a complete match of the key. Unless
250 * the node is one of the roots, we are finished.
251 * If it is the zeros root, then take what we have, preferring
253 * If it is the ones root, then pretend the target key was followed
254 * by a byte of zeros.
256 if (!(t->rn_flags & RNF_ROOT))
257 return t; /* not a root */
258 if (t->rn_dupedkey) {
260 return t; /* have some real data */
263 return t; /* not the ones root */
264 b = 0; /* fake a zero after 255.255.255.255 */
267 test = (*cp ^ *cp2) & 0xff; /* find first bit that differs */
268 for (b = 7; (test >>= 1) > 0;)
271 matched_off = cp - v;
272 b += matched_off << 3;
275 * If there is a host route in a duped-key chain, it will be first.
277 if ((saved_t = t)->rn_mask == 0)
279 for (; t; t = t->rn_dupedkey) {
281 * Even if we don't match exactly as a host,
282 * we may match if the leaf we wound up at is
285 if (t->rn_flags & RNF_NORMAL) {
288 } else if (rn_satisfies_leaf(v, t, matched_off)) {
293 /* start searching up the tree */
295 struct radix_mask *m;
297 if ((m = t->rn_mklist)) {
299 * If non-contiguous masks ever become important
300 * we can restore the masking and open coding of
301 * the search and satisfaction test and put the
302 * calculation of "off" back before the "do".
305 if (m->rm_flags & RNF_NORMAL) {
309 off = min(t->rn_off, matched_off);
310 x = rn_search_m(v, t, m->rm_mask);
311 while (x && x->rn_mask != m->rm_mask)
313 if (x && rn_satisfies_leaf(v, x, off))
316 } while ((m = m->rm_mklist));
324 struct radix_node *rn_clist;
329 static struct radix_node *
330 rn_newpair(void *v, int b, struct radix_node nodes[2])
332 struct radix_node *tt = nodes, *t = tt + 1;
333 t->rn_b = b; t->rn_bmask = 0x80 >> (b & 7);
334 t->rn_l = tt; t->rn_off = b >> 3;
335 tt->rn_b = -1; tt->rn_key = (caddr_t)v; tt->rn_p = t;
336 tt->rn_flags = t->rn_flags = RNF_ACTIVE;
338 tt->rn_info = rn_nodenum++; t->rn_info = rn_nodenum++;
339 tt->rn_twin = t; tt->rn_ybro = rn_clist; rn_clist = tt;
344 static struct radix_node *
345 rn_insert(void* v_arg,
346 struct radix_node_head *head,
348 struct radix_node nodes[2])
351 struct radix_node *top = head->rnh_treetop;
352 int head_off = top->rn_off, vlen = (int)*((u_char *)v);
353 struct radix_node *t = rn_search(v_arg, top);
354 caddr_t cp = v + head_off;
356 struct radix_node *tt;
359 * Find first bit at which v and t->rn_key differ
362 caddr_t cp2 = t->rn_key + head_off;
364 caddr_t cplim = v + vlen;
369 /* handle adding 255.255.255.255 */
370 if (!(t->rn_flags & RNF_ROOT) || *(cp2-1) == 0) {
376 cmp_res = (cp[-1] ^ cp2[-1]) & 0xff;
377 for (b = (cp - v) << 3; cmp_res; b--)
381 struct radix_node *p, *x = top;
385 if (cp[x->rn_off] & x->rn_bmask)
388 } while ((unsigned)b > (unsigned)x->rn_b);
391 log(LOG_DEBUG, "rn_insert: Going In:\n"), traverse(p);
393 t = rn_newpair(v_arg, b, nodes); tt = t->rn_l;
394 if ((cp[p->rn_off] & p->rn_bmask) == 0)
398 x->rn_p = t; t->rn_p = p; /* frees x, p as temp vars below */
399 if ((cp[t->rn_off] & t->rn_bmask) == 0) {
402 t->rn_r = tt; t->rn_l = x;
406 log(LOG_DEBUG, "rn_insert: Coming Out:\n"), traverse(p);
412 static struct radix_node *
413 rn_addmask(void *n_arg, int search, int skip)
415 caddr_t netmask = (caddr_t)n_arg;
416 struct radix_node *x;
419 int maskduplicated, m0, isnormal;
420 struct radix_node *saved_x;
421 static int last_zeroed = 0;
423 if ((mlen = *(u_char *)netmask) > max_keylen)
428 return (mask_rnhead->rnh_nodes);
430 Bcopy(rn_ones + 1, addmask_key + 1, skip - 1);
431 if ((m0 = mlen) > skip)
432 Bcopy(netmask + skip, addmask_key + skip, mlen - skip);
434 * Trim trailing zeroes.
436 for (cp = addmask_key + mlen; (cp > addmask_key) && cp[-1] == 0;)
438 mlen = cp - addmask_key;
440 if (m0 >= last_zeroed)
442 return (mask_rnhead->rnh_nodes);
444 if (m0 < last_zeroed)
445 Bzero(addmask_key + m0, last_zeroed - m0);
446 *addmask_key = last_zeroed = mlen;
447 x = rn_search(addmask_key, rn_masktop);
448 if (Bcmp(addmask_key, x->rn_key, mlen) != 0)
452 x = (struct radix_node *)rtmalloc(max_keylen + 2*sizeof(*x),
455 Bzero(x, max_keylen + 2 * sizeof (*x));
456 netmask = cp = (caddr_t)(x + 2);
457 Bcopy(addmask_key, cp, mlen);
458 x = rn_insert(cp, mask_rnhead, &maskduplicated, x);
459 if (maskduplicated) {
460 log(LOG_ERR, "rn_addmask: mask impossibly already in tree");
465 * Calculate index of mask, and check for normalcy.
467 cplim = netmask + mlen; isnormal = 1;
468 for (cp = netmask + skip; (cp < cplim) && *(u_char *)cp == 0xff;)
471 for (j = 0x80; (j & *cp) != 0; j >>= 1)
473 if (*cp != normal_chars[b] || cp != (cplim - 1))
476 b += (cp - netmask) << 3;
479 x->rn_flags |= RNF_NORMAL;
483 static int /* XXX: arbitrary ordering for non-contiguous masks */
484 rn_lexobetter(void *m_arg, void *n_arg)
486 u_char *mp = m_arg, *np = n_arg, *lim;
489 return 1; /* not really, but need to check longer one first */
491 for (lim = mp + *mp; mp < lim;)
497 static struct radix_mask *
498 rn_new_radix_mask(struct radix_node *tt,
499 struct radix_mask *next)
501 struct radix_mask *m;
505 log(LOG_ERR, "Mask for route not entered\n");
510 m->rm_flags = tt->rn_flags;
511 if (tt->rn_flags & RNF_NORMAL)
514 m->rm_mask = tt->rn_mask;
520 static struct radix_node *
521 rn_addroute(void *v_arg,
523 struct radix_node_head *head,
524 struct radix_node treenodes[2])
526 caddr_t v = (caddr_t)v_arg, netmask = (caddr_t)n_arg;
527 struct radix_node *t, *x = NULL, *tt;
528 struct radix_node *saved_tt, *top = head->rnh_treetop;
529 short b = 0, b_leaf = 0;
532 struct radix_mask *m, **mp;
535 * In dealing with non-contiguous masks, there may be
536 * many different routes which have the same mask.
537 * We will find it useful to have a unique pointer to
538 * the mask to speed avoiding duplicate references at
539 * nodes and possibly save time in calculating indices.
542 if ((x = rn_addmask(netmask, 0, top->rn_off)) == NULL)
549 * Deal with duplicated keys: attach node to previous instance
551 saved_tt = tt = rn_insert(v, head, &keyduplicated, treenodes);
553 for (t = tt; tt; t = tt, tt = tt->rn_dupedkey) {
554 if (tt->rn_mask == netmask)
558 ((b_leaf < tt->rn_b) || /* index(netmask) > node */
559 rn_refines(netmask, tt->rn_mask) ||
560 rn_lexobetter(netmask, tt->rn_mask))))
564 * If the mask is not duplicated, we wouldn't
565 * find it among possible duplicate key entries
566 * anyway, so the above test doesn't hurt.
568 * We sort the masks for a duplicated key the same way as
569 * in a masklist -- most specific to least specific.
570 * This may require the unfortunate nuisance of relocating
571 * the head of the list.
573 if (tt == saved_tt) {
574 struct radix_node *xx = x;
575 /* link in at head of list */
576 (tt = treenodes)->rn_dupedkey = t;
577 tt->rn_flags = t->rn_flags;
578 tt->rn_p = x = t->rn_p;
579 if (x->rn_l == t) x->rn_l = tt; else x->rn_r = tt;
580 saved_tt = tt; x = xx;
582 (tt = treenodes)->rn_dupedkey = t->rn_dupedkey;
586 t=tt+1; tt->rn_info = rn_nodenum++; t->rn_info = rn_nodenum++;
587 tt->rn_twin = t; tt->rn_ybro = rn_clist; rn_clist = tt;
589 tt->rn_key = (caddr_t) v;
591 tt->rn_flags = RNF_ACTIVE;
597 tt->rn_mask = netmask;
599 tt->rn_flags |= x->rn_flags & RNF_NORMAL;
604 b_leaf = -1 - t->rn_b;
605 if (t->rn_r == saved_tt) x = t->rn_l; else x = t->rn_r;
606 /* Promote general routes from below */
608 for (mp = &t->rn_mklist; x; x = x->rn_dupedkey)
609 if (x->rn_mask && (x->rn_b >= b_leaf) && x->rn_mklist == 0) {
610 if ((*mp = m = rn_new_radix_mask(x, 0)))
613 } else if (x->rn_mklist) {
615 * Skip over masks whose index is > that of new node
617 for (mp = &x->rn_mklist; (m = *mp); mp = &m->rm_mklist)
618 if (m->rm_b >= b_leaf)
620 t->rn_mklist = m; *mp = NULL;
623 /* Add new route to highest possible ancestor's list */
624 if ((netmask == 0) || (b > t->rn_b ))
625 return tt; /* can't lift at all */
630 } while (b <= t->rn_b && x != top);
632 * Search through routes associated with node to
633 * insert new route according to index.
634 * Need same criteria as when sorting dupedkeys to avoid
635 * double loop on deletion.
637 for (mp = &x->rn_mklist; (m = *mp); mp = &m->rm_mklist) {
638 if (m->rm_b < b_leaf)
640 if (m->rm_b > b_leaf)
642 if (m->rm_flags & RNF_NORMAL) {
643 mmask = m->rm_leaf->rn_mask;
644 if (tt->rn_flags & RNF_NORMAL) {
646 "Non-unique normal route, mask not entered");
651 if (mmask == netmask) {
656 if (rn_refines(netmask, mmask) || rn_lexobetter(netmask, mmask))
659 *mp = rn_new_radix_mask(tt, *mp);
663 static struct radix_node *
664 rn_delete(void *v_arg,
666 struct radix_node_head *head)
668 struct radix_node *t, *p, *x, *tt;
669 struct radix_mask *m, *saved_m, **mp;
670 struct radix_node *dupedkey, *saved_tt, *top;
672 int b, head_off, vlen;
675 netmask = netmask_arg;
676 x = head->rnh_treetop;
677 tt = rn_search(v, x);
678 head_off = x->rn_off;
683 Bcmp(v + head_off, tt->rn_key + head_off, vlen - head_off))
686 * Delete our route from mask lists.
689 if ((x = rn_addmask(netmask, 1, head_off)) == NULL)
692 while (tt->rn_mask != netmask)
693 if ((tt = tt->rn_dupedkey) == NULL)
696 if (tt->rn_mask == 0 || (saved_m = m = tt->rn_mklist) == NULL)
698 if (tt->rn_flags & RNF_NORMAL) {
699 if (m->rm_leaf != tt || m->rm_refs > 0) {
700 log(LOG_ERR, "rn_delete: inconsistent annotation\n");
701 return 0; /* dangling ref could cause disaster */
704 if (m->rm_mask != tt->rn_mask) {
705 log(LOG_ERR, "rn_delete: inconsistent annotation\n");
708 if (--m->rm_refs >= 0)
714 goto on1; /* Wasn't lifted at all */
718 } while (b <= t->rn_b && x != top);
719 for (mp = &x->rn_mklist; (m = *mp); mp = &m->rm_mklist)
726 log(LOG_ERR, "rn_delete: couldn't find our annotation\n");
727 if (tt->rn_flags & RNF_NORMAL)
728 return (0); /* Dangling ref to us */
732 * Eliminate us from tree
734 if (tt->rn_flags & RNF_ROOT)
737 /* Get us out of the creation list */
738 for (t = rn_clist; t && t->rn_ybro != tt; t = t->rn_ybro) {}
739 if (t) t->rn_ybro = tt->rn_ybro;
742 if ((dupedkey = saved_tt->rn_dupedkey)) {
743 if (tt == saved_tt) {
744 x = dupedkey; x->rn_p = t;
745 if (t->rn_l == tt) t->rn_l = x; else t->rn_r = x;
747 for (x = p = saved_tt; p && p->rn_dupedkey != tt;)
749 if (p) p->rn_dupedkey = tt->rn_dupedkey;
750 else log(LOG_ERR, "rn_delete: couldn't find us\n");
753 if (t->rn_flags & RNF_ACTIVE) {
755 *++x = *t; p = t->rn_p;
757 b = t->rn_info; *++x = *t; t->rn_info = b; p = t->rn_p;
759 if (p->rn_l == t) p->rn_l = x; else p->rn_r = x;
760 x->rn_l->rn_p = x; x->rn_r->rn_p = x;
764 if (t->rn_l == tt) x = t->rn_r; else x = t->rn_l;
766 if (p->rn_r == t) p->rn_r = x; else p->rn_l = x;
769 * Demote routes attached to us.
773 for (mp = &x->rn_mklist; (m = *mp);)
777 /* If there are any key,mask pairs in a sibling
778 duped-key chain, some subset will appear sorted
779 in the same order attached to our mklist */
780 for (m = t->rn_mklist; m && x; x = x->rn_dupedkey)
781 if (m == x->rn_mklist) {
782 struct radix_mask *mm = m->rm_mklist;
784 if (--(m->rm_refs) < 0)
789 syslog(LOG_ERR, "%s 0x%lx at 0x%lx\n",
790 "rn_delete: Orphaned Mask",
796 * We may be holding an active internal node in the tree.
803 b = t->rn_info; *t = *x; t->rn_info = b;
805 t->rn_l->rn_p = t; t->rn_r->rn_p = t;
807 if (p->rn_l == x) p->rn_l = t; else p->rn_r = t;
810 tt->rn_flags &= ~RNF_ACTIVE;
811 tt[1].rn_flags &= ~RNF_ACTIVE;
816 rn_walktree(struct radix_node_head *h,
817 int (*f)(struct radix_node *, struct walkarg *),
821 struct radix_node *base, *next;
822 struct radix_node *rn = h->rnh_treetop;
824 * This gets complicated because we may delete the node
825 * while applying the function f to it, so we need to calculate
826 * the successor node in advance.
828 /* First time through node, go left */
829 while (rn->rn_b >= 0)
833 /* If at right child go back up, otherwise, go right */
834 while (rn->rn_p->rn_r == rn && (rn->rn_flags & RNF_ROOT) == 0)
836 /* Find the next *leaf* since next node might vanish, too */
837 for (rn = rn->rn_p->rn_r; rn->rn_b >= 0;)
841 while ((rn = base)) {
842 base = rn->rn_dupedkey;
843 if (!(rn->rn_flags & RNF_ROOT) && (error = (*f)(rn, w)))
847 if (rn->rn_flags & RNF_ROOT)
854 rn_inithead(struct radix_node_head **head, int off)
856 struct radix_node_head *rnh;
857 struct radix_node *t, *tt, *ttt;
860 rnh = (struct radix_node_head *)rtmalloc(sizeof(*rnh), "rn_inithead");
861 Bzero(rnh, sizeof (*rnh));
863 t = rn_newpair(rn_zeros, off, rnh->rnh_nodes);
864 ttt = rnh->rnh_nodes + 2;
868 tt->rn_flags = t->rn_flags = RNF_ROOT | RNF_ACTIVE;
871 ttt->rn_key = rn_ones;
872 rnh->rnh_addaddr = rn_addroute;
873 rnh->rnh_deladdr = rn_delete;
874 rnh->rnh_matchaddr = rn_match;
875 rnh->rnh_lookup = rn_lookup;
876 rnh->rnh_walktree = rn_walktree;
877 rnh->rnh_treetop = t;
885 if (max_keylen == 0) {
886 printf("rn_init: radix functions require max_keylen be set\n");
889 rn_zeros = (char *)rtmalloc(3 * max_keylen, "rn_init");
890 Bzero(rn_zeros, 3 * max_keylen);
891 rn_ones = cp = rn_zeros + max_keylen;
892 addmask_key = cplim = rn_ones + max_keylen;
895 if (rn_inithead(&mask_rnhead, 0) == 0)