xref: /freebsd/sys/net/radix.c (revision 7773002178c8dbc52b44e4d705f07706409af8e4)
1 /*
2  * Copyright (c) 1988, 1989, 1993
3  *	The Regents of the University of California.  All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 3. All advertising materials mentioning features or use of this software
14  *    must display the following acknowledgement:
15  *	This product includes software developed by the University of
16  *	California, Berkeley and its contributors.
17  * 4. Neither the name of the University nor the names of its contributors
18  *    may be used to endorse or promote products derived from this software
19  *    without specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  *
33  *	@(#)radix.c	8.5 (Berkeley) 5/19/95
34  * $FreeBSD$
35  */
36 
37 /*
38  * Routines to build and maintain radix trees for routing lookups.
39  */
40 #ifndef _RADIX_H_
41 #include <sys/param.h>
42 #ifdef	_KERNEL
43 #include <sys/lock.h>
44 #include <sys/mutex.h>
45 #include <sys/systm.h>
46 #include <sys/malloc.h>
47 #include <sys/domain.h>
48 #else
49 #include <stdlib.h>
50 #endif
51 #include <sys/syslog.h>
52 #include <net/radix.h>
53 #endif
54 
55 static int	rn_walktree_from(struct radix_node_head *h, void *a, void *m,
56 		    walktree_f_t *f, void *w);
57 static int rn_walktree(struct radix_node_head *, walktree_f_t *, void *);
58 static struct radix_node
59 	 *rn_insert(void *, struct radix_node_head *, int *,
60 	     struct radix_node [2]),
61 	 *rn_newpair(void *, int, struct radix_node[2]),
62 	 *rn_search(void *, struct radix_node *),
63 	 *rn_search_m(void *, struct radix_node *, void *);
64 
65 static int	max_keylen;
66 static struct radix_mask *rn_mkfreelist;
67 static struct radix_node_head *mask_rnhead;
68 static char *addmask_key;
69 static char normal_chars[] = {0, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe, -1};
70 static char *rn_zeros, *rn_ones;
71 
72 #define rn_masktop (mask_rnhead->rnh_treetop)
73 #undef Bcmp
74 #define Bcmp(a, b, l) \
75 	((l) == 0 ? 0 : bcmp((caddr_t)(a), (caddr_t)(b), (u_long)(l)))
76 
77 static int	rn_lexobetter(void *m_arg, void *n_arg);
78 static struct radix_mask *
79 		rn_new_radix_mask(struct radix_node *tt,
80 		    struct radix_mask *next);
81 static int	rn_satisfies_leaf(char *trial, struct radix_node *leaf,
82 		    int skip);
83 
84 /*
85  * The data structure for the keys is a radix tree with one way
86  * branching removed.  The index rn_bit at an internal node n represents a bit
87  * position to be tested.  The tree is arranged so that all descendants
88  * of a node n have keys whose bits all agree up to position rn_bit - 1.
89  * (We say the index of n is rn_bit.)
90  *
91  * There is at least one descendant which has a one bit at position rn_bit,
92  * and at least one with a zero there.
93  *
94  * A route is determined by a pair of key and mask.  We require that the
95  * bit-wise logical and of the key and mask to be the key.
96  * We define the index of a route to associated with the mask to be
97  * the first bit number in the mask where 0 occurs (with bit number 0
98  * representing the highest order bit).
99  *
100  * We say a mask is normal if every bit is 0, past the index of the mask.
101  * If a node n has a descendant (k, m) with index(m) == index(n) == rn_bit,
102  * and m is a normal mask, then the route applies to every descendant of n.
103  * If the index(m) < rn_bit, this implies the trailing last few bits of k
104  * before bit b are all 0, (and hence consequently true of every descendant
105  * of n), so the route applies to all descendants of the node as well.
106  *
107  * Similar logic shows that a non-normal mask m such that
108  * index(m) <= index(n) could potentially apply to many children of n.
109  * Thus, for each non-host route, we attach its mask to a list at an internal
110  * node as high in the tree as we can go.
111  *
112  * The present version of the code makes use of normal routes in short-
113  * circuiting an explict mask and compare operation when testing whether
114  * a key satisfies a normal route, and also in remembering the unique leaf
115  * that governs a subtree.
116  */
117 
118 static struct radix_node *
119 rn_search(v_arg, head)
120 	void *v_arg;
121 	struct radix_node *head;
122 {
123 	register struct radix_node *x;
124 	register caddr_t v;
125 
126 	for (x = head, v = v_arg; x->rn_bit >= 0;) {
127 		if (x->rn_bmask & v[x->rn_offset])
128 			x = x->rn_right;
129 		else
130 			x = x->rn_left;
131 	}
132 	return (x);
133 }
134 
135 static struct radix_node *
136 rn_search_m(v_arg, head, m_arg)
137 	struct radix_node *head;
138 	void *v_arg, *m_arg;
139 {
140 	register struct radix_node *x;
141 	register caddr_t v = v_arg, m = m_arg;
142 
143 	for (x = head; x->rn_bit >= 0;) {
144 		if ((x->rn_bmask & m[x->rn_offset]) &&
145 		    (x->rn_bmask & v[x->rn_offset]))
146 			x = x->rn_right;
147 		else
148 			x = x->rn_left;
149 	}
150 	return x;
151 }
152 
153 int
154 rn_refines(m_arg, n_arg)
155 	void *m_arg, *n_arg;
156 {
157 	register caddr_t m = m_arg, n = n_arg;
158 	register caddr_t lim, lim2 = lim = n + *(u_char *)n;
159 	int longer = (*(u_char *)n++) - (int)(*(u_char *)m++);
160 	int masks_are_equal = 1;
161 
162 	if (longer > 0)
163 		lim -= longer;
164 	while (n < lim) {
165 		if (*n & ~(*m))
166 			return 0;
167 		if (*n++ != *m++)
168 			masks_are_equal = 0;
169 	}
170 	while (n < lim2)
171 		if (*n++)
172 			return 0;
173 	if (masks_are_equal && (longer < 0))
174 		for (lim2 = m - longer; m < lim2; )
175 			if (*m++)
176 				return 1;
177 	return (!masks_are_equal);
178 }
179 
180 struct radix_node *
181 rn_lookup(v_arg, m_arg, head)
182 	void *v_arg, *m_arg;
183 	struct radix_node_head *head;
184 {
185 	register struct radix_node *x;
186 	caddr_t netmask = 0;
187 
188 	if (m_arg) {
189 		x = rn_addmask(m_arg, 1, head->rnh_treetop->rn_offset);
190 		if (x == 0)
191 			return (0);
192 		netmask = x->rn_key;
193 	}
194 	x = rn_match(v_arg, head);
195 	if (x && netmask) {
196 		while (x && x->rn_mask != netmask)
197 			x = x->rn_dupedkey;
198 	}
199 	return x;
200 }
201 
202 static int
203 rn_satisfies_leaf(trial, leaf, skip)
204 	char *trial;
205 	register struct radix_node *leaf;
206 	int skip;
207 {
208 	register char *cp = trial, *cp2 = leaf->rn_key, *cp3 = leaf->rn_mask;
209 	char *cplim;
210 	int length = min(*(u_char *)cp, *(u_char *)cp2);
211 
212 	if (cp3 == 0)
213 		cp3 = rn_ones;
214 	else
215 		length = min(length, *(u_char *)cp3);
216 	cplim = cp + length; cp3 += skip; cp2 += skip;
217 	for (cp += skip; cp < cplim; cp++, cp2++, cp3++)
218 		if ((*cp ^ *cp2) & *cp3)
219 			return 0;
220 	return 1;
221 }
222 
223 struct radix_node *
224 rn_match(v_arg, head)
225 	void *v_arg;
226 	struct radix_node_head *head;
227 {
228 	caddr_t v = v_arg;
229 	register struct radix_node *t = head->rnh_treetop, *x;
230 	register caddr_t cp = v, cp2;
231 	caddr_t cplim;
232 	struct radix_node *saved_t, *top = t;
233 	int off = t->rn_offset, vlen = *(u_char *)cp, matched_off;
234 	register int test, b, rn_bit;
235 
236 	/*
237 	 * Open code rn_search(v, top) to avoid overhead of extra
238 	 * subroutine call.
239 	 */
240 	for (; t->rn_bit >= 0; ) {
241 		if (t->rn_bmask & cp[t->rn_offset])
242 			t = t->rn_right;
243 		else
244 			t = t->rn_left;
245 	}
246 	/*
247 	 * See if we match exactly as a host destination
248 	 * or at least learn how many bits match, for normal mask finesse.
249 	 *
250 	 * It doesn't hurt us to limit how many bytes to check
251 	 * to the length of the mask, since if it matches we had a genuine
252 	 * match and the leaf we have is the most specific one anyway;
253 	 * if it didn't match with a shorter length it would fail
254 	 * with a long one.  This wins big for class B&C netmasks which
255 	 * are probably the most common case...
256 	 */
257 	if (t->rn_mask)
258 		vlen = *(u_char *)t->rn_mask;
259 	cp += off; cp2 = t->rn_key + off; cplim = v + vlen;
260 	for (; cp < cplim; cp++, cp2++)
261 		if (*cp != *cp2)
262 			goto on1;
263 	/*
264 	 * This extra grot is in case we are explicitly asked
265 	 * to look up the default.  Ugh!
266 	 *
267 	 * Never return the root node itself, it seems to cause a
268 	 * lot of confusion.
269 	 */
270 	if (t->rn_flags & RNF_ROOT)
271 		t = t->rn_dupedkey;
272 	return t;
273 on1:
274 	test = (*cp ^ *cp2) & 0xff; /* find first bit that differs */
275 	for (b = 7; (test >>= 1) > 0;)
276 		b--;
277 	matched_off = cp - v;
278 	b += matched_off << 3;
279 	rn_bit = -1 - b;
280 	/*
281 	 * If there is a host route in a duped-key chain, it will be first.
282 	 */
283 	if ((saved_t = t)->rn_mask == 0)
284 		t = t->rn_dupedkey;
285 	for (; t; t = t->rn_dupedkey)
286 		/*
287 		 * Even if we don't match exactly as a host,
288 		 * we may match if the leaf we wound up at is
289 		 * a route to a net.
290 		 */
291 		if (t->rn_flags & RNF_NORMAL) {
292 			if (rn_bit <= t->rn_bit)
293 				return t;
294 		} else if (rn_satisfies_leaf(v, t, matched_off))
295 				return t;
296 	t = saved_t;
297 	/* start searching up the tree */
298 	do {
299 		register struct radix_mask *m;
300 		t = t->rn_parent;
301 		m = t->rn_mklist;
302 		/*
303 		 * If non-contiguous masks ever become important
304 		 * we can restore the masking and open coding of
305 		 * the search and satisfaction test and put the
306 		 * calculation of "off" back before the "do".
307 		 */
308 		while (m) {
309 			if (m->rm_flags & RNF_NORMAL) {
310 				if (rn_bit <= m->rm_bit)
311 					return (m->rm_leaf);
312 			} else {
313 				off = min(t->rn_offset, matched_off);
314 				x = rn_search_m(v, t, m->rm_mask);
315 				while (x && x->rn_mask != m->rm_mask)
316 					x = x->rn_dupedkey;
317 				if (x && rn_satisfies_leaf(v, x, off))
318 					return x;
319 			}
320 			m = m->rm_mklist;
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 static struct radix_node *
334 rn_newpair(v, b, nodes)
335 	void *v;
336 	int b;
337 	struct radix_node nodes[2];
338 {
339 	register struct radix_node *tt = nodes, *t = tt + 1;
340 	t->rn_bit = b;
341 	t->rn_bmask = 0x80 >> (b & 7);
342 	t->rn_left = tt;
343 	t->rn_offset = b >> 3;
344 	tt->rn_bit = -1;
345 	tt->rn_key = (caddr_t)v;
346 	tt->rn_parent = t;
347 	tt->rn_flags = t->rn_flags = RNF_ACTIVE;
348 	tt->rn_mklist = t->rn_mklist = 0;
349 #ifdef RN_DEBUG
350 	tt->rn_info = rn_nodenum++; t->rn_info = rn_nodenum++;
351 	tt->rn_twin = t;
352 	tt->rn_ybro = rn_clist;
353 	rn_clist = tt;
354 #endif
355 	return t;
356 }
357 
358 static struct radix_node *
359 rn_insert(v_arg, head, dupentry, nodes)
360 	void *v_arg;
361 	struct radix_node_head *head;
362 	int *dupentry;
363 	struct radix_node nodes[2];
364 {
365 	caddr_t v = v_arg;
366 	struct radix_node *top = head->rnh_treetop;
367 	int head_off = top->rn_offset, vlen = (int)*((u_char *)v);
368 	register struct radix_node *t = rn_search(v_arg, top);
369 	register caddr_t cp = v + head_off;
370 	register int b;
371 	struct radix_node *tt;
372     	/*
373 	 * Find first bit at which v and t->rn_key differ
374 	 */
375     {
376 	register caddr_t cp2 = t->rn_key + head_off;
377 	register int cmp_res;
378 	caddr_t cplim = v + vlen;
379 
380 	while (cp < cplim)
381 		if (*cp2++ != *cp++)
382 			goto on1;
383 	*dupentry = 1;
384 	return t;
385 on1:
386 	*dupentry = 0;
387 	cmp_res = (cp[-1] ^ cp2[-1]) & 0xff;
388 	for (b = (cp - v) << 3; cmp_res; b--)
389 		cmp_res >>= 1;
390     }
391     {
392 	register struct radix_node *p, *x = top;
393 	cp = v;
394 	do {
395 		p = x;
396 		if (cp[x->rn_offset] & x->rn_bmask)
397 			x = x->rn_right;
398 		else
399 			x = x->rn_left;
400 	} while (b > (unsigned) x->rn_bit);
401 				/* x->rn_bit < b && x->rn_bit >= 0 */
402 #ifdef RN_DEBUG
403 	if (rn_debug)
404 		log(LOG_DEBUG, "rn_insert: Going In:\n"), traverse(p);
405 #endif
406 	t = rn_newpair(v_arg, b, nodes);
407 	tt = t->rn_left;
408 	if ((cp[p->rn_offset] & p->rn_bmask) == 0)
409 		p->rn_left = t;
410 	else
411 		p->rn_right = t;
412 	x->rn_parent = t;
413 	t->rn_parent = p; /* frees x, p as temp vars below */
414 	if ((cp[t->rn_offset] & t->rn_bmask) == 0) {
415 		t->rn_right = x;
416 	} else {
417 		t->rn_right = tt;
418 		t->rn_left = x;
419 	}
420 #ifdef RN_DEBUG
421 	if (rn_debug)
422 		log(LOG_DEBUG, "rn_insert: Coming Out:\n"), traverse(p);
423 #endif
424     }
425 	return (tt);
426 }
427 
428 struct radix_node *
429 rn_addmask(n_arg, search, skip)
430 	int search, skip;
431 	void *n_arg;
432 {
433 	caddr_t netmask = (caddr_t)n_arg;
434 	register struct radix_node *x;
435 	register caddr_t cp, cplim;
436 	register int b = 0, mlen, j;
437 	int maskduplicated, m0, isnormal;
438 	struct radix_node *saved_x;
439 	static int last_zeroed = 0;
440 
441 	if ((mlen = *(u_char *)netmask) > max_keylen)
442 		mlen = max_keylen;
443 	if (skip == 0)
444 		skip = 1;
445 	if (mlen <= skip)
446 		return (mask_rnhead->rnh_nodes);
447 	if (skip > 1)
448 		Bcopy(rn_ones + 1, addmask_key + 1, skip - 1);
449 	if ((m0 = mlen) > skip)
450 		Bcopy(netmask + skip, addmask_key + skip, mlen - skip);
451 	/*
452 	 * Trim trailing zeroes.
453 	 */
454 	for (cp = addmask_key + mlen; (cp > addmask_key) && cp[-1] == 0;)
455 		cp--;
456 	mlen = cp - addmask_key;
457 	if (mlen <= skip) {
458 		if (m0 >= last_zeroed)
459 			last_zeroed = mlen;
460 		return (mask_rnhead->rnh_nodes);
461 	}
462 	if (m0 < last_zeroed)
463 		Bzero(addmask_key + m0, last_zeroed - m0);
464 	*addmask_key = last_zeroed = mlen;
465 	x = rn_search(addmask_key, rn_masktop);
466 	if (Bcmp(addmask_key, x->rn_key, mlen) != 0)
467 		x = 0;
468 	if (x || search)
469 		return (x);
470 	R_Malloc(x, struct radix_node *, max_keylen + 2 * sizeof (*x));
471 	if ((saved_x = x) == 0)
472 		return (0);
473 	Bzero(x, max_keylen + 2 * sizeof (*x));
474 	netmask = cp = (caddr_t)(x + 2);
475 	Bcopy(addmask_key, cp, mlen);
476 	x = rn_insert(cp, mask_rnhead, &maskduplicated, x);
477 	if (maskduplicated) {
478 		log(LOG_ERR, "rn_addmask: mask impossibly already in tree");
479 		Free(saved_x);
480 		return (x);
481 	}
482 	/*
483 	 * Calculate index of mask, and check for normalcy.
484 	 */
485 	cplim = netmask + mlen; isnormal = 1;
486 	for (cp = netmask + skip; (cp < cplim) && *(u_char *)cp == 0xff;)
487 		cp++;
488 	if (cp != cplim) {
489 		for (j = 0x80; (j & *cp) != 0; j >>= 1)
490 			b++;
491 		if (*cp != normal_chars[b] || cp != (cplim - 1))
492 			isnormal = 0;
493 	}
494 	b += (cp - netmask) << 3;
495 	x->rn_bit = -1 - b;
496 	if (isnormal)
497 		x->rn_flags |= RNF_NORMAL;
498 	return (x);
499 }
500 
501 static int	/* XXX: arbitrary ordering for non-contiguous masks */
502 rn_lexobetter(m_arg, n_arg)
503 	void *m_arg, *n_arg;
504 {
505 	register u_char *mp = m_arg, *np = n_arg, *lim;
506 
507 	if (*mp > *np)
508 		return 1;  /* not really, but need to check longer one first */
509 	if (*mp == *np)
510 		for (lim = mp + *mp; mp < lim;)
511 			if (*mp++ > *np++)
512 				return 1;
513 	return 0;
514 }
515 
516 static struct radix_mask *
517 rn_new_radix_mask(tt, next)
518 	register struct radix_node *tt;
519 	register struct radix_mask *next;
520 {
521 	register struct radix_mask *m;
522 
523 	MKGet(m);
524 	if (m == 0) {
525 		log(LOG_ERR, "Mask for route not entered\n");
526 		return (0);
527 	}
528 	Bzero(m, sizeof *m);
529 	m->rm_bit = tt->rn_bit;
530 	m->rm_flags = tt->rn_flags;
531 	if (tt->rn_flags & RNF_NORMAL)
532 		m->rm_leaf = tt;
533 	else
534 		m->rm_mask = tt->rn_mask;
535 	m->rm_mklist = next;
536 	tt->rn_mklist = m;
537 	return m;
538 }
539 
540 struct radix_node *
541 rn_addroute(v_arg, n_arg, head, treenodes)
542 	void *v_arg, *n_arg;
543 	struct radix_node_head *head;
544 	struct radix_node treenodes[2];
545 {
546 	caddr_t v = (caddr_t)v_arg, netmask = (caddr_t)n_arg;
547 	register struct radix_node *t, *x = 0, *tt;
548 	struct radix_node *saved_tt, *top = head->rnh_treetop;
549 	short b = 0, b_leaf = 0;
550 	int keyduplicated;
551 	caddr_t 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_offset)) == 0)
563 			return (0);
564 		b_leaf = x->rn_bit;
565 		b = -1 - x->rn_bit;
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_bit) /* 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_parent = x = t->rn_parent;
602 			t->rn_parent = tt;	 		/* parent */
603 			if (x->rn_left == t)
604 				x->rn_left = tt;
605 			else
606 				x->rn_right = tt;
607 			saved_tt = tt; x = xx;
608 		} else {
609 			(tt = treenodes)->rn_dupedkey = t->rn_dupedkey;
610 			t->rn_dupedkey = tt;
611 			tt->rn_parent = t;			/* parent */
612 			if (tt->rn_dupedkey)			/* parent */
613 				tt->rn_dupedkey->rn_parent = tt; /* parent */
614 		}
615 #ifdef RN_DEBUG
616 		t=tt+1; tt->rn_info = rn_nodenum++; t->rn_info = rn_nodenum++;
617 		tt->rn_twin = t; tt->rn_ybro = rn_clist; rn_clist = tt;
618 #endif
619 		tt->rn_key = (caddr_t) v;
620 		tt->rn_bit = -1;
621 		tt->rn_flags = RNF_ACTIVE;
622 	}
623 	/*
624 	 * Put mask in tree.
625 	 */
626 	if (netmask) {
627 		tt->rn_mask = netmask;
628 		tt->rn_bit = x->rn_bit;
629 		tt->rn_flags |= x->rn_flags & RNF_NORMAL;
630 	}
631 	t = saved_tt->rn_parent;
632 	if (keyduplicated)
633 		goto on2;
634 	b_leaf = -1 - t->rn_bit;
635 	if (t->rn_right == saved_tt)
636 		x = t->rn_left;
637 	else
638 		x = t->rn_right;
639 	/* Promote general routes from below */
640 	if (x->rn_bit < 0) {
641 	    for (mp = &t->rn_mklist; x; x = x->rn_dupedkey)
642 		if (x->rn_mask && (x->rn_bit >= b_leaf) && x->rn_mklist == 0) {
643 			*mp = m = rn_new_radix_mask(x, 0);
644 			if (m)
645 				mp = &m->rm_mklist;
646 		}
647 	} else if (x->rn_mklist) {
648 		/*
649 		 * Skip over masks whose index is > that of new node
650 		 */
651 		for (mp = &x->rn_mklist; (m = *mp); mp = &m->rm_mklist)
652 			if (m->rm_bit >= b_leaf)
653 				break;
654 		t->rn_mklist = m; *mp = 0;
655 	}
656 on2:
657 	/* Add new route to highest possible ancestor's list */
658 	if ((netmask == 0) || (b > t->rn_bit ))
659 		return tt; /* can't lift at all */
660 	b_leaf = tt->rn_bit;
661 	do {
662 		x = t;
663 		t = t->rn_parent;
664 	} while (b <= t->rn_bit && x != top);
665 	/*
666 	 * Search through routes associated with node to
667 	 * insert new route according to index.
668 	 * Need same criteria as when sorting dupedkeys to avoid
669 	 * double loop on deletion.
670 	 */
671 	for (mp = &x->rn_mklist; (m = *mp); mp = &m->rm_mklist) {
672 		if (m->rm_bit < b_leaf)
673 			continue;
674 		if (m->rm_bit > b_leaf)
675 			break;
676 		if (m->rm_flags & RNF_NORMAL) {
677 			mmask = m->rm_leaf->rn_mask;
678 			if (tt->rn_flags & RNF_NORMAL) {
679 			    log(LOG_ERR,
680 			        "Non-unique normal route, mask not entered\n");
681 				return tt;
682 			}
683 		} else
684 			mmask = m->rm_mask;
685 		if (mmask == netmask) {
686 			m->rm_refs++;
687 			tt->rn_mklist = m;
688 			return tt;
689 		}
690 		if (rn_refines(netmask, mmask)
691 		    || rn_lexobetter(netmask, mmask))
692 			break;
693 	}
694 	*mp = rn_new_radix_mask(tt, *mp);
695 	return tt;
696 }
697 
698 struct radix_node *
699 rn_delete(v_arg, netmask_arg, head)
700 	void *v_arg, *netmask_arg;
701 	struct radix_node_head *head;
702 {
703 	register struct radix_node *t, *p, *x, *tt;
704 	struct radix_mask *m, *saved_m, **mp;
705 	struct radix_node *dupedkey, *saved_tt, *top;
706 	caddr_t v, netmask;
707 	int b, head_off, vlen;
708 
709 	v = v_arg;
710 	netmask = netmask_arg;
711 	x = head->rnh_treetop;
712 	tt = rn_search(v, x);
713 	head_off = x->rn_offset;
714 	vlen =  *(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_bit;
747 	t = saved_tt->rn_parent;
748 	if (b > t->rn_bit)
749 		goto on1; /* Wasn't lifted at all */
750 	do {
751 		x = t;
752 		t = t->rn_parent;
753 	} while (b <= t->rn_bit && 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_parent;
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 dupekey chain.
782 		 */
783 		if (tt == saved_tt) {
784 			/* remove from head of chain */
785 			x = dupedkey; x->rn_parent = t;
786 			if (t->rn_left == tt)
787 				t->rn_left = x;
788 			else
789 				t->rn_right = x;
790 		} else {
791 			/* find node in front of tt on the chain */
792 			for (x = p = saved_tt; p && p->rn_dupedkey != tt;)
793 				p = p->rn_dupedkey;
794 			if (p) {
795 				p->rn_dupedkey = tt->rn_dupedkey;
796 				if (tt->rn_dupedkey)		/* parent */
797 					tt->rn_dupedkey->rn_parent = p;
798 								/* parent */
799 			} else log(LOG_ERR, "rn_delete: couldn't find us\n");
800 		}
801 		t = tt + 1;
802 		if  (t->rn_flags & RNF_ACTIVE) {
803 #ifndef RN_DEBUG
804 			*++x = *t;
805 			p = t->rn_parent;
806 #else
807 			b = t->rn_info;
808 			*++x = *t;
809 			t->rn_info = b;
810 			p = t->rn_parent;
811 #endif
812 			if (p->rn_left == t)
813 				p->rn_left = x;
814 			else
815 				p->rn_right = x;
816 			x->rn_left->rn_parent = x;
817 			x->rn_right->rn_parent = x;
818 		}
819 		goto out;
820 	}
821 	if (t->rn_left == tt)
822 		x = t->rn_right;
823 	else
824 		x = t->rn_left;
825 	p = t->rn_parent;
826 	if (p->rn_right == t)
827 		p->rn_right = x;
828 	else
829 		p->rn_left = x;
830 	x->rn_parent = p;
831 	/*
832 	 * Demote routes attached to us.
833 	 */
834 	if (t->rn_mklist) {
835 		if (x->rn_bit >= 0) {
836 			for (mp = &x->rn_mklist; (m = *mp);)
837 				mp = &m->rm_mklist;
838 			*mp = t->rn_mklist;
839 		} else {
840 			/* If there are any key,mask pairs in a sibling
841 			   duped-key chain, some subset will appear sorted
842 			   in the same order attached to our mklist */
843 			for (m = t->rn_mklist; m && x; x = x->rn_dupedkey)
844 				if (m == x->rn_mklist) {
845 					struct radix_mask *mm = m->rm_mklist;
846 					x->rn_mklist = 0;
847 					if (--(m->rm_refs) < 0)
848 						MKFree(m);
849 					m = mm;
850 				}
851 			if (m)
852 				log(LOG_ERR,
853 				    "rn_delete: Orphaned Mask %p at %p\n",
854 				    (void *)m, (void *)x);
855 		}
856 	}
857 	/*
858 	 * We may be holding an active internal node in the tree.
859 	 */
860 	x = tt + 1;
861 	if (t != x) {
862 #ifndef RN_DEBUG
863 		*t = *x;
864 #else
865 		b = t->rn_info;
866 		*t = *x;
867 		t->rn_info = b;
868 #endif
869 		t->rn_left->rn_parent = t;
870 		t->rn_right->rn_parent = t;
871 		p = x->rn_parent;
872 		if (p->rn_left == x)
873 			p->rn_left = t;
874 		else
875 			p->rn_right = t;
876 	}
877 out:
878 	tt->rn_flags &= ~RNF_ACTIVE;
879 	tt[1].rn_flags &= ~RNF_ACTIVE;
880 	return (tt);
881 }
882 
883 /*
884  * This is the same as rn_walktree() except for the parameters and the
885  * exit.
886  */
887 static int
888 rn_walktree_from(h, a, m, f, w)
889 	struct radix_node_head *h;
890 	void *a, *m;
891 	walktree_f_t *f;
892 	void *w;
893 {
894 	int error;
895 	struct radix_node *base, *next;
896 	u_char *xa = (u_char *)a;
897 	u_char *xm = (u_char *)m;
898 	register struct radix_node *rn, *last = 0 /* shut up gcc */;
899 	int stopping = 0;
900 	int lastb;
901 
902 	/*
903 	 * rn_search_m is sort-of-open-coded here.
904 	 */
905 	/* printf("about to search\n"); */
906 	for (rn = h->rnh_treetop; rn->rn_bit >= 0; ) {
907 		last = rn;
908 		/* printf("rn_bit %d, rn_bmask %x, xm[rn_offset] %x\n",
909 		       rn->rn_bit, rn->rn_bmask, xm[rn->rn_offset]); */
910 		if (!(rn->rn_bmask & xm[rn->rn_offset])) {
911 			break;
912 		}
913 		if (rn->rn_bmask & xa[rn->rn_offset]) {
914 			rn = rn->rn_right;
915 		} else {
916 			rn = rn->rn_left;
917 		}
918 	}
919 	/* printf("done searching\n"); */
920 
921 	/*
922 	 * Two cases: either we stepped off the end of our mask,
923 	 * in which case last == rn, or we reached a leaf, in which
924 	 * case we want to start from the last node we looked at.
925 	 * Either way, last is the node we want to start from.
926 	 */
927 	rn = last;
928 	lastb = rn->rn_bit;
929 
930 	/* printf("rn %p, lastb %d\n", rn, lastb);*/
931 
932 	/*
933 	 * This gets complicated because we may delete the node
934 	 * while applying the function f to it, so we need to calculate
935 	 * the successor node in advance.
936 	 */
937 	while (rn->rn_bit >= 0)
938 		rn = rn->rn_left;
939 
940 	while (!stopping) {
941 		/* printf("node %p (%d)\n", rn, rn->rn_bit); */
942 		base = rn;
943 		/* If at right child go back up, otherwise, go right */
944 		while (rn->rn_parent->rn_right == rn
945 		       && !(rn->rn_flags & RNF_ROOT)) {
946 			rn = rn->rn_parent;
947 
948 			/* if went up beyond last, stop */
949 			if (rn->rn_bit < lastb) {
950 				stopping = 1;
951 				/* printf("up too far\n"); */
952 			}
953 		}
954 
955 		/* Find the next *leaf* since next node might vanish, too */
956 		for (rn = rn->rn_parent->rn_right; rn->rn_bit >= 0;)
957 			rn = rn->rn_left;
958 		next = rn;
959 		/* Process leaves */
960 		while ((rn = base) != 0) {
961 			base = rn->rn_dupedkey;
962 			/* printf("leaf %p\n", rn); */
963 			if (!(rn->rn_flags & RNF_ROOT)
964 			    && (error = (*f)(rn, w)))
965 				return (error);
966 		}
967 		rn = next;
968 
969 		if (rn->rn_flags & RNF_ROOT) {
970 			/* printf("root, stopping"); */
971 			stopping = 1;
972 		}
973 
974 	}
975 	return 0;
976 }
977 
978 static int
979 rn_walktree(h, f, w)
980 	struct radix_node_head *h;
981 	walktree_f_t *f;
982 	void *w;
983 {
984 	int error;
985 	struct radix_node *base, *next;
986 	register struct radix_node *rn = h->rnh_treetop;
987 	/*
988 	 * This gets complicated because we may delete the node
989 	 * while applying the function f to it, so we need to calculate
990 	 * the successor node in advance.
991 	 */
992 	/* First time through node, go left */
993 	while (rn->rn_bit >= 0)
994 		rn = rn->rn_left;
995 	for (;;) {
996 		base = rn;
997 		/* If at right child go back up, otherwise, go right */
998 		while (rn->rn_parent->rn_right == rn
999 		       && (rn->rn_flags & RNF_ROOT) == 0)
1000 			rn = rn->rn_parent;
1001 		/* Find the next *leaf* since next node might vanish, too */
1002 		for (rn = rn->rn_parent->rn_right; rn->rn_bit >= 0;)
1003 			rn = rn->rn_left;
1004 		next = rn;
1005 		/* Process leaves */
1006 		while ((rn = base)) {
1007 			base = rn->rn_dupedkey;
1008 			if (!(rn->rn_flags & RNF_ROOT)
1009 			    && (error = (*f)(rn, w)))
1010 				return (error);
1011 		}
1012 		rn = next;
1013 		if (rn->rn_flags & RNF_ROOT)
1014 			return (0);
1015 	}
1016 	/* NOTREACHED */
1017 }
1018 
1019 int
1020 rn_inithead(head, off)
1021 	void **head;
1022 	int off;
1023 {
1024 	register struct radix_node_head *rnh;
1025 	register struct radix_node *t, *tt, *ttt;
1026 	if (*head)
1027 		return (1);
1028 	R_Malloc(rnh, struct radix_node_head *, sizeof (*rnh));
1029 	if (rnh == 0)
1030 		return (0);
1031 	Bzero(rnh, sizeof (*rnh));
1032 #ifdef _KERNEL
1033 	RADIX_NODE_HEAD_LOCK_INIT(rnh);
1034 #endif
1035 	*head = rnh;
1036 	t = rn_newpair(rn_zeros, off, rnh->rnh_nodes);
1037 	ttt = rnh->rnh_nodes + 2;
1038 	t->rn_right = ttt;
1039 	t->rn_parent = t;
1040 	tt = t->rn_left;
1041 	tt->rn_flags = t->rn_flags = RNF_ROOT | RNF_ACTIVE;
1042 	tt->rn_bit = -1 - off;
1043 	*ttt = *tt;
1044 	ttt->rn_key = rn_ones;
1045 	rnh->rnh_addaddr = rn_addroute;
1046 	rnh->rnh_deladdr = rn_delete;
1047 	rnh->rnh_matchaddr = rn_match;
1048 	rnh->rnh_lookup = rn_lookup;
1049 	rnh->rnh_walktree = rn_walktree;
1050 	rnh->rnh_walktree_from = rn_walktree_from;
1051 	rnh->rnh_treetop = t;
1052 	return (1);
1053 }
1054 
1055 void
1056 rn_init()
1057 {
1058 	char *cp, *cplim;
1059 #ifdef _KERNEL
1060 	struct domain *dom;
1061 
1062 	for (dom = domains; dom; dom = dom->dom_next)
1063 		if (dom->dom_maxrtkey > max_keylen)
1064 			max_keylen = dom->dom_maxrtkey;
1065 #endif
1066 	if (max_keylen == 0) {
1067 		log(LOG_ERR,
1068 		    "rn_init: radix functions require max_keylen be set\n");
1069 		return;
1070 	}
1071 	R_Malloc(rn_zeros, char *, 3 * max_keylen);
1072 	if (rn_zeros == NULL)
1073 		panic("rn_init");
1074 	Bzero(rn_zeros, 3 * max_keylen);
1075 	rn_ones = cp = rn_zeros + max_keylen;
1076 	addmask_key = cplim = rn_ones + max_keylen;
1077 	while (cp < cplim)
1078 		*cp++ = -1;
1079 	if (rn_inithead((void **)(void *)&mask_rnhead, 0) == 0)
1080 		panic("rn_init 2");
1081 }
1082