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