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