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