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