Home | History | Annotate | Line # | Download | only in net
radix.c revision 1.39.6.1
      1 /*	$NetBSD: radix.c,v 1.39.6.1 2009/01/19 13:20:12 skrll Exp $	*/
      2 
      3 /*
      4  * Copyright (c) 1988, 1989, 1993
      5  *	The Regents of the University of California.  All rights reserved.
      6  *
      7  * Redistribution and use in source and binary forms, with or without
      8  * modification, are permitted provided that the following conditions
      9  * are met:
     10  * 1. Redistributions of source code must retain the above copyright
     11  *    notice, this list of conditions and the following disclaimer.
     12  * 2. Redistributions in binary form must reproduce the above copyright
     13  *    notice, this list of conditions and the following disclaimer in the
     14  *    documentation and/or other materials provided with the distribution.
     15  * 3. Neither the name of the University nor the names of its contributors
     16  *    may be used to endorse or promote products derived from this software
     17  *    without specific prior written permission.
     18  *
     19  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     29  * SUCH DAMAGE.
     30  *
     31  *	@(#)radix.c	8.6 (Berkeley) 10/17/95
     32  */
     33 
     34 /*
     35  * Routines to build and maintain radix trees for routing lookups.
     36  */
     37 
     38 #include <sys/cdefs.h>
     39 __KERNEL_RCSID(0, "$NetBSD: radix.c,v 1.39.6.1 2009/01/19 13:20:12 skrll Exp $");
     40 
     41 #ifndef _NET_RADIX_H_
     42 #include <sys/param.h>
     43 #ifdef	_KERNEL
     44 #include "opt_inet.h"
     45 
     46 #include <sys/systm.h>
     47 #include <sys/malloc.h>
     48 #define	M_DONTWAIT M_NOWAIT
     49 #include <sys/domain.h>
     50 #else
     51 #include <stdlib.h>
     52 #endif
     53 #include <machine/stdarg.h>
     54 #include <sys/syslog.h>
     55 #include <net/radix.h>
     56 #endif
     57 
     58 typedef void (*rn_printer_t)(void *, const char *fmt, ...);
     59 
     60 int	max_keylen;
     61 struct radix_mask *rn_mkfreelist;
     62 struct radix_node_head *mask_rnhead;
     63 static char *addmask_key;
     64 static const char normal_chars[] =
     65     {0, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe, -1};
     66 static char *rn_zeros, *rn_ones;
     67 
     68 #define rn_masktop (mask_rnhead->rnh_treetop)
     69 
     70 static int rn_satisfies_leaf(const char *, struct radix_node *, int);
     71 static int rn_lexobetter(const void *, const void *);
     72 static struct radix_mask *rn_new_radix_mask(struct radix_node *,
     73     struct radix_mask *);
     74 static struct radix_node *rn_walknext(struct radix_node *, rn_printer_t,
     75     void *);
     76 static struct radix_node *rn_walkfirst(struct radix_node *, rn_printer_t,
     77     void *);
     78 static void rn_nodeprint(struct radix_node *, rn_printer_t, void *,
     79     const char *);
     80 
     81 #define	SUBTREE_OPEN	"[ "
     82 #define	SUBTREE_CLOSE	" ]"
     83 
     84 #ifdef RN_DEBUG
     85 static void rn_treeprint(struct radix_node_head *, rn_printer_t, void *);
     86 #endif /* RN_DEBUG */
     87 
     88 /*
     89  * The data structure for the keys is a radix tree with one way
     90  * branching removed.  The index rn_b at an internal node n represents a bit
     91  * position to be tested.  The tree is arranged so that all descendants
     92  * of a node n have keys whose bits all agree up to position rn_b - 1.
     93  * (We say the index of n is rn_b.)
     94  *
     95  * There is at least one descendant which has a one bit at position rn_b,
     96  * and at least one with a zero there.
     97  *
     98  * A route is determined by a pair of key and mask.  We require that the
     99  * bit-wise logical and of the key and mask to be the key.
    100  * We define the index of a route to associated with the mask to be
    101  * the first bit number in the mask where 0 occurs (with bit number 0
    102  * representing the highest order bit).
    103  *
    104  * We say a mask is normal if every bit is 0, past the index of the mask.
    105  * If a node n has a descendant (k, m) with index(m) == index(n) == rn_b,
    106  * and m is a normal mask, then the route applies to every descendant of n.
    107  * If the index(m) < rn_b, this implies the trailing last few bits of k
    108  * before bit b are all 0, (and hence consequently true of every descendant
    109  * of n), so the route applies to all descendants of the node as well.
    110  *
    111  * Similar logic shows that a non-normal mask m such that
    112  * index(m) <= index(n) could potentially apply to many children of n.
    113  * Thus, for each non-host route, we attach its mask to a list at an internal
    114  * node as high in the tree as we can go.
    115  *
    116  * The present version of the code makes use of normal routes in short-
    117  * circuiting an explicit mask and compare operation when testing whether
    118  * a key satisfies a normal route, and also in remembering the unique leaf
    119  * that governs a subtree.
    120  */
    121 
    122 struct radix_node *
    123 rn_search(
    124 	const void *v_arg,
    125 	struct radix_node *head)
    126 {
    127 	const u_char * const v = v_arg;
    128 	struct radix_node *x;
    129 
    130 	for (x = head; x->rn_b >= 0;) {
    131 		if (x->rn_bmask & v[x->rn_off])
    132 			x = x->rn_r;
    133 		else
    134 			x = x->rn_l;
    135 	}
    136 	return x;
    137 }
    138 
    139 struct radix_node *
    140 rn_search_m(
    141 	const void *v_arg,
    142 	struct radix_node *head,
    143 	const void *m_arg)
    144 {
    145 	struct radix_node *x;
    146 	const u_char * const v = v_arg;
    147 	const u_char * const m = m_arg;
    148 
    149 	for (x = head; x->rn_b >= 0;) {
    150 		if ((x->rn_bmask & m[x->rn_off]) &&
    151 		    (x->rn_bmask & v[x->rn_off]))
    152 			x = x->rn_r;
    153 		else
    154 			x = x->rn_l;
    155 	}
    156 	return x;
    157 }
    158 
    159 int
    160 rn_refines(
    161 	const void *m_arg,
    162 	const void *n_arg)
    163 {
    164 	const char *m = m_arg;
    165 	const char *n = n_arg;
    166 	const char *lim = n + *(const u_char *)n;
    167 	const char *lim2 = lim;
    168 	int longer = (*(const u_char *)n++) - (int)(*(const u_char *)m++);
    169 	int masks_are_equal = 1;
    170 
    171 	if (longer > 0)
    172 		lim -= longer;
    173 	while (n < lim) {
    174 		if (*n & ~(*m))
    175 			return 0;
    176 		if (*n++ != *m++)
    177 			masks_are_equal = 0;
    178 	}
    179 	while (n < lim2)
    180 		if (*n++)
    181 			return 0;
    182 	if (masks_are_equal && (longer < 0))
    183 		for (lim2 = m - longer; m < lim2; )
    184 			if (*m++)
    185 				return 1;
    186 	return !masks_are_equal;
    187 }
    188 
    189 struct radix_node *
    190 rn_lookup(
    191 	const void *v_arg,
    192 	const void *m_arg,
    193 	struct radix_node_head *head)
    194 {
    195 	struct radix_node *x;
    196 	const char *netmask = NULL;
    197 
    198 	if (m_arg) {
    199 		if ((x = rn_addmask(m_arg, 1, head->rnh_treetop->rn_off)) == 0)
    200 			return NULL;
    201 		netmask = x->rn_key;
    202 	}
    203 	x = rn_match(v_arg, head);
    204 	if (x != NULL && netmask != NULL) {
    205 		while (x != NULL && x->rn_mask != netmask)
    206 			x = x->rn_dupedkey;
    207 	}
    208 	return x;
    209 }
    210 
    211 static int
    212 rn_satisfies_leaf(
    213 	const char *trial,
    214 	struct radix_node *leaf,
    215 	int skip)
    216 {
    217 	const char *cp = trial;
    218 	const char *cp2 = leaf->rn_key;
    219 	const char *cp3 = leaf->rn_mask;
    220 	const char *cplim;
    221 	int length = min(*(const u_char *)cp, *(const u_char *)cp2);
    222 
    223 	if (cp3 == 0)
    224 		cp3 = rn_ones;
    225 	else
    226 		length = min(length, *(const u_char *)cp3);
    227 	cplim = cp + length; cp3 += skip; cp2 += skip;
    228 	for (cp += skip; cp < cplim; cp++, cp2++, cp3++)
    229 		if ((*cp ^ *cp2) & *cp3)
    230 			return 0;
    231 	return 1;
    232 }
    233 
    234 struct radix_node *
    235 rn_match(
    236 	const void *v_arg,
    237 	struct radix_node_head *head)
    238 {
    239 	const char * const v = v_arg;
    240 	struct radix_node *t = head->rnh_treetop;
    241 	struct radix_node *top = t;
    242 	struct radix_node *x;
    243 	struct radix_node *saved_t;
    244 	const char *cp = v;
    245 	const char *cp2;
    246 	const char *cplim;
    247 	int off = t->rn_off;
    248 	int vlen = *(const u_char *)cp;
    249 	int matched_off;
    250 	int test, b, rn_b;
    251 
    252 	/*
    253 	 * Open code rn_search(v, top) to avoid overhead of extra
    254 	 * subroutine call.
    255 	 */
    256 	for (; t->rn_b >= 0; ) {
    257 		if (t->rn_bmask & cp[t->rn_off])
    258 			t = t->rn_r;
    259 		else
    260 			t = t->rn_l;
    261 	}
    262 	/*
    263 	 * See if we match exactly as a host destination
    264 	 * or at least learn how many bits match, for normal mask finesse.
    265 	 *
    266 	 * It doesn't hurt us to limit how many bytes to check
    267 	 * to the length of the mask, since if it matches we had a genuine
    268 	 * match and the leaf we have is the most specific one anyway;
    269 	 * if it didn't match with a shorter length it would fail
    270 	 * with a long one.  This wins big for class B&C netmasks which
    271 	 * are probably the most common case...
    272 	 */
    273 	if (t->rn_mask)
    274 		vlen = *(const u_char *)t->rn_mask;
    275 	cp += off; cp2 = t->rn_key + off; cplim = v + vlen;
    276 	for (; cp < cplim; cp++, cp2++)
    277 		if (*cp != *cp2)
    278 			goto on1;
    279 	/*
    280 	 * This extra grot is in case we are explicitly asked
    281 	 * to look up the default.  Ugh!
    282 	 */
    283 	if ((t->rn_flags & RNF_ROOT) && t->rn_dupedkey)
    284 		t = t->rn_dupedkey;
    285 	return t;
    286 on1:
    287 	test = (*cp ^ *cp2) & 0xff; /* find first bit that differs */
    288 	for (b = 7; (test >>= 1) > 0;)
    289 		b--;
    290 	matched_off = cp - v;
    291 	b += matched_off << 3;
    292 	rn_b = -1 - b;
    293 	/*
    294 	 * If there is a host route in a duped-key chain, it will be first.
    295 	 */
    296 	if ((saved_t = t)->rn_mask == 0)
    297 		t = t->rn_dupedkey;
    298 	for (; t; t = t->rn_dupedkey)
    299 		/*
    300 		 * Even if we don't match exactly as a host,
    301 		 * we may match if the leaf we wound up at is
    302 		 * a route to a net.
    303 		 */
    304 		if (t->rn_flags & RNF_NORMAL) {
    305 			if (rn_b <= t->rn_b)
    306 				return t;
    307 		} else if (rn_satisfies_leaf(v, t, matched_off))
    308 				return t;
    309 	t = saved_t;
    310 	/* start searching up the tree */
    311 	do {
    312 		struct radix_mask *m;
    313 		t = t->rn_p;
    314 		m = t->rn_mklist;
    315 		if (m) {
    316 			/*
    317 			 * If non-contiguous masks ever become important
    318 			 * we can restore the masking and open coding of
    319 			 * the search and satisfaction test and put the
    320 			 * calculation of "off" back before the "do".
    321 			 */
    322 			do {
    323 				if (m->rm_flags & RNF_NORMAL) {
    324 					if (rn_b <= m->rm_b)
    325 						return m->rm_leaf;
    326 				} else {
    327 					off = min(t->rn_off, matched_off);
    328 					x = rn_search_m(v, t, m->rm_mask);
    329 					while (x && x->rn_mask != m->rm_mask)
    330 						x = x->rn_dupedkey;
    331 					if (x && rn_satisfies_leaf(v, x, off))
    332 						return x;
    333 				}
    334 				m = m->rm_mklist;
    335 			} while (m);
    336 		}
    337 	} while (t != top);
    338 	return NULL;
    339 }
    340 
    341 static void
    342 rn_nodeprint(struct radix_node *rn, rn_printer_t printer, void *arg,
    343     const char *delim)
    344 {
    345 	(*printer)(arg, "%s(%s%p: p<%p> l<%p> r<%p>)",
    346 	    delim, ((void *)rn == arg) ? "*" : "", rn, rn->rn_p,
    347 	    rn->rn_l, rn->rn_r);
    348 }
    349 
    350 #ifdef RN_DEBUG
    351 int	rn_debug =  1;
    352 
    353 static void
    354 rn_dbg_print(void *arg, const char *fmt, ...)
    355 {
    356 	va_list ap;
    357 
    358 	va_start(ap, fmt);
    359 	vlog(LOG_DEBUG, fmt, ap);
    360 	va_end(ap);
    361 }
    362 
    363 static void
    364 rn_treeprint(struct radix_node_head *h, rn_printer_t printer, void *arg)
    365 {
    366 	struct radix_node *dup, *rn;
    367 	const char *delim;
    368 
    369 	if (printer == NULL)
    370 		return;
    371 
    372 	rn = rn_walkfirst(h->rnh_treetop, printer, arg);
    373 	for (;;) {
    374 		/* Process leaves */
    375 		delim = "";
    376 		for (dup = rn; dup != NULL; dup = dup->rn_dupedkey) {
    377 			if ((dup->rn_flags & RNF_ROOT) != 0)
    378 				continue;
    379 			rn_nodeprint(dup, printer, arg, delim);
    380 			delim = ", ";
    381 		}
    382 		rn = rn_walknext(rn, printer, arg);
    383 		if (rn->rn_flags & RNF_ROOT)
    384 			return;
    385 	}
    386 	/* NOTREACHED */
    387 }
    388 
    389 #define	traverse(__head, __rn)	rn_treeprint((__head), rn_dbg_print, (__rn))
    390 #endif /* RN_DEBUG */
    391 
    392 struct radix_node *
    393 rn_newpair(
    394 	const void *v,
    395 	int b,
    396 	struct radix_node nodes[2])
    397 {
    398 	struct radix_node *tt = nodes;
    399 	struct radix_node *t = tt + 1;
    400 	t->rn_b = b; t->rn_bmask = 0x80 >> (b & 7);
    401 	t->rn_l = tt; t->rn_off = b >> 3;
    402 	tt->rn_b = -1; tt->rn_key = v; tt->rn_p = t;
    403 	tt->rn_flags = t->rn_flags = RNF_ACTIVE;
    404 	return t;
    405 }
    406 
    407 struct radix_node *
    408 rn_insert(
    409 	const void *v_arg,
    410 	struct radix_node_head *head,
    411 	int *dupentry,
    412 	struct radix_node nodes[2])
    413 {
    414 	struct radix_node *top = head->rnh_treetop;
    415 	struct radix_node *t = rn_search(v_arg, top);
    416 	struct radix_node *tt;
    417 	const char *v = v_arg;
    418 	int head_off = top->rn_off;
    419 	int vlen = *((const u_char *)v);
    420 	const char *cp = v + head_off;
    421 	int b;
    422     	/*
    423 	 * Find first bit at which v and t->rn_key differ
    424 	 */
    425     {
    426 	const char *cp2 = t->rn_key + head_off;
    427 	const char *cplim = v + vlen;
    428 	int cmp_res;
    429 
    430 	while (cp < cplim)
    431 		if (*cp2++ != *cp++)
    432 			goto on1;
    433 	*dupentry = 1;
    434 	return t;
    435 on1:
    436 	*dupentry = 0;
    437 	cmp_res = (cp[-1] ^ cp2[-1]) & 0xff;
    438 	for (b = (cp - v) << 3; cmp_res; b--)
    439 		cmp_res >>= 1;
    440     }
    441     {
    442 	struct radix_node *p, *x = top;
    443 	cp = v;
    444 	do {
    445 		p = x;
    446 		if (cp[x->rn_off] & x->rn_bmask)
    447 			x = x->rn_r;
    448 		else x = x->rn_l;
    449 	} while (b > (unsigned) x->rn_b); /* x->rn_b < b && x->rn_b >= 0 */
    450 #ifdef RN_DEBUG
    451 	if (rn_debug)
    452 		log(LOG_DEBUG, "%s: Going In:\n", __func__), traverse(head, p);
    453 #endif
    454 	t = rn_newpair(v_arg, b, nodes); tt = t->rn_l;
    455 	if ((cp[p->rn_off] & p->rn_bmask) == 0)
    456 		p->rn_l = t;
    457 	else
    458 		p->rn_r = t;
    459 	x->rn_p = t; t->rn_p = p; /* frees x, p as temp vars below */
    460 	if ((cp[t->rn_off] & t->rn_bmask) == 0) {
    461 		t->rn_r = x;
    462 	} else {
    463 		t->rn_r = tt; t->rn_l = x;
    464 	}
    465 #ifdef RN_DEBUG
    466 	if (rn_debug) {
    467 		log(LOG_DEBUG, "%s: Coming Out:\n", __func__),
    468 		    traverse(head, p);
    469 	}
    470 #endif /* RN_DEBUG */
    471     }
    472 	return tt;
    473 }
    474 
    475 struct radix_node *
    476 rn_addmask(
    477 	const void *n_arg,
    478 	int search,
    479 	int skip)
    480 {
    481 	const char *netmask = n_arg;
    482 	const char *cp;
    483 	const char *cplim;
    484 	struct radix_node *x;
    485 	struct radix_node *saved_x;
    486 	int b = 0, mlen, j;
    487 	int maskduplicated, m0, isnormal;
    488 	static int last_zeroed = 0;
    489 
    490 	if ((mlen = *(const u_char *)netmask) > max_keylen)
    491 		mlen = max_keylen;
    492 	if (skip == 0)
    493 		skip = 1;
    494 	if (mlen <= skip)
    495 		return mask_rnhead->rnh_nodes;
    496 	if (skip > 1)
    497 		memmove(addmask_key + 1, rn_ones + 1, skip - 1);
    498 	if ((m0 = mlen) > skip)
    499 		memmove(addmask_key + skip, netmask + skip, mlen - skip);
    500 	/*
    501 	 * Trim trailing zeroes.
    502 	 */
    503 	for (cp = addmask_key + mlen; (cp > addmask_key) && cp[-1] == 0;)
    504 		cp--;
    505 	mlen = cp - addmask_key;
    506 	if (mlen <= skip) {
    507 		if (m0 >= last_zeroed)
    508 			last_zeroed = mlen;
    509 		return mask_rnhead->rnh_nodes;
    510 	}
    511 	if (m0 < last_zeroed)
    512 		memset(addmask_key + m0, 0, last_zeroed - m0);
    513 	*addmask_key = last_zeroed = mlen;
    514 	x = rn_search(addmask_key, rn_masktop);
    515 	if (memcmp(addmask_key, x->rn_key, mlen) != 0)
    516 		x = 0;
    517 	if (x || search)
    518 		return x;
    519 	R_Malloc(x, struct radix_node *, max_keylen + 2 * sizeof (*x));
    520 	if ((saved_x = x) == NULL)
    521 		return NULL;
    522 	memset(x, 0, max_keylen + 2 * sizeof (*x));
    523 	cp = netmask = (void *)(x + 2);
    524 	memmove(x + 2, addmask_key, mlen);
    525 	x = rn_insert(cp, mask_rnhead, &maskduplicated, x);
    526 	if (maskduplicated) {
    527 		log(LOG_ERR, "rn_addmask: mask impossibly already in tree\n");
    528 		Free(saved_x);
    529 		return x;
    530 	}
    531 	/*
    532 	 * Calculate index of mask, and check for normalcy.
    533 	 */
    534 	cplim = netmask + mlen; isnormal = 1;
    535 	for (cp = netmask + skip; (cp < cplim) && *(const u_char *)cp == 0xff;)
    536 		cp++;
    537 	if (cp != cplim) {
    538 		for (j = 0x80; (j & *cp) != 0; j >>= 1)
    539 			b++;
    540 		if (*cp != normal_chars[b] || cp != (cplim - 1))
    541 			isnormal = 0;
    542 	}
    543 	b += (cp - netmask) << 3;
    544 	x->rn_b = -1 - b;
    545 	if (isnormal)
    546 		x->rn_flags |= RNF_NORMAL;
    547 	return x;
    548 }
    549 
    550 static int	/* XXX: arbitrary ordering for non-contiguous masks */
    551 rn_lexobetter(
    552 	const void *m_arg,
    553 	const void *n_arg)
    554 {
    555 	const u_char *mp = m_arg;
    556 	const u_char *np = n_arg;
    557 	const u_char *lim;
    558 
    559 	if (*mp > *np)
    560 		return 1;  /* not really, but need to check longer one first */
    561 	if (*mp == *np)
    562 		for (lim = mp + *mp; mp < lim;)
    563 			if (*mp++ > *np++)
    564 				return 1;
    565 	return 0;
    566 }
    567 
    568 static struct radix_mask *
    569 rn_new_radix_mask(
    570 	struct radix_node *tt,
    571 	struct radix_mask *next)
    572 {
    573 	struct radix_mask *m;
    574 
    575 	MKGet(m);
    576 	if (m == NULL) {
    577 		log(LOG_ERR, "Mask for route not entered\n");
    578 		return NULL;
    579 	}
    580 	memset(m, 0, sizeof(*m));
    581 	m->rm_b = tt->rn_b;
    582 	m->rm_flags = tt->rn_flags;
    583 	if (tt->rn_flags & RNF_NORMAL)
    584 		m->rm_leaf = tt;
    585 	else
    586 		m->rm_mask = tt->rn_mask;
    587 	m->rm_mklist = next;
    588 	tt->rn_mklist = m;
    589 	return m;
    590 }
    591 
    592 struct radix_node *
    593 rn_addroute(
    594 	const void *v_arg,
    595 	const void *n_arg,
    596 	struct radix_node_head *head,
    597 	struct radix_node treenodes[2])
    598 {
    599 	const char *v = v_arg, *netmask = n_arg;
    600 	struct radix_node *t, *x = NULL, *tt;
    601 	struct radix_node *saved_tt, *top = head->rnh_treetop;
    602 	short b = 0, b_leaf = 0;
    603 	int keyduplicated;
    604 	const char *mmask;
    605 	struct radix_mask *m, **mp;
    606 
    607 	/*
    608 	 * In dealing with non-contiguous masks, there may be
    609 	 * many different routes which have the same mask.
    610 	 * We will find it useful to have a unique pointer to
    611 	 * the mask to speed avoiding duplicate references at
    612 	 * nodes and possibly save time in calculating indices.
    613 	 */
    614 	if (netmask != NULL) {
    615 		if ((x = rn_addmask(netmask, 0, top->rn_off)) == NULL)
    616 			return NULL;
    617 		b_leaf = x->rn_b;
    618 		b = -1 - x->rn_b;
    619 		netmask = x->rn_key;
    620 	}
    621 	/*
    622 	 * Deal with duplicated keys: attach node to previous instance
    623 	 */
    624 	saved_tt = tt = rn_insert(v, head, &keyduplicated, treenodes);
    625 	if (keyduplicated) {
    626 		for (t = tt; tt != NULL; t = tt, tt = tt->rn_dupedkey) {
    627 			if (tt->rn_mask == netmask)
    628 				return NULL;
    629 			if (netmask == NULL ||
    630 			    (tt->rn_mask != NULL &&
    631 			     (b_leaf < tt->rn_b || /* index(netmask) > node */
    632 			       rn_refines(netmask, tt->rn_mask) ||
    633 			       rn_lexobetter(netmask, tt->rn_mask))))
    634 				break;
    635 		}
    636 		/*
    637 		 * If the mask is not duplicated, we wouldn't
    638 		 * find it among possible duplicate key entries
    639 		 * anyway, so the above test doesn't hurt.
    640 		 *
    641 		 * We sort the masks for a duplicated key the same way as
    642 		 * in a masklist -- most specific to least specific.
    643 		 * This may require the unfortunate nuisance of relocating
    644 		 * the head of the list.
    645 		 *
    646 		 * We also reverse, or doubly link the list through the
    647 		 * parent pointer.
    648 		 */
    649 		if (tt == saved_tt) {
    650 			struct	radix_node *xx = x;
    651 			/* link in at head of list */
    652 			(tt = treenodes)->rn_dupedkey = t;
    653 			tt->rn_flags = t->rn_flags;
    654 			tt->rn_p = x = t->rn_p;
    655 			t->rn_p = tt;
    656 			if (x->rn_l == t)
    657 				x->rn_l = tt;
    658 			else
    659 				x->rn_r = tt;
    660 			saved_tt = tt;
    661 			x = xx;
    662 		} else {
    663 			(tt = treenodes)->rn_dupedkey = t->rn_dupedkey;
    664 			t->rn_dupedkey = tt;
    665 			tt->rn_p = t;
    666 			if (tt->rn_dupedkey)
    667 				tt->rn_dupedkey->rn_p = tt;
    668 		}
    669 		tt->rn_key = v;
    670 		tt->rn_b = -1;
    671 		tt->rn_flags = RNF_ACTIVE;
    672 	}
    673 	/*
    674 	 * Put mask in tree.
    675 	 */
    676 	if (netmask != NULL) {
    677 		tt->rn_mask = netmask;
    678 		tt->rn_b = x->rn_b;
    679 		tt->rn_flags |= x->rn_flags & RNF_NORMAL;
    680 	}
    681 	t = saved_tt->rn_p;
    682 	if (keyduplicated)
    683 		goto on2;
    684 	b_leaf = -1 - t->rn_b;
    685 	if (t->rn_r == saved_tt)
    686 		x = t->rn_l;
    687 	else
    688 		x = t->rn_r;
    689 	/* Promote general routes from below */
    690 	if (x->rn_b < 0) {
    691 		for (mp = &t->rn_mklist; x != NULL; x = x->rn_dupedkey) {
    692 			if (x->rn_mask != NULL && x->rn_b >= b_leaf &&
    693 			    x->rn_mklist == NULL) {
    694 				*mp = m = rn_new_radix_mask(x, NULL);
    695 				if (m != NULL)
    696 					mp = &m->rm_mklist;
    697 			}
    698 		}
    699 	} else if (x->rn_mklist != NULL) {
    700 		/*
    701 		 * Skip over masks whose index is > that of new node
    702 		 */
    703 		for (mp = &x->rn_mklist; (m = *mp) != NULL; mp = &m->rm_mklist)
    704 			if (m->rm_b >= b_leaf)
    705 				break;
    706 		t->rn_mklist = m;
    707 		*mp = NULL;
    708 	}
    709 on2:
    710 	/* Add new route to highest possible ancestor's list */
    711 	if (netmask == NULL || b > t->rn_b)
    712 		return tt; /* can't lift at all */
    713 	b_leaf = tt->rn_b;
    714 	do {
    715 		x = t;
    716 		t = t->rn_p;
    717 	} while (b <= t->rn_b && x != top);
    718 	/*
    719 	 * Search through routes associated with node to
    720 	 * insert new route according to index.
    721 	 * Need same criteria as when sorting dupedkeys to avoid
    722 	 * double loop on deletion.
    723 	 */
    724 	for (mp = &x->rn_mklist; (m = *mp) != NULL; mp = &m->rm_mklist) {
    725 		if (m->rm_b < b_leaf)
    726 			continue;
    727 		if (m->rm_b > b_leaf)
    728 			break;
    729 		if (m->rm_flags & RNF_NORMAL) {
    730 			mmask = m->rm_leaf->rn_mask;
    731 			if (tt->rn_flags & RNF_NORMAL) {
    732 				log(LOG_ERR, "Non-unique normal route,"
    733 				    " mask not entered\n");
    734 				return tt;
    735 			}
    736 		} else
    737 			mmask = m->rm_mask;
    738 		if (mmask == netmask) {
    739 			m->rm_refs++;
    740 			tt->rn_mklist = m;
    741 			return tt;
    742 		}
    743 		if (rn_refines(netmask, mmask) || rn_lexobetter(netmask, mmask))
    744 			break;
    745 	}
    746 	*mp = rn_new_radix_mask(tt, *mp);
    747 	return tt;
    748 }
    749 
    750 struct radix_node *
    751 rn_delete1(
    752 	const void *v_arg,
    753 	const void *netmask_arg,
    754 	struct radix_node_head *head,
    755 	struct radix_node *rn)
    756 {
    757 	struct radix_node *t, *p, *x, *tt;
    758 	struct radix_mask *m, *saved_m, **mp;
    759 	struct radix_node *dupedkey, *saved_tt, *top;
    760 	const char *v, *netmask;
    761 	int b, head_off, vlen;
    762 
    763 	v = v_arg;
    764 	netmask = netmask_arg;
    765 	x = head->rnh_treetop;
    766 	tt = rn_search(v, x);
    767 	head_off = x->rn_off;
    768 	vlen =  *(const u_char *)v;
    769 	saved_tt = tt;
    770 	top = x;
    771 	if (tt == NULL ||
    772 	    memcmp(v + head_off, tt->rn_key + head_off, vlen - head_off) != 0)
    773 		return NULL;
    774 	/*
    775 	 * Delete our route from mask lists.
    776 	 */
    777 	if (netmask != NULL) {
    778 		if ((x = rn_addmask(netmask, 1, head_off)) == NULL)
    779 			return NULL;
    780 		netmask = x->rn_key;
    781 		while (tt->rn_mask != netmask)
    782 			if ((tt = tt->rn_dupedkey) == NULL)
    783 				return NULL;
    784 	}
    785 	if (tt->rn_mask == NULL || (saved_m = m = tt->rn_mklist) == NULL)
    786 		goto on1;
    787 	if (tt->rn_flags & RNF_NORMAL) {
    788 		if (m->rm_leaf != tt || m->rm_refs > 0) {
    789 			log(LOG_ERR, "rn_delete: inconsistent annotation\n");
    790 			return NULL;  /* dangling ref could cause disaster */
    791 		}
    792 	} else {
    793 		if (m->rm_mask != tt->rn_mask) {
    794 			log(LOG_ERR, "rn_delete: inconsistent annotation\n");
    795 			goto on1;
    796 		}
    797 		if (--m->rm_refs >= 0)
    798 			goto on1;
    799 	}
    800 	b = -1 - tt->rn_b;
    801 	t = saved_tt->rn_p;
    802 	if (b > t->rn_b)
    803 		goto on1; /* Wasn't lifted at all */
    804 	do {
    805 		x = t;
    806 		t = t->rn_p;
    807 	} while (b <= t->rn_b && x != top);
    808 	for (mp = &x->rn_mklist; (m = *mp) != NULL; mp = &m->rm_mklist) {
    809 		if (m == saved_m) {
    810 			*mp = m->rm_mklist;
    811 			MKFree(m);
    812 			break;
    813 		}
    814 	}
    815 	if (m == NULL) {
    816 		log(LOG_ERR, "rn_delete: couldn't find our annotation\n");
    817 		if (tt->rn_flags & RNF_NORMAL)
    818 			return NULL; /* Dangling ref to us */
    819 	}
    820 on1:
    821 	/*
    822 	 * Eliminate us from tree
    823 	 */
    824 	if (tt->rn_flags & RNF_ROOT)
    825 		return NULL;
    826 #ifdef RN_DEBUG
    827 	if (rn_debug)
    828 		log(LOG_DEBUG, "%s: Going In:\n", __func__), traverse(head, tt);
    829 #endif
    830 	t = tt->rn_p;
    831 	dupedkey = saved_tt->rn_dupedkey;
    832 	if (dupedkey != NULL) {
    833 		/*
    834 		 * Here, tt is the deletion target, and
    835 		 * saved_tt is the head of the dupedkey chain.
    836 		 */
    837 		if (tt == saved_tt) {
    838 			x = dupedkey;
    839 			x->rn_p = t;
    840 			if (t->rn_l == tt)
    841 				t->rn_l = x;
    842 			else
    843 				t->rn_r = x;
    844 		} else {
    845 			/* find node in front of tt on the chain */
    846 			for (x = p = saved_tt;
    847 			     p != NULL && p->rn_dupedkey != tt;)
    848 				p = p->rn_dupedkey;
    849 			if (p != NULL) {
    850 				p->rn_dupedkey = tt->rn_dupedkey;
    851 				if (tt->rn_dupedkey != NULL)
    852 					tt->rn_dupedkey->rn_p = p;
    853 			} else
    854 				log(LOG_ERR, "rn_delete: couldn't find us\n");
    855 		}
    856 		t = tt + 1;
    857 		if  (t->rn_flags & RNF_ACTIVE) {
    858 			*++x = *t;
    859 			p = t->rn_p;
    860 			if (p->rn_l == t)
    861 				p->rn_l = x;
    862 			else
    863 				p->rn_r = x;
    864 			x->rn_l->rn_p = x;
    865 			x->rn_r->rn_p = x;
    866 		}
    867 		goto out;
    868 	}
    869 	if (t->rn_l == tt)
    870 		x = t->rn_r;
    871 	else
    872 		x = t->rn_l;
    873 	p = t->rn_p;
    874 	if (p->rn_r == t)
    875 		p->rn_r = x;
    876 	else
    877 		p->rn_l = x;
    878 	x->rn_p = p;
    879 	/*
    880 	 * Demote routes attached to us.
    881 	 */
    882 	if (t->rn_mklist == NULL)
    883 		;
    884 	else if (x->rn_b >= 0) {
    885 		for (mp = &x->rn_mklist; (m = *mp) != NULL; mp = &m->rm_mklist)
    886 			;
    887 		*mp = t->rn_mklist;
    888 	} else {
    889 		/* If there are any key,mask pairs in a sibling
    890 		   duped-key chain, some subset will appear sorted
    891 		   in the same order attached to our mklist */
    892 		for (m = t->rn_mklist;
    893 		     m != NULL && x != NULL;
    894 		     x = x->rn_dupedkey) {
    895 			if (m == x->rn_mklist) {
    896 				struct radix_mask *mm = m->rm_mklist;
    897 				x->rn_mklist = NULL;
    898 				if (--(m->rm_refs) < 0)
    899 					MKFree(m);
    900 				m = mm;
    901 			}
    902 		}
    903 		if (m != NULL) {
    904 			log(LOG_ERR, "rn_delete: Orphaned Mask %p at %p\n",
    905 			    m, x);
    906 		}
    907 	}
    908 	/*
    909 	 * We may be holding an active internal node in the tree.
    910 	 */
    911 	x = tt + 1;
    912 	if (t != x) {
    913 		*t = *x;
    914 		t->rn_l->rn_p = t;
    915 		t->rn_r->rn_p = t;
    916 		p = x->rn_p;
    917 		if (p->rn_l == x)
    918 			p->rn_l = t;
    919 		else
    920 			p->rn_r = t;
    921 	}
    922 out:
    923 #ifdef RN_DEBUG
    924 	if (rn_debug) {
    925 		log(LOG_DEBUG, "%s: Coming Out:\n", __func__),
    926 		    traverse(head, tt);
    927 	}
    928 #endif /* RN_DEBUG */
    929 	tt->rn_flags &= ~RNF_ACTIVE;
    930 	tt[1].rn_flags &= ~RNF_ACTIVE;
    931 	return tt;
    932 }
    933 
    934 struct radix_node *
    935 rn_delete(
    936 	const void *v_arg,
    937 	const void *netmask_arg,
    938 	struct radix_node_head *head)
    939 {
    940 	return rn_delete1(v_arg, netmask_arg, head, NULL);
    941 }
    942 
    943 static struct radix_node *
    944 rn_walknext(struct radix_node *rn, rn_printer_t printer, void *arg)
    945 {
    946 	/* If at right child go back up, otherwise, go right */
    947 	while (rn->rn_p->rn_r == rn && (rn->rn_flags & RNF_ROOT) == 0) {
    948 		if (printer != NULL)
    949 			(*printer)(arg, SUBTREE_CLOSE);
    950 		rn = rn->rn_p;
    951 	}
    952 	if (printer)
    953 		rn_nodeprint(rn->rn_p, printer, arg, "");
    954 	/* Find the next *leaf* since next node might vanish, too */
    955 	for (rn = rn->rn_p->rn_r; rn->rn_b >= 0;) {
    956 		if (printer != NULL)
    957 			(*printer)(arg, SUBTREE_OPEN);
    958 		rn = rn->rn_l;
    959 	}
    960 	return rn;
    961 }
    962 
    963 static struct radix_node *
    964 rn_walkfirst(struct radix_node *rn, rn_printer_t printer, void *arg)
    965 {
    966 	/* First time through node, go left */
    967 	while (rn->rn_b >= 0) {
    968 		if (printer != NULL)
    969 			(*printer)(arg, SUBTREE_OPEN);
    970 		rn = rn->rn_l;
    971 	}
    972 	return rn;
    973 }
    974 
    975 int
    976 rn_walktree(
    977 	struct radix_node_head *h,
    978 	int (*f)(struct radix_node *, void *),
    979 	void *w)
    980 {
    981 	int error;
    982 	struct radix_node *base, *next, *rn;
    983 	/*
    984 	 * This gets complicated because we may delete the node
    985 	 * while applying the function f to it, so we need to calculate
    986 	 * the successor node in advance.
    987 	 */
    988 	rn = rn_walkfirst(h->rnh_treetop, NULL, NULL);
    989 	for (;;) {
    990 		base = rn;
    991 		next = rn_walknext(rn, NULL, NULL);
    992 		/* Process leaves */
    993 		while ((rn = base) != NULL) {
    994 			base = rn->rn_dupedkey;
    995 			if (!(rn->rn_flags & RNF_ROOT) && (error = (*f)(rn, w)))
    996 				return error;
    997 		}
    998 		rn = next;
    999 		if (rn->rn_flags & RNF_ROOT)
   1000 			return 0;
   1001 	}
   1002 	/* NOTREACHED */
   1003 }
   1004 
   1005 int
   1006 rn_inithead(head, off)
   1007 	void **head;
   1008 	int off;
   1009 {
   1010 	struct radix_node_head *rnh;
   1011 
   1012 	if (*head != NULL)
   1013 		return 1;
   1014 	R_Malloc(rnh, struct radix_node_head *, sizeof (*rnh));
   1015 	if (rnh == NULL)
   1016 		return 0;
   1017 	*head = rnh;
   1018 	return rn_inithead0(rnh, off);
   1019 }
   1020 
   1021 int
   1022 rn_inithead0(rnh, off)
   1023 	struct radix_node_head *rnh;
   1024 	int off;
   1025 {
   1026 	struct radix_node *t;
   1027 	struct radix_node *tt;
   1028 	struct radix_node *ttt;
   1029 
   1030 	memset(rnh, 0, sizeof(*rnh));
   1031 	t = rn_newpair(rn_zeros, off, rnh->rnh_nodes);
   1032 	ttt = rnh->rnh_nodes + 2;
   1033 	t->rn_r = ttt;
   1034 	t->rn_p = t;
   1035 	tt = t->rn_l;
   1036 	tt->rn_flags = t->rn_flags = RNF_ROOT | RNF_ACTIVE;
   1037 	tt->rn_b = -1 - off;
   1038 	*ttt = *tt;
   1039 	ttt->rn_key = rn_ones;
   1040 	rnh->rnh_addaddr = rn_addroute;
   1041 	rnh->rnh_deladdr = rn_delete;
   1042 	rnh->rnh_matchaddr = rn_match;
   1043 	rnh->rnh_lookup = rn_lookup;
   1044 	rnh->rnh_treetop = t;
   1045 	return 1;
   1046 }
   1047 
   1048 void
   1049 rn_init()
   1050 {
   1051 	char *cp, *cplim;
   1052 #ifdef _KERNEL
   1053 	static int initialized;
   1054 	__link_set_decl(domains, struct domain);
   1055 	struct domain *const *dpp;
   1056 
   1057 	if (initialized)
   1058 		return;
   1059 	initialized = 1;
   1060 
   1061 	__link_set_foreach(dpp, domains) {
   1062 		if ((*dpp)->dom_maxrtkey > max_keylen)
   1063 			max_keylen = (*dpp)->dom_maxrtkey;
   1064 	}
   1065 #endif
   1066 	if (max_keylen == 0) {
   1067 		log(LOG_ERR,
   1068 		    "rn_init: radix functions require max_keylen be set\n");
   1069 		return;
   1070 	}
   1071 	R_Malloc(rn_zeros, char *, 3 * max_keylen);
   1072 	if (rn_zeros == NULL)
   1073 		panic("rn_init");
   1074 	memset(rn_zeros, 0, 3 * max_keylen);
   1075 	rn_ones = cp = rn_zeros + max_keylen;
   1076 	addmask_key = cplim = rn_ones + max_keylen;
   1077 	while (cp < cplim)
   1078 		*cp++ = -1;
   1079 	if (rn_inithead((void *)&mask_rnhead, 0) == 0)
   1080 		panic("rn_init 2");
   1081 }
   1082