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