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