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