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