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