xref: /openbsd-src/sys/net/radix.c (revision 8500990981f885cbe5e6a4958549cacc238b5ae6)
1 /*	$OpenBSD: radix.c,v 1.11 2003/08/27 00:33:34 henric 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 = 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 						return (m->rm_leaf);
292 				} else {
293 					off = min(t->rn_off, matched_off);
294 					x = rn_search_m(v, t, m->rm_mask);
295 					while (x && x->rn_mask != m->rm_mask)
296 						x = x->rn_dupedkey;
297 					if (x && rn_satsifies_leaf(v, x, off))
298 						    return x;
299 				}
300 			} while ((m = m->rm_mklist) != NULL);
301 		}
302 	} while (t != top);
303 	return 0;
304 }
305 
306 #ifdef RN_DEBUG
307 int	rn_nodenum;
308 struct	radix_node *rn_clist;
309 int	rn_saveinfo;
310 int	rn_debug =  1;
311 #endif
312 
313 struct radix_node *
314 rn_newpair(v, b, nodes)
315 	void *v;
316 	int b;
317 	struct radix_node nodes[2];
318 {
319 	register struct radix_node *tt = nodes, *t = tt + 1;
320 	t->rn_b = b;
321 	t->rn_bmask = 0x80 >> (b & 7);
322 	t->rn_l = tt;
323 	t->rn_off = b >> 3;
324 	tt->rn_b = -1;
325 	tt->rn_key = (caddr_t)v;
326 	tt->rn_p = t;
327 	tt->rn_flags = t->rn_flags = RNF_ACTIVE;
328 #ifdef RN_DEBUG
329 	tt->rn_info = rn_nodenum++;
330 	t->rn_info = rn_nodenum++;
331 	tt->rn_twin = t;
332 	tt->rn_ybro = rn_clist;
333 	rn_clist = tt;
334 #endif
335 	return t;
336 }
337 
338 struct radix_node *
339 rn_insert(v_arg, head, dupentry, nodes)
340 	void *v_arg;
341 	struct radix_node_head *head;
342 	int *dupentry;
343 	struct radix_node nodes[2];
344 {
345 	caddr_t v = v_arg;
346 	struct radix_node *top = head->rnh_treetop;
347 	int head_off = top->rn_off, vlen = (int)*((u_char *)v);
348 	register struct radix_node *t = rn_search(v_arg, top);
349 	register caddr_t cp = v + head_off;
350 	register int b;
351 	struct radix_node *tt;
352 	/*
353 	 * Find first bit at which v and t->rn_key differ
354 	 */
355     {
356 	register caddr_t cp2 = t->rn_key + head_off;
357 	register int cmp_res;
358 	caddr_t cplim = v + vlen;
359 
360 	while (cp < cplim)
361 		if (*cp2++ != *cp++)
362 			goto on1;
363 	*dupentry = 1;
364 	return t;
365 on1:
366 	*dupentry = 0;
367 	cmp_res = (cp[-1] ^ cp2[-1]) & 0xff;
368 	for (b = (cp - v) << 3; cmp_res; b--)
369 		cmp_res >>= 1;
370     }
371     {
372 	register struct radix_node *p, *x = top;
373 	cp = v;
374 	do {
375 		p = x;
376 		if (cp[x->rn_off] & x->rn_bmask)
377 			x = x->rn_r;
378 		else
379 			x = x->rn_l;
380 	} while (b > (unsigned) x->rn_b); /* x->rn_b < b && x->rn_b >= 0 */
381 #ifdef RN_DEBUG
382 	if (rn_debug)
383 		log(LOG_DEBUG, "rn_insert: Going In:\n"), traverse(p);
384 #endif
385 	t = rn_newpair(v_arg, b, nodes);
386 	tt = t->rn_l;
387 	if ((cp[p->rn_off] & p->rn_bmask) == 0)
388 		p->rn_l = t;
389 	else
390 		p->rn_r = t;
391 	x->rn_p = t;
392 	t->rn_p = p; /* frees x, p as temp vars below */
393 	if ((cp[t->rn_off] & t->rn_bmask) == 0) {
394 		t->rn_r = x;
395 	} else {
396 		t->rn_r = tt;
397 		t->rn_l = x;
398 	}
399 #ifdef RN_DEBUG
400 	if (rn_debug)
401 		log(LOG_DEBUG, "rn_insert: Coming Out:\n"), traverse(p);
402 #endif
403     }
404 	return (tt);
405 }
406 
407 struct radix_node *
408 rn_addmask(n_arg, search, skip)
409 	int search, skip;
410 	void *n_arg;
411 {
412 	caddr_t netmask = (caddr_t)n_arg;
413 	register struct radix_node *x;
414 	register caddr_t cp, cplim;
415 	register int b = 0, mlen, j;
416 	int maskduplicated, m0, isnormal;
417 	struct radix_node *saved_x;
418 	static int last_zeroed = 0;
419 
420 	if ((mlen = *(u_char *)netmask) > max_keylen)
421 		mlen = max_keylen;
422 	if (skip == 0)
423 		skip = 1;
424 	if (mlen <= skip)
425 		return (mask_rnhead->rnh_nodes);
426 	if (skip > 1)
427 		Bcopy(rn_ones + 1, addmask_key + 1, skip - 1);
428 	if ((m0 = mlen) > skip)
429 		Bcopy(netmask + skip, addmask_key + skip, mlen - skip);
430 	/*
431 	 * Trim trailing zeroes.
432 	 */
433 	for (cp = addmask_key + mlen; (cp > addmask_key) && cp[-1] == 0;)
434 		cp--;
435 	mlen = cp - addmask_key;
436 	if (mlen <= skip) {
437 		if (m0 >= last_zeroed)
438 			last_zeroed = mlen;
439 		return (mask_rnhead->rnh_nodes);
440 	}
441 	if (m0 < last_zeroed)
442 		Bzero(addmask_key + m0, last_zeroed - m0);
443 	*addmask_key = last_zeroed = mlen;
444 	x = rn_search(addmask_key, rn_masktop);
445 	if (Bcmp(addmask_key, x->rn_key, mlen) != 0)
446 		x = 0;
447 	if (x || search)
448 		return (x);
449 	R_Malloc(x, struct radix_node *, max_keylen + 2 * sizeof (*x));
450 	if ((saved_x = x) == 0)
451 		return (0);
452 	Bzero(x, max_keylen + 2 * sizeof (*x));
453 	netmask = cp = (caddr_t)(x + 2);
454 	Bcopy(addmask_key, cp, mlen);
455 	x = rn_insert(cp, mask_rnhead, &maskduplicated, x);
456 	if (maskduplicated) {
457 		log(LOG_ERR, "rn_addmask: mask impossibly already in tree");
458 		Free(saved_x);
459 		return (x);
460 	}
461 	/*
462 	 * Calculate index of mask, and check for normalcy.
463 	 */
464 	cplim = netmask + mlen;
465 	isnormal = 1;
466 	for (cp = netmask + skip; (cp < cplim) && *(u_char *)cp == 0xff;)
467 		cp++;
468 	if (cp != cplim) {
469 		for (j = 0x80; (j & *cp) != 0; j >>= 1)
470 			b++;
471 		if (*cp != normal_chars[b] || cp != (cplim - 1))
472 			isnormal = 0;
473 	}
474 	b += (cp - netmask) << 3;
475 	x->rn_b = -1 - b;
476 	if (isnormal)
477 		x->rn_flags |= RNF_NORMAL;
478 	return (x);
479 }
480 
481 static int	/* XXX: arbitrary ordering for non-contiguous masks */
482 rn_lexobetter(m_arg, n_arg)
483 	void *m_arg, *n_arg;
484 {
485 	register u_char *mp = m_arg, *np = n_arg, *lim;
486 
487 	if (*mp > *np)
488 		return 1;  /* not really, but need to check longer one first */
489 	if (*mp == *np)
490 		for (lim = mp + *mp; mp < lim;)
491 			if (*mp++ > *np++)
492 				return 1;
493 	return 0;
494 }
495 
496 static struct radix_mask *
497 rn_new_radix_mask(tt, next)
498 	register struct radix_node *tt;
499 	register struct radix_mask *next;
500 {
501 	register struct radix_mask *m;
502 
503 	MKGet(m);
504 	if (m == 0) {
505 		log(LOG_ERR, "Mask for route not entered\n");
506 		return (0);
507 	}
508 	Bzero(m, sizeof *m);
509 	m->rm_b = tt->rn_b;
510 	m->rm_flags = tt->rn_flags;
511 	if (tt->rn_flags & RNF_NORMAL)
512 		m->rm_leaf = tt;
513 	else
514 		m->rm_mask = tt->rn_mask;
515 	m->rm_mklist = next;
516 	tt->rn_mklist = m;
517 	return m;
518 }
519 
520 struct radix_node *
521 rn_addroute(v_arg, n_arg, head, treenodes)
522 	void *v_arg, *n_arg;
523 	struct radix_node_head *head;
524 	struct radix_node treenodes[2];
525 {
526 	caddr_t v = (caddr_t)v_arg, netmask = (caddr_t)n_arg;
527 	register struct radix_node *t, *x = NULL, *tt;
528 	struct radix_node *saved_tt, *top = head->rnh_treetop;
529 	short b = 0, b_leaf = 0;
530 	int keyduplicated;
531 	caddr_t mmask;
532 	struct radix_mask *m, **mp;
533 
534 	/*
535 	 * In dealing with non-contiguous masks, there may be
536 	 * many different routes which have the same mask.
537 	 * We will find it useful to have a unique pointer to
538 	 * the mask to speed avoiding duplicate references at
539 	 * nodes and possibly save time in calculating indices.
540 	 */
541 	if (netmask)  {
542 		if ((x = rn_addmask(netmask, 0, top->rn_off)) == 0)
543 			return (0);
544 		b_leaf = x->rn_b;
545 		b = -1 - x->rn_b;
546 		netmask = x->rn_key;
547 	}
548 	/*
549 	 * Deal with duplicated keys: attach node to previous instance
550 	 */
551 	saved_tt = tt = rn_insert(v, head, &keyduplicated, treenodes);
552 	if (keyduplicated) {
553 		for (t = tt; tt; t = tt, tt = tt->rn_dupedkey) {
554 			if (tt->rn_mask == netmask)
555 				return (0);
556 			if (netmask == 0 ||
557 			    (tt->rn_mask &&
558 			     ((b_leaf < tt->rn_b) || /* index(netmask) > node */
559 			       rn_refines(netmask, tt->rn_mask) ||
560 			       rn_lexobetter(netmask, tt->rn_mask))))
561 				break;
562 		}
563 		/*
564 		 * If the mask is not duplicated, we wouldn't
565 		 * find it among possible duplicate key entries
566 		 * anyway, so the above test doesn't hurt.
567 		 *
568 		 * We sort the masks for a duplicated key the same way as
569 		 * in a masklist -- most specific to least specific.
570 		 * This may require the unfortunate nuisance of relocating
571 		 * the head of the list.
572 		 */
573 		if (tt == saved_tt) {
574 			struct	radix_node *xx = x;
575 			/* link in at head of list */
576 			(tt = treenodes)->rn_dupedkey = t;
577 			tt->rn_flags = t->rn_flags;
578 			tt->rn_p = x = t->rn_p;
579 			if (x->rn_l == t)
580 				x->rn_l = tt;
581 			else
582 				x->rn_r = tt;
583 			saved_tt = tt;
584 			x = xx;
585 		} else {
586 			(tt = treenodes)->rn_dupedkey = t->rn_dupedkey;
587 			t->rn_dupedkey = tt;
588 		}
589 #ifdef RN_DEBUG
590 		t=tt+1;
591 		tt->rn_info = rn_nodenum++;
592 		t->rn_info = rn_nodenum++;
593 		tt->rn_twin = t;
594 		tt->rn_ybro = rn_clist;
595 		rn_clist = tt;
596 #endif
597 		tt->rn_key = (caddr_t) v;
598 		tt->rn_b = -1;
599 		tt->rn_flags = RNF_ACTIVE;
600 	}
601 	/*
602 	 * Put mask in tree.
603 	 */
604 	if (netmask) {
605 		tt->rn_mask = netmask;
606 		tt->rn_b = x->rn_b;
607 		tt->rn_flags |= x->rn_flags & RNF_NORMAL;
608 	}
609 	t = saved_tt->rn_p;
610 	if (keyduplicated)
611 		goto on2;
612 	b_leaf = -1 - t->rn_b;
613 	if (t->rn_r == saved_tt)
614 		x = t->rn_l;
615 	else
616 		x = t->rn_r;
617 	/* Promote general routes from below */
618 	if (x->rn_b < 0) {
619 	    for (mp = &t->rn_mklist; x; x = x->rn_dupedkey)
620 		if (x->rn_mask && (x->rn_b >= b_leaf) && x->rn_mklist == 0) {
621 			*mp = m = rn_new_radix_mask(x, 0);
622 			if (m)
623 				mp = &m->rm_mklist;
624 		}
625 	} else if (x->rn_mklist) {
626 		/*
627 		 * Skip over masks whose index is > that of new node
628 		 */
629 		for (mp = &x->rn_mklist; (m = *mp) != NULL; mp = &m->rm_mklist)
630 			if (m->rm_b >= b_leaf)
631 				break;
632 		t->rn_mklist = m;
633 		*mp = 0;
634 	}
635 on2:
636 	/* Add new route to highest possible ancestor's list */
637 	if ((netmask == 0) || (b > t->rn_b ))
638 		return tt; /* can't lift at all */
639 	b_leaf = tt->rn_b;
640 	do {
641 		x = t;
642 		t = t->rn_p;
643 	} while (b <= t->rn_b && x != top);
644 	/*
645 	 * Search through routes associated with node to
646 	 * insert new route according to index.
647 	 * Need same criteria as when sorting dupedkeys to avoid
648 	 * double loop on deletion.
649 	 */
650 	for (mp = &x->rn_mklist; (m = *mp) != NULL; mp = &m->rm_mklist) {
651 		if (m->rm_b < b_leaf)
652 			continue;
653 		if (m->rm_b > b_leaf)
654 			break;
655 		if (m->rm_flags & RNF_NORMAL) {
656 			mmask = m->rm_leaf->rn_mask;
657 			if (tt->rn_flags & RNF_NORMAL) {
658 				log(LOG_ERR, "Non-unique normal route, "
659 				    "mask not entered\n");
660 				return tt;
661 			}
662 		} else
663 			mmask = m->rm_mask;
664 		if (mmask == netmask) {
665 			m->rm_refs++;
666 			tt->rn_mklist = m;
667 			return tt;
668 		}
669 		if (rn_refines(netmask, mmask) || rn_lexobetter(netmask, mmask))
670 			break;
671 	}
672 	*mp = rn_new_radix_mask(tt, *mp);
673 	return tt;
674 }
675 
676 struct radix_node *
677 rn_delete(v_arg, netmask_arg, head)
678 	void *v_arg, *netmask_arg;
679 	struct radix_node_head *head;
680 {
681 	register struct radix_node *t, *p, *x, *tt;
682 	struct radix_mask *m, *saved_m, **mp;
683 	struct radix_node *dupedkey, *saved_tt, *top;
684 	caddr_t v, netmask;
685 	int b, head_off, vlen;
686 
687 	v = v_arg;
688 	netmask = netmask_arg;
689 	x = head->rnh_treetop;
690 	tt = rn_search(v, x);
691 	head_off = x->rn_off;
692 	vlen =  *(u_char *)v;
693 	saved_tt = tt;
694 	top = x;
695 	if (tt == 0 ||
696 	    Bcmp(v + head_off, tt->rn_key + head_off, vlen - head_off))
697 		return (0);
698 	/*
699 	 * Delete our route from mask lists.
700 	 */
701 	if (netmask) {
702 		if ((x = rn_addmask(netmask, 1, head_off)) == 0)
703 			return (0);
704 		netmask = x->rn_key;
705 		while (tt->rn_mask != netmask)
706 			if ((tt = tt->rn_dupedkey) == 0)
707 				return (0);
708 	}
709 	if (tt->rn_mask == 0 || (saved_m = m = tt->rn_mklist) == 0)
710 		goto on1;
711 	if (tt->rn_flags & RNF_NORMAL) {
712 		if (m->rm_leaf != tt || m->rm_refs > 0) {
713 			log(LOG_ERR, "rn_delete: inconsistent annotation\n");
714 			return 0;  /* dangling ref could cause disaster */
715 		}
716 	} else {
717 		if (m->rm_mask != tt->rn_mask) {
718 			log(LOG_ERR, "rn_delete: inconsistent annotation\n");
719 			goto on1;
720 		}
721 		if (--m->rm_refs >= 0)
722 			goto on1;
723 	}
724 	b = -1 - tt->rn_b;
725 	t = saved_tt->rn_p;
726 	if (b > t->rn_b)
727 		goto on1; /* Wasn't lifted at all */
728 	do {
729 		x = t;
730 		t = t->rn_p;
731 	} while (b <= t->rn_b && x != top);
732 	for (mp = &x->rn_mklist; (m = *mp) != NULL; mp = &m->rm_mklist)
733 		if (m == saved_m) {
734 			*mp = m->rm_mklist;
735 			MKFree(m);
736 			break;
737 		}
738 	if (m == 0) {
739 		log(LOG_ERR, "rn_delete: couldn't find our annotation\n");
740 		if (tt->rn_flags & RNF_NORMAL)
741 			return (0); /* Dangling ref to us */
742 	}
743 on1:
744 	/*
745 	 * Eliminate us from tree
746 	 */
747 	if (tt->rn_flags & RNF_ROOT)
748 		return (0);
749 #ifdef RN_DEBUG
750 	/* Get us out of the creation list */
751 	for (t = rn_clist; t && t->rn_ybro != tt; t = t->rn_ybro)
752 		;
753 	if (t) t->rn_ybro = tt->rn_ybro;
754 #endif
755 	t = tt->rn_p;
756 	if ((dupedkey = saved_tt->rn_dupedkey) != 0) {
757 		if (tt == saved_tt) {
758 			x = dupedkey;
759 			x->rn_p = t;
760 			if (t->rn_l == tt)
761 				t->rn_l = x;
762 			else
763 				t->rn_r = x;
764 		} else {
765 			for (x = p = saved_tt; p && p->rn_dupedkey != tt;)
766 				p = p->rn_dupedkey;
767 			if (p)
768 				p->rn_dupedkey = tt->rn_dupedkey;
769 			else
770 				log(LOG_ERR, "rn_delete: couldn't find us\n");
771 		}
772 		t = tt + 1;
773 		if  (t->rn_flags & RNF_ACTIVE) {
774 #ifndef RN_DEBUG
775 			*++x = *t;
776 			p = t->rn_p;
777 #else
778 			b = t->rn_info;
779 			*++x = *t;
780 			t->rn_info = b;
781 			p = t->rn_p;
782 #endif
783 			if (p->rn_l == t)
784 				p->rn_l = x;
785 			else
786 				p->rn_r = x;
787 			x->rn_l->rn_p = x;
788 			x->rn_r->rn_p = x;
789 		}
790 		goto out;
791 	}
792 	if (t->rn_l == tt)
793 		x = t->rn_r;
794 	else
795 		x = t->rn_l;
796 	p = t->rn_p;
797 	if (p->rn_r == t)
798 		p->rn_r = x;
799 	else
800 		p->rn_l = x;
801 	x->rn_p = p;
802 	/*
803 	 * Demote routes attached to us.
804 	 */
805 	if (t->rn_mklist) {
806 		if (x->rn_b >= 0) {
807 			for (mp = &x->rn_mklist; (m = *mp) != NULL;)
808 				mp = &m->rm_mklist;
809 			*mp = t->rn_mklist;
810 		} else {
811 			/* If there are any key,mask pairs in a sibling
812 			   duped-key chain, some subset will appear sorted
813 			   in the same order attached to our mklist */
814 			for (m = t->rn_mklist; m && x; x = x->rn_dupedkey)
815 				if (m == x->rn_mklist) {
816 					struct radix_mask *mm = m->rm_mklist;
817 					x->rn_mklist = 0;
818 					if (--(m->rm_refs) < 0)
819 						MKFree(m);
820 					m = mm;
821 				}
822 			if (m)
823 				log(LOG_ERR, "%s %p at %p\n",
824 					    "rn_delete: Orphaned Mask", m, x);
825 		}
826 	}
827 	/*
828 	 * We may be holding an active internal node in the tree.
829 	 */
830 	x = tt + 1;
831 	if (t != x) {
832 #ifndef RN_DEBUG
833 		*t = *x;
834 #else
835 		b = t->rn_info;
836 		*t = *x;
837 		t->rn_info = b;
838 #endif
839 		t->rn_l->rn_p = t;
840 		t->rn_r->rn_p = t;
841 		p = x->rn_p;
842 		if (p->rn_l == x)
843 			p->rn_l = t;
844 		else
845 			p->rn_r = t;
846 	}
847 out:
848 	tt->rn_flags &= ~RNF_ACTIVE;
849 	tt[1].rn_flags &= ~RNF_ACTIVE;
850 	return (tt);
851 }
852 
853 int
854 rn_walktree(h, f, w)
855 	struct radix_node_head *h;
856 	register int (*f)(struct radix_node *, void *);
857 	void *w;
858 {
859 	int error;
860 	struct radix_node *base, *next;
861 	register struct radix_node *rn = h->rnh_treetop;
862 	/*
863 	 * This gets complicated because we may delete the node
864 	 * while applying the function f to it, so we need to calculate
865 	 * the successor node in advance.
866 	 */
867 	/* First time through node, go left */
868 	while (rn->rn_b >= 0)
869 		rn = rn->rn_l;
870 	for (;;) {
871 		base = rn;
872 		/* If at right child go back up, otherwise, go right */
873 		while (rn->rn_p->rn_r == rn && (rn->rn_flags & RNF_ROOT) == 0)
874 			rn = rn->rn_p;
875 		/* Find the next *leaf* since next node might vanish, too */
876 		for (rn = rn->rn_p->rn_r; rn->rn_b >= 0;)
877 			rn = rn->rn_l;
878 		next = rn;
879 		/* Process leaves */
880 		while ((rn = base) != NULL) {
881 			base = rn->rn_dupedkey;
882 			if (!(rn->rn_flags & RNF_ROOT) && (error = (*f)(rn, w)))
883 				return (error);
884 		}
885 		rn = next;
886 		if (rn->rn_flags & RNF_ROOT)
887 			return (0);
888 	}
889 	/* NOTREACHED */
890 }
891 
892 int
893 rn_inithead(head, off)
894 	void **head;
895 	int off;
896 {
897 	register struct radix_node_head *rnh;
898 	register struct radix_node *t, *tt, *ttt;
899 	if (*head)
900 		return (1);
901 	R_Malloc(rnh, struct radix_node_head *, sizeof (*rnh));
902 	if (rnh == 0)
903 		return (0);
904 	Bzero(rnh, sizeof (*rnh));
905 	*head = rnh;
906 	t = rn_newpair(rn_zeros, off, rnh->rnh_nodes);
907 	ttt = rnh->rnh_nodes + 2;
908 	t->rn_r = ttt;
909 	t->rn_p = t;
910 	tt = t->rn_l;
911 	tt->rn_flags = t->rn_flags = RNF_ROOT | RNF_ACTIVE;
912 	tt->rn_b = -1 - off;
913 	*ttt = *tt;
914 	ttt->rn_key = rn_ones;
915 	rnh->rnh_addaddr = rn_addroute;
916 	rnh->rnh_deladdr = rn_delete;
917 	rnh->rnh_matchaddr = rn_match;
918 	rnh->rnh_lookup = rn_lookup;
919 	rnh->rnh_walktree = rn_walktree;
920 	rnh->rnh_treetop = t;
921 	return (1);
922 }
923 
924 void
925 rn_init()
926 {
927 	char *cp, *cplim;
928 #ifdef _KERNEL
929 	struct domain *dom;
930 
931 	for (dom = domains; dom; dom = dom->dom_next)
932 		if (dom->dom_maxrtkey > max_keylen)
933 			max_keylen = dom->dom_maxrtkey;
934 #endif
935 	if (max_keylen == 0) {
936 		log(LOG_ERR,
937 		    "rn_init: radix functions require max_keylen be set\n");
938 		return;
939 	}
940 	R_Malloc(rn_zeros, char *, 3 * max_keylen);
941 	if (rn_zeros == NULL)
942 		panic("rn_init");
943 	Bzero(rn_zeros, 3 * max_keylen);
944 	rn_ones = cp = rn_zeros + max_keylen;
945 	addmask_key = cplim = rn_ones + max_keylen;
946 	while (cp < cplim)
947 		*cp++ = -1;
948 	if (rn_inithead((void **)&mask_rnhead, 0) == 0)
949 		panic("rn_init 2");
950 }
951