Home | History | Annotate | Line # | Download | only in net
radix.c revision 1.32
      1 /*	$NetBSD: radix.c,v 1.32 2006/12/04 01:45:50 dyoung 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.32 2006/12/04 01:45:50 dyoung 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_nodenum;
    353 struct	radix_node *rn_clist;
    354 int	rn_saveinfo;
    355 int	rn_debug =  1;
    356 
    357 static void
    358 rn_dbg_print(void *arg, const char *fmt, ...)
    359 {
    360 	va_list ap;
    361 
    362 	va_start(ap, fmt);
    363 	vlog(LOG_DEBUG, fmt, ap);
    364 	va_end(ap);
    365 }
    366 
    367 static void
    368 rn_treeprint(struct radix_node_head *h, rn_printer_t printer, void *arg)
    369 {
    370 	struct radix_node *dup, *rn;
    371 	const char *delim;
    372 
    373 	if (printer == NULL)
    374 		return;
    375 
    376 	rn = rn_walkfirst(h->rnh_treetop, printer, arg);
    377 	for (;;) {
    378 		/* Process leaves */
    379 		delim = "";
    380 		for (dup = rn; dup != NULL; dup = dup->rn_dupedkey) {
    381 			if ((dup->rn_flags & RNF_ROOT) != 0)
    382 				continue;
    383 			rn_nodeprint(dup, printer, arg, delim);
    384 			delim = ", ";
    385 		}
    386 		rn = rn_walknext(rn, printer, arg);
    387 		if (rn->rn_flags & RNF_ROOT)
    388 			return;
    389 	}
    390 	/* NOTREACHED */
    391 }
    392 
    393 #define	traverse(__head, __rn)	rn_treeprint((__head), rn_dbg_print, (__rn))
    394 #endif /* RN_DEBUG */
    395 
    396 struct radix_node *
    397 rn_newpair(
    398 	const void *v,
    399 	int b,
    400 	struct radix_node nodes[2])
    401 {
    402 	struct radix_node *tt = nodes;
    403 	struct radix_node *t = tt + 1;
    404 	t->rn_b = b; t->rn_bmask = 0x80 >> (b & 7);
    405 	t->rn_l = tt; t->rn_off = b >> 3;
    406 	tt->rn_b = -1; tt->rn_key = v; tt->rn_p = t;
    407 	tt->rn_flags = t->rn_flags = RNF_ACTIVE;
    408 #ifdef RN_DEBUG
    409 	tt->rn_info = rn_nodenum++; t->rn_info = rn_nodenum++;
    410 	tt->rn_twin = t; tt->rn_ybro = rn_clist; rn_clist = tt;
    411 #endif
    412 	return t;
    413 }
    414 
    415 struct radix_node *
    416 rn_insert(
    417 	const void *v_arg,
    418 	struct radix_node_head *head,
    419 	int *dupentry,
    420 	struct radix_node nodes[2])
    421 {
    422 	struct radix_node *top = head->rnh_treetop;
    423 	struct radix_node *t = rn_search(v_arg, top);
    424 	struct radix_node *tt;
    425 	const char *v = v_arg;
    426 	int head_off = top->rn_off;
    427 	int vlen = *((const u_char *)v);
    428 	const char *cp = v + head_off;
    429 	int b;
    430     	/*
    431 	 * Find first bit at which v and t->rn_key differ
    432 	 */
    433     {
    434 	const char *cp2 = t->rn_key + head_off;
    435 	const char *cplim = v + vlen;
    436 	int cmp_res;
    437 
    438 	while (cp < cplim)
    439 		if (*cp2++ != *cp++)
    440 			goto on1;
    441 	*dupentry = 1;
    442 	return t;
    443 on1:
    444 	*dupentry = 0;
    445 	cmp_res = (cp[-1] ^ cp2[-1]) & 0xff;
    446 	for (b = (cp - v) << 3; cmp_res; b--)
    447 		cmp_res >>= 1;
    448     }
    449     {
    450 	struct radix_node *p, *x = top;
    451 	cp = v;
    452 	do {
    453 		p = x;
    454 		if (cp[x->rn_off] & x->rn_bmask)
    455 			x = x->rn_r;
    456 		else x = x->rn_l;
    457 	} while (b > (unsigned) x->rn_b); /* x->rn_b < b && x->rn_b >= 0 */
    458 #ifdef RN_DEBUG
    459 	if (rn_debug)
    460 		log(LOG_DEBUG, "%s: Going In:\n", __func__), traverse(head, p);
    461 #endif
    462 	t = rn_newpair(v_arg, b, nodes); tt = t->rn_l;
    463 	if ((cp[p->rn_off] & p->rn_bmask) == 0)
    464 		p->rn_l = t;
    465 	else
    466 		p->rn_r = t;
    467 	x->rn_p = t; t->rn_p = p; /* frees x, p as temp vars below */
    468 	if ((cp[t->rn_off] & t->rn_bmask) == 0) {
    469 		t->rn_r = x;
    470 	} else {
    471 		t->rn_r = tt; t->rn_l = x;
    472 	}
    473 #ifdef RN_DEBUG
    474 	if (rn_debug) {
    475 		log(LOG_DEBUG, "%s: Coming Out:\n", __func__),
    476 		    traverse(head, p);
    477 	}
    478 #endif /* RN_DEBUG */
    479     }
    480 	return (tt);
    481 }
    482 
    483 struct radix_node *
    484 rn_addmask(
    485 	const void *n_arg,
    486 	int search,
    487 	int skip)
    488 {
    489 	const char *netmask = n_arg;
    490 	const char *cp;
    491 	const char *cplim;
    492 	struct radix_node *x;
    493 	struct radix_node *saved_x;
    494 	int b = 0, mlen, j;
    495 	int maskduplicated, m0, isnormal;
    496 	static int last_zeroed = 0;
    497 
    498 	if ((mlen = *(const u_char *)netmask) > max_keylen)
    499 		mlen = max_keylen;
    500 	if (skip == 0)
    501 		skip = 1;
    502 	if (mlen <= skip)
    503 		return (mask_rnhead->rnh_nodes);
    504 	if (skip > 1)
    505 		Bcopy(rn_ones + 1, addmask_key + 1, skip - 1);
    506 	if ((m0 = mlen) > skip)
    507 		Bcopy(netmask + skip, addmask_key + skip, mlen - skip);
    508 	/*
    509 	 * Trim trailing zeroes.
    510 	 */
    511 	for (cp = addmask_key + mlen; (cp > addmask_key) && cp[-1] == 0;)
    512 		cp--;
    513 	mlen = cp - addmask_key;
    514 	if (mlen <= skip) {
    515 		if (m0 >= last_zeroed)
    516 			last_zeroed = mlen;
    517 		return (mask_rnhead->rnh_nodes);
    518 	}
    519 	if (m0 < last_zeroed)
    520 		Bzero(addmask_key + m0, last_zeroed - m0);
    521 	*addmask_key = last_zeroed = mlen;
    522 	x = rn_search(addmask_key, rn_masktop);
    523 	if (Bcmp(addmask_key, x->rn_key, mlen) != 0)
    524 		x = 0;
    525 	if (x || search)
    526 		return (x);
    527 	R_Malloc(x, struct radix_node *, max_keylen + 2 * sizeof (*x));
    528 	if ((saved_x = x) == 0)
    529 		return (0);
    530 	Bzero(x, max_keylen + 2 * sizeof (*x));
    531 	cp = netmask = (caddr_t)(x + 2);
    532 	Bcopy(addmask_key, (caddr_t)(x + 2), mlen);
    533 	x = rn_insert(cp, mask_rnhead, &maskduplicated, x);
    534 	if (maskduplicated) {
    535 		log(LOG_ERR, "rn_addmask: mask impossibly already in tree\n");
    536 		Free(saved_x);
    537 		return (x);
    538 	}
    539 	/*
    540 	 * Calculate index of mask, and check for normalcy.
    541 	 */
    542 	cplim = netmask + mlen; isnormal = 1;
    543 	for (cp = netmask + skip; (cp < cplim) && *(const u_char *)cp == 0xff;)
    544 		cp++;
    545 	if (cp != cplim) {
    546 		for (j = 0x80; (j & *cp) != 0; j >>= 1)
    547 			b++;
    548 		if (*cp != normal_chars[b] || cp != (cplim - 1))
    549 			isnormal = 0;
    550 	}
    551 	b += (cp - netmask) << 3;
    552 	x->rn_b = -1 - b;
    553 	if (isnormal)
    554 		x->rn_flags |= RNF_NORMAL;
    555 	return (x);
    556 }
    557 
    558 static int	/* XXX: arbitrary ordering for non-contiguous masks */
    559 rn_lexobetter(
    560 	const void *m_arg,
    561 	const void *n_arg)
    562 {
    563 	const u_char *mp = m_arg;
    564 	const u_char *np = n_arg;
    565 	const u_char *lim;
    566 
    567 	if (*mp > *np)
    568 		return 1;  /* not really, but need to check longer one first */
    569 	if (*mp == *np)
    570 		for (lim = mp + *mp; mp < lim;)
    571 			if (*mp++ > *np++)
    572 				return 1;
    573 	return 0;
    574 }
    575 
    576 static struct radix_mask *
    577 rn_new_radix_mask(
    578 	struct radix_node *tt,
    579 	struct radix_mask *next)
    580 {
    581 	struct radix_mask *m;
    582 
    583 	MKGet(m);
    584 	if (m == 0) {
    585 		log(LOG_ERR, "Mask for route not entered\n");
    586 		return (0);
    587 	}
    588 	Bzero(m, sizeof *m);
    589 	m->rm_b = tt->rn_b;
    590 	m->rm_flags = tt->rn_flags;
    591 	if (tt->rn_flags & RNF_NORMAL)
    592 		m->rm_leaf = tt;
    593 	else
    594 		m->rm_mask = tt->rn_mask;
    595 	m->rm_mklist = next;
    596 	tt->rn_mklist = m;
    597 	return m;
    598 }
    599 
    600 struct radix_node *
    601 rn_addroute(
    602 	const void *v_arg,
    603 	const void *n_arg,
    604 	struct radix_node_head *head,
    605 	struct radix_node treenodes[2])
    606 {
    607 	const char *v = v_arg;
    608 	const char *netmask = n_arg;
    609 	struct radix_node *t;
    610 	struct radix_node *x = 0;
    611 	struct radix_node *tt;
    612 	struct radix_node *saved_tt;
    613 	struct radix_node *top = head->rnh_treetop;
    614 	short b = 0, b_leaf = 0;
    615 	int keyduplicated;
    616 	const char *mmask;
    617 	struct radix_mask *m, **mp;
    618 
    619 	/*
    620 	 * In dealing with non-contiguous masks, there may be
    621 	 * many different routes which have the same mask.
    622 	 * We will find it useful to have a unique pointer to
    623 	 * the mask to speed avoiding duplicate references at
    624 	 * nodes and possibly save time in calculating indices.
    625 	 */
    626 	if (netmask)  {
    627 		if ((x = rn_addmask(netmask, 0, top->rn_off)) == 0)
    628 			return (0);
    629 		b_leaf = x->rn_b;
    630 		b = -1 - x->rn_b;
    631 		netmask = x->rn_key;
    632 	}
    633 	/*
    634 	 * Deal with duplicated keys: attach node to previous instance
    635 	 */
    636 	saved_tt = tt = rn_insert(v, head, &keyduplicated, treenodes);
    637 	if (keyduplicated) {
    638 		for (t = tt; tt; t = tt, tt = tt->rn_dupedkey) {
    639 			if (tt->rn_mask == netmask)
    640 				return (0);
    641 			if (netmask == 0 ||
    642 			    (tt->rn_mask &&
    643 			     ((b_leaf < tt->rn_b) || /* index(netmask) > node */
    644 			       rn_refines(netmask, tt->rn_mask) ||
    645 			       rn_lexobetter(netmask, tt->rn_mask))))
    646 				break;
    647 		}
    648 		/*
    649 		 * If the mask is not duplicated, we wouldn't
    650 		 * find it among possible duplicate key entries
    651 		 * anyway, so the above test doesn't hurt.
    652 		 *
    653 		 * We sort the masks for a duplicated key the same way as
    654 		 * in a masklist -- most specific to least specific.
    655 		 * This may require the unfortunate nuisance of relocating
    656 		 * the head of the list.
    657 		 *
    658 		 * We also reverse, or doubly link the list through the
    659 		 * parent pointer.
    660 		 */
    661 		if (tt == saved_tt) {
    662 			struct	radix_node *xx = x;
    663 			/* link in at head of list */
    664 			(tt = treenodes)->rn_dupedkey = t;
    665 			tt->rn_flags = t->rn_flags;
    666 			tt->rn_p = x = t->rn_p;
    667 			t->rn_p = tt;
    668 			if (x->rn_l == t) x->rn_l = tt; else x->rn_r = tt;
    669 			saved_tt = tt; x = xx;
    670 		} else {
    671 			(tt = treenodes)->rn_dupedkey = t->rn_dupedkey;
    672 			t->rn_dupedkey = tt;
    673 			tt->rn_p = t;
    674 			if (tt->rn_dupedkey)
    675 				tt->rn_dupedkey->rn_p = tt;
    676 		}
    677 #ifdef RN_DEBUG
    678 		t=tt+1; tt->rn_info = rn_nodenum++; t->rn_info = rn_nodenum++;
    679 		tt->rn_twin = t; tt->rn_ybro = rn_clist; rn_clist = tt;
    680 #endif
    681 		tt->rn_key = __UNCONST(v); /*XXXUNCONST*/
    682 		tt->rn_b = -1;
    683 		tt->rn_flags = RNF_ACTIVE;
    684 	}
    685 	/*
    686 	 * Put mask in tree.
    687 	 */
    688 	if (netmask) {
    689 		tt->rn_mask = netmask;
    690 		tt->rn_b = x->rn_b;
    691 		tt->rn_flags |= x->rn_flags & RNF_NORMAL;
    692 	}
    693 	t = saved_tt->rn_p;
    694 	if (keyduplicated)
    695 		goto on2;
    696 	b_leaf = -1 - t->rn_b;
    697 	if (t->rn_r == saved_tt) x = t->rn_l; else x = t->rn_r;
    698 	/* Promote general routes from below */
    699 	if (x->rn_b < 0) {
    700 	    for (mp = &t->rn_mklist; x; x = x->rn_dupedkey)
    701 		if (x->rn_mask && (x->rn_b >= b_leaf) && x->rn_mklist == 0) {
    702 			*mp = m = rn_new_radix_mask(x, 0);
    703 			if (m)
    704 				mp = &m->rm_mklist;
    705 		}
    706 	} else if (x->rn_mklist) {
    707 		/*
    708 		 * Skip over masks whose index is > that of new node
    709 		 */
    710 		for (mp = &x->rn_mklist; (m = *mp); mp = &m->rm_mklist)
    711 			if (m->rm_b >= b_leaf)
    712 				break;
    713 		t->rn_mklist = m; *mp = 0;
    714 	}
    715 on2:
    716 	/* Add new route to highest possible ancestor's list */
    717 	if ((netmask == 0) || (b > t->rn_b ))
    718 		return tt; /* can't lift at all */
    719 	b_leaf = tt->rn_b;
    720 	do {
    721 		x = t;
    722 		t = t->rn_p;
    723 	} while (b <= t->rn_b && x != top);
    724 	/*
    725 	 * Search through routes associated with node to
    726 	 * insert new route according to index.
    727 	 * Need same criteria as when sorting dupedkeys to avoid
    728 	 * double loop on deletion.
    729 	 */
    730 	for (mp = &x->rn_mklist; (m = *mp); mp = &m->rm_mklist) {
    731 		if (m->rm_b < b_leaf)
    732 			continue;
    733 		if (m->rm_b > b_leaf)
    734 			break;
    735 		if (m->rm_flags & RNF_NORMAL) {
    736 			mmask = m->rm_leaf->rn_mask;
    737 			if (tt->rn_flags & RNF_NORMAL) {
    738 				log(LOG_ERR, "Non-unique normal route,"
    739 				    " mask not entered\n");
    740 				return tt;
    741 			}
    742 		} else
    743 			mmask = m->rm_mask;
    744 		if (mmask == netmask) {
    745 			m->rm_refs++;
    746 			tt->rn_mklist = m;
    747 			return tt;
    748 		}
    749 		if (rn_refines(netmask, mmask) || rn_lexobetter(netmask, mmask))
    750 			break;
    751 	}
    752 	*mp = rn_new_radix_mask(tt, *mp);
    753 	return tt;
    754 }
    755 
    756 struct radix_node *
    757 rn_delete(
    758 	const void *v_arg,
    759 	const void *netmask_arg,
    760 	struct radix_node_head *head)
    761 {
    762 	struct radix_node *t;
    763 	struct radix_node *p;
    764 	struct radix_node *x;
    765 	struct radix_node *tt;
    766 	struct radix_node *dupedkey;
    767 	struct radix_node *saved_tt;
    768 	struct radix_node *top;
    769 	struct radix_mask *m;
    770 	struct radix_mask *saved_m;
    771 	struct radix_mask **mp;
    772 	const char *v = v_arg;
    773 	const char *netmask = netmask_arg;
    774 	int b, head_off, vlen;
    775 
    776 	x = head->rnh_treetop;
    777 	tt = rn_search(v, x);
    778 	head_off = x->rn_off;
    779 	vlen =  *(const u_char *)v;
    780 	saved_tt = tt;
    781 	top = x;
    782 	if (tt == 0 ||
    783 	    Bcmp(v + head_off, tt->rn_key + head_off, vlen - head_off))
    784 		return (0);
    785 	/*
    786 	 * Delete our route from mask lists.
    787 	 */
    788 	if (netmask) {
    789 		if ((x = rn_addmask(netmask, 1, head_off)) == 0)
    790 			return (0);
    791 		netmask = x->rn_key;
    792 		while (tt->rn_mask != netmask)
    793 			if ((tt = tt->rn_dupedkey) == 0)
    794 				return (0);
    795 	}
    796 	if (tt->rn_mask == 0 || (saved_m = m = tt->rn_mklist) == 0)
    797 		goto on1;
    798 	if (tt->rn_flags & RNF_NORMAL) {
    799 		if (m->rm_leaf != tt || m->rm_refs > 0) {
    800 			log(LOG_ERR, "rn_delete: inconsistent annotation\n");
    801 			return 0;  /* dangling ref could cause disaster */
    802 		}
    803 	} else {
    804 		if (m->rm_mask != tt->rn_mask) {
    805 			log(LOG_ERR, "rn_delete: inconsistent annotation\n");
    806 			goto on1;
    807 		}
    808 		if (--m->rm_refs >= 0)
    809 			goto on1;
    810 	}
    811 	b = -1 - tt->rn_b;
    812 	t = saved_tt->rn_p;
    813 	if (b > t->rn_b)
    814 		goto on1; /* Wasn't lifted at all */
    815 	do {
    816 		x = t;
    817 		t = t->rn_p;
    818 	} while (b <= t->rn_b && x != top);
    819 	for (mp = &x->rn_mklist; (m = *mp); mp = &m->rm_mklist)
    820 		if (m == saved_m) {
    821 			*mp = m->rm_mklist;
    822 			MKFree(m);
    823 			break;
    824 		}
    825 	if (m == 0) {
    826 		log(LOG_ERR, "rn_delete: couldn't find our annotation\n");
    827 		if (tt->rn_flags & RNF_NORMAL)
    828 			return (0); /* Dangling ref to us */
    829 	}
    830 on1:
    831 	/*
    832 	 * Eliminate us from tree
    833 	 */
    834 	if (tt->rn_flags & RNF_ROOT)
    835 		return (0);
    836 #ifdef RN_DEBUG
    837 	/* Get us out of the creation list */
    838 	for (t = rn_clist; t && t->rn_ybro != tt; t = t->rn_ybro) {}
    839 	if (t) t->rn_ybro = tt->rn_ybro;
    840 	if (rn_debug)
    841 		log(LOG_DEBUG, "%s: Going In:\n", __func__), traverse(head, tt);
    842 #endif
    843 	t = tt->rn_p;
    844 	dupedkey = saved_tt->rn_dupedkey;
    845 	if (dupedkey) {
    846 		/*
    847 		 * Here, tt is the deletion target, and
    848 		 * saved_tt is the head of the dupedkey chain.
    849 		 */
    850 		if (tt == saved_tt) {
    851 			x = dupedkey; x->rn_p = t;
    852 			if (t->rn_l == tt) t->rn_l = x; else t->rn_r = x;
    853 		} else {
    854 			/* find node in front of tt on the chain */
    855 			for (x = p = saved_tt; p && p->rn_dupedkey != tt;)
    856 				p = p->rn_dupedkey;
    857 			if (p) {
    858 				p->rn_dupedkey = tt->rn_dupedkey;
    859 				if (tt->rn_dupedkey)
    860 					tt->rn_dupedkey->rn_p = p;
    861 			} else log(LOG_ERR, "rn_delete: couldn't find us\n");
    862 		}
    863 		t = tt + 1;
    864 		if  (t->rn_flags & RNF_ACTIVE) {
    865 #ifndef RN_DEBUG
    866 			*++x = *t; p = t->rn_p;
    867 #else
    868 			b = t->rn_info; *++x = *t; t->rn_info = b; p = t->rn_p;
    869 #endif
    870 			if (p->rn_l == t) p->rn_l = x; else p->rn_r = x;
    871 			x->rn_l->rn_p = x; x->rn_r->rn_p = x;
    872 		}
    873 		goto out;
    874 	}
    875 	if (t->rn_l == tt) x = t->rn_r; else x = t->rn_l;
    876 	p = t->rn_p;
    877 	if (p->rn_r == t) p->rn_r = x; else p->rn_l = x;
    878 	x->rn_p = p;
    879 	/*
    880 	 * Demote routes attached to us.
    881 	 */
    882 	if (t->rn_mklist) {
    883 		if (x->rn_b >= 0) {
    884 			for (mp = &x->rn_mklist; (m = *mp);)
    885 				mp = &m->rm_mklist;
    886 			*mp = t->rn_mklist;
    887 		} else {
    888 			/* If there are any key,mask pairs in a sibling
    889 			   duped-key chain, some subset will appear sorted
    890 			   in the same order attached to our mklist */
    891 			for (m = t->rn_mklist; m && x; x = x->rn_dupedkey)
    892 				if (m == x->rn_mklist) {
    893 					struct radix_mask *mm = m->rm_mklist;
    894 					x->rn_mklist = 0;
    895 					if (--(m->rm_refs) < 0)
    896 						MKFree(m);
    897 					m = mm;
    898 				}
    899 			if (m)
    900 				log(LOG_ERR, "%s %p at %p\n",
    901 				    "rn_delete: Orphaned Mask", m, x);
    902 		}
    903 	}
    904 	/*
    905 	 * We may be holding an active internal node in the tree.
    906 	 */
    907 	x = tt + 1;
    908 	if (t != x) {
    909 #ifndef RN_DEBUG
    910 		*t = *x;
    911 #else
    912 		b = t->rn_info; *t = *x; t->rn_info = b;
    913 #endif
    914 		t->rn_l->rn_p = t; t->rn_r->rn_p = t;
    915 		p = x->rn_p;
    916 		if (p->rn_l == x) p->rn_l = t; else p->rn_r = t;
    917 	}
    918 out:
    919 #ifdef RN_DEBUG
    920 	if (rn_debug) {
    921 		log(LOG_DEBUG, "%s: Coming Out:\n", __func__),
    922 		    traverse(head, tt);
    923 	}
    924 #endif /* RN_DEBUG */
    925 	tt->rn_flags &= ~RNF_ACTIVE;
    926 	tt[1].rn_flags &= ~RNF_ACTIVE;
    927 	return (tt);
    928 }
    929 
    930 static struct radix_node *
    931 rn_walknext(struct radix_node *rn, rn_printer_t printer, void *arg)
    932 {
    933 	/* If at right child go back up, otherwise, go right */
    934 	while (rn->rn_p->rn_r == rn && (rn->rn_flags & RNF_ROOT) == 0) {
    935 		if (printer != NULL)
    936 			(*printer)(arg, SUBTREE_CLOSE);
    937 		rn = rn->rn_p;
    938 	}
    939 	if (printer)
    940 		rn_nodeprint(rn->rn_p, printer, arg, "");
    941 	/* Find the next *leaf* since next node might vanish, too */
    942 	for (rn = rn->rn_p->rn_r; rn->rn_b >= 0;) {
    943 		if (printer != NULL)
    944 			(*printer)(arg, SUBTREE_OPEN);
    945 		rn = rn->rn_l;
    946 	}
    947 	return rn;
    948 }
    949 
    950 static struct radix_node *
    951 rn_walkfirst(struct radix_node *rn, rn_printer_t printer, void *arg)
    952 {
    953 	/* First time through node, go left */
    954 	while (rn->rn_b >= 0) {
    955 		if (printer != NULL)
    956 			(*printer)(arg, SUBTREE_OPEN);
    957 		rn = rn->rn_l;
    958 	}
    959 	return rn;
    960 }
    961 
    962 int
    963 rn_walktree(
    964 	struct radix_node_head *h,
    965 	int (*f)(struct radix_node *, void *),
    966 	void *w)
    967 {
    968 	int error;
    969 	struct radix_node *base, *next, *rn;
    970 	/*
    971 	 * This gets complicated because we may delete the node
    972 	 * while applying the function f to it, so we need to calculate
    973 	 * the successor node in advance.
    974 	 */
    975 	rn = rn_walkfirst(h->rnh_treetop, NULL, NULL);
    976 	for (;;) {
    977 		base = rn;
    978 		next = rn_walknext(rn, NULL, NULL);
    979 		/* Process leaves */
    980 		while ((rn = base) != NULL) {
    981 			base = rn->rn_dupedkey;
    982 			if (!(rn->rn_flags & RNF_ROOT) && (error = (*f)(rn, w)))
    983 				return (error);
    984 		}
    985 		rn = next;
    986 		if (rn->rn_flags & RNF_ROOT)
    987 			return (0);
    988 	}
    989 	/* NOTREACHED */
    990 }
    991 
    992 int
    993 rn_inithead(head, off)
    994 	void **head;
    995 	int off;
    996 {
    997 	struct radix_node_head *rnh;
    998 
    999 	if (*head)
   1000 		return (1);
   1001 	R_Malloc(rnh, struct radix_node_head *, sizeof (*rnh));
   1002 	if (rnh == 0)
   1003 		return (0);
   1004 	*head = rnh;
   1005 	return rn_inithead0(rnh, off);
   1006 }
   1007 
   1008 int
   1009 rn_inithead0(rnh, off)
   1010 	struct radix_node_head *rnh;
   1011 	int off;
   1012 {
   1013 	struct radix_node *t;
   1014 	struct radix_node *tt;
   1015 	struct radix_node *ttt;
   1016 
   1017 	Bzero(rnh, sizeof (*rnh));
   1018 	t = rn_newpair(rn_zeros, off, rnh->rnh_nodes);
   1019 	ttt = rnh->rnh_nodes + 2;
   1020 	t->rn_r = ttt;
   1021 	t->rn_p = t;
   1022 	tt = t->rn_l;
   1023 	tt->rn_flags = t->rn_flags = RNF_ROOT | RNF_ACTIVE;
   1024 	tt->rn_b = -1 - off;
   1025 	*ttt = *tt;
   1026 	ttt->rn_key = rn_ones;
   1027 	rnh->rnh_addaddr = rn_addroute;
   1028 	rnh->rnh_deladdr = rn_delete;
   1029 	rnh->rnh_matchaddr = rn_match;
   1030 	rnh->rnh_lookup = rn_lookup;
   1031 	rnh->rnh_walktree = rn_walktree;
   1032 	rnh->rnh_treetop = t;
   1033 	return (1);
   1034 }
   1035 
   1036 void
   1037 rn_init()
   1038 {
   1039 	char *cp, *cplim;
   1040 #ifdef _KERNEL
   1041 	static int initialized;
   1042 	__link_set_decl(domains, struct domain);
   1043 	struct domain *const *dpp;
   1044 
   1045 	if (initialized)
   1046 		return;
   1047 	initialized = 1;
   1048 
   1049 	__link_set_foreach(dpp, domains) {
   1050 		if ((*dpp)->dom_maxrtkey > max_keylen)
   1051 			max_keylen = (*dpp)->dom_maxrtkey;
   1052 	}
   1053 #ifdef INET
   1054 	encap_setkeylen();
   1055 #endif
   1056 #endif
   1057 	if (max_keylen == 0) {
   1058 		log(LOG_ERR,
   1059 		    "rn_init: radix functions require max_keylen be set\n");
   1060 		return;
   1061 	}
   1062 	R_Malloc(rn_zeros, char *, 3 * max_keylen);
   1063 	if (rn_zeros == NULL)
   1064 		panic("rn_init");
   1065 	Bzero(rn_zeros, 3 * max_keylen);
   1066 	rn_ones = cp = rn_zeros + max_keylen;
   1067 	addmask_key = cplim = rn_ones + max_keylen;
   1068 	while (cp < cplim)
   1069 		*cp++ = -1;
   1070 	if (rn_inithead((void *)&mask_rnhead, 0) == 0)
   1071 		panic("rn_init 2");
   1072 }
   1073