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