xref: /freebsd/sys/net/radix.c (revision 9162f64b58d01ec01481d60b6cdc06ffd8e8c7fc)
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  * 4. Neither the name of the University nor the names of its contributors
14  *    may be used to endorse or promote products derived from this software
15  *    without specific prior written permission.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
21  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  *
29  *	@(#)radix.c	8.5 (Berkeley) 5/19/95
30  * $FreeBSD$
31  */
32 
33 /*
34  * Routines to build and maintain radix trees for routing lookups.
35  */
36 #ifndef _RADIX_H_
37 #include <sys/param.h>
38 #ifdef	_KERNEL
39 #include <sys/lock.h>
40 #include <sys/mutex.h>
41 #include <sys/rwlock.h>
42 #include <sys/systm.h>
43 #include <sys/malloc.h>
44 #include <sys/domain.h>
45 #else
46 #include <stdlib.h>
47 #endif
48 #include <sys/syslog.h>
49 #include <net/radix.h>
50 #endif
51 
52 #include "opt_mpath.h"
53 
54 #ifdef RADIX_MPATH
55 #include <net/radix_mpath.h>
56 #endif
57 
58 
59 static int	rn_walktree_from(struct radix_node_head *h, void *a, void *m,
60 		    walktree_f_t *f, void *w);
61 static int rn_walktree(struct radix_node_head *, walktree_f_t *, void *);
62 static struct radix_node
63 	 *rn_insert(void *, struct radix_node_head *, int *,
64 	     struct radix_node [2]),
65 	 *rn_newpair(void *, int, struct radix_node[2]),
66 	 *rn_search(void *, struct radix_node *),
67 	 *rn_search_m(void *, struct radix_node *, void *);
68 
69 static int	max_keylen;
70 static struct radix_mask *rn_mkfreelist;
71 static struct radix_node_head *mask_rnhead;
72 /*
73  * Work area -- the following point to 3 buffers of size max_keylen,
74  * allocated in this order in a block of memory malloc'ed by rn_init.
75  */
76 static char *rn_zeros, *rn_ones, *addmask_key;
77 
78 #define MKGet(m) {						\
79 	if (rn_mkfreelist) {					\
80 		m = rn_mkfreelist;				\
81 		rn_mkfreelist = (m)->rm_mklist;			\
82 	} else							\
83 		R_Malloc(m, struct radix_mask *, sizeof (struct radix_mask)); }
84 
85 #define MKFree(m) { (m)->rm_mklist = rn_mkfreelist; rn_mkfreelist = (m);}
86 
87 #define rn_masktop (mask_rnhead->rnh_treetop)
88 
89 static int	rn_lexobetter(void *m_arg, void *n_arg);
90 static struct radix_mask *
91 		rn_new_radix_mask(struct radix_node *tt,
92 		    struct radix_mask *next);
93 static int	rn_satisfies_leaf(char *trial, struct radix_node *leaf,
94 		    int skip);
95 
96 /*
97  * The data structure for the keys is a radix tree with one way
98  * branching removed.  The index rn_bit at an internal node n represents a bit
99  * position to be tested.  The tree is arranged so that all descendants
100  * of a node n have keys whose bits all agree up to position rn_bit - 1.
101  * (We say the index of n is rn_bit.)
102  *
103  * There is at least one descendant which has a one bit at position rn_bit,
104  * and at least one with a zero there.
105  *
106  * A route is determined by a pair of key and mask.  We require that the
107  * bit-wise logical and of the key and mask to be the key.
108  * We define the index of a route to associated with the mask to be
109  * the first bit number in the mask where 0 occurs (with bit number 0
110  * representing the highest order bit).
111  *
112  * We say a mask is normal if every bit is 0, past the index of the mask.
113  * If a node n has a descendant (k, m) with index(m) == index(n) == rn_bit,
114  * and m is a normal mask, then the route applies to every descendant of n.
115  * If the index(m) < rn_bit, this implies the trailing last few bits of k
116  * before bit b are all 0, (and hence consequently true of every descendant
117  * of n), so the route applies to all descendants of the node as well.
118  *
119  * Similar logic shows that a non-normal mask m such that
120  * index(m) <= index(n) could potentially apply to many children of n.
121  * Thus, for each non-host route, we attach its mask to a list at an internal
122  * node as high in the tree as we can go.
123  *
124  * The present version of the code makes use of normal routes in short-
125  * circuiting an explict mask and compare operation when testing whether
126  * a key satisfies a normal route, and also in remembering the unique leaf
127  * that governs a subtree.
128  */
129 
130 /*
131  * Most of the functions in this code assume that the key/mask arguments
132  * are sockaddr-like structures, where the first byte is an u_char
133  * indicating the size of the entire structure.
134  *
135  * To make the assumption more explicit, we use the LEN() macro to access
136  * this field. It is safe to pass an expression with side effects
137  * to LEN() as the argument is evaluated only once.
138  */
139 #define LEN(x) (*(const u_char *)(x))
140 
141 /*
142  * XXX THIS NEEDS TO BE FIXED
143  * In the code, pointers to keys and masks are passed as either
144  * 'void *' (because callers use to pass pointers of various kinds), or
145  * 'caddr_t' (which is fine for pointer arithmetics, but not very
146  * clean when you dereference it to access data). Furthermore, caddr_t
147  * is really 'char *', while the natural type to operate on keys and
148  * masks would be 'u_char'. This mismatch require a lot of casts and
149  * intermediate variables to adapt types that clutter the code.
150  */
151 
152 /*
153  * Search a node in the tree matching the key.
154  */
155 static struct radix_node *
156 rn_search(v_arg, head)
157 	void *v_arg;
158 	struct radix_node *head;
159 {
160 	register struct radix_node *x;
161 	register caddr_t v;
162 
163 	for (x = head, v = v_arg; x->rn_bit >= 0;) {
164 		if (x->rn_bmask & v[x->rn_offset])
165 			x = x->rn_right;
166 		else
167 			x = x->rn_left;
168 	}
169 	return (x);
170 }
171 
172 /*
173  * Same as above, but with an additional mask.
174  * XXX note this function is used only once.
175  */
176 static struct radix_node *
177 rn_search_m(v_arg, head, m_arg)
178 	struct radix_node *head;
179 	void *v_arg, *m_arg;
180 {
181 	register struct radix_node *x;
182 	register caddr_t v = v_arg, m = m_arg;
183 
184 	for (x = head; x->rn_bit >= 0;) {
185 		if ((x->rn_bmask & m[x->rn_offset]) &&
186 		    (x->rn_bmask & v[x->rn_offset]))
187 			x = x->rn_right;
188 		else
189 			x = x->rn_left;
190 	}
191 	return x;
192 }
193 
194 int
195 rn_refines(m_arg, n_arg)
196 	void *m_arg, *n_arg;
197 {
198 	register caddr_t m = m_arg, n = n_arg;
199 	register caddr_t lim, lim2 = lim = n + LEN(n);
200 	int longer = LEN(n++) - (int)LEN(m++);
201 	int masks_are_equal = 1;
202 
203 	if (longer > 0)
204 		lim -= longer;
205 	while (n < lim) {
206 		if (*n & ~(*m))
207 			return 0;
208 		if (*n++ != *m++)
209 			masks_are_equal = 0;
210 	}
211 	while (n < lim2)
212 		if (*n++)
213 			return 0;
214 	if (masks_are_equal && (longer < 0))
215 		for (lim2 = m - longer; m < lim2; )
216 			if (*m++)
217 				return 1;
218 	return (!masks_are_equal);
219 }
220 
221 struct radix_node *
222 rn_lookup(v_arg, m_arg, head)
223 	void *v_arg, *m_arg;
224 	struct radix_node_head *head;
225 {
226 	register struct radix_node *x;
227 	caddr_t netmask = 0;
228 
229 	if (m_arg) {
230 		x = rn_addmask(m_arg, 1, head->rnh_treetop->rn_offset);
231 		if (x == 0)
232 			return (0);
233 		netmask = x->rn_key;
234 	}
235 	x = rn_match(v_arg, head);
236 	if (x && netmask) {
237 		while (x && x->rn_mask != netmask)
238 			x = x->rn_dupedkey;
239 	}
240 	return x;
241 }
242 
243 static int
244 rn_satisfies_leaf(trial, leaf, skip)
245 	char *trial;
246 	register struct radix_node *leaf;
247 	int skip;
248 {
249 	register char *cp = trial, *cp2 = leaf->rn_key, *cp3 = leaf->rn_mask;
250 	char *cplim;
251 	int length = min(LEN(cp), LEN(cp2));
252 
253 	if (cp3 == 0)
254 		cp3 = rn_ones;
255 	else
256 		length = min(length, *(u_char *)cp3);
257 	cplim = cp + length; cp3 += skip; cp2 += skip;
258 	for (cp += skip; cp < cplim; cp++, cp2++, cp3++)
259 		if ((*cp ^ *cp2) & *cp3)
260 			return 0;
261 	return 1;
262 }
263 
264 struct radix_node *
265 rn_match(v_arg, head)
266 	void *v_arg;
267 	struct radix_node_head *head;
268 {
269 	caddr_t v = v_arg;
270 	register struct radix_node *t = head->rnh_treetop, *x;
271 	register caddr_t cp = v, cp2;
272 	caddr_t cplim;
273 	struct radix_node *saved_t, *top = t;
274 	int off = t->rn_offset, vlen = LEN(cp), matched_off;
275 	register int test, b, rn_bit;
276 
277 	/*
278 	 * Open code rn_search(v, top) to avoid overhead of extra
279 	 * subroutine call.
280 	 */
281 	for (; t->rn_bit >= 0; ) {
282 		if (t->rn_bmask & cp[t->rn_offset])
283 			t = t->rn_right;
284 		else
285 			t = t->rn_left;
286 	}
287 	/*
288 	 * See if we match exactly as a host destination
289 	 * or at least learn how many bits match, for normal mask finesse.
290 	 *
291 	 * It doesn't hurt us to limit how many bytes to check
292 	 * to the length of the mask, since if it matches we had a genuine
293 	 * match and the leaf we have is the most specific one anyway;
294 	 * if it didn't match with a shorter length it would fail
295 	 * with a long one.  This wins big for class B&C netmasks which
296 	 * are probably the most common case...
297 	 */
298 	if (t->rn_mask)
299 		vlen = *(u_char *)t->rn_mask;
300 	cp += off; cp2 = t->rn_key + off; cplim = v + vlen;
301 	for (; cp < cplim; cp++, cp2++)
302 		if (*cp != *cp2)
303 			goto on1;
304 	/*
305 	 * This extra grot is in case we are explicitly asked
306 	 * to look up the default.  Ugh!
307 	 *
308 	 * Never return the root node itself, it seems to cause a
309 	 * lot of confusion.
310 	 */
311 	if (t->rn_flags & RNF_ROOT)
312 		t = t->rn_dupedkey;
313 	return t;
314 on1:
315 	test = (*cp ^ *cp2) & 0xff; /* find first bit that differs */
316 	for (b = 7; (test >>= 1) > 0;)
317 		b--;
318 	matched_off = cp - v;
319 	b += matched_off << 3;
320 	rn_bit = -1 - b;
321 	/*
322 	 * If there is a host route in a duped-key chain, it will be first.
323 	 */
324 	if ((saved_t = t)->rn_mask == 0)
325 		t = t->rn_dupedkey;
326 	for (; t; t = t->rn_dupedkey)
327 		/*
328 		 * Even if we don't match exactly as a host,
329 		 * we may match if the leaf we wound up at is
330 		 * a route to a net.
331 		 */
332 		if (t->rn_flags & RNF_NORMAL) {
333 			if (rn_bit <= t->rn_bit)
334 				return t;
335 		} else if (rn_satisfies_leaf(v, t, matched_off))
336 				return t;
337 	t = saved_t;
338 	/* start searching up the tree */
339 	do {
340 		register struct radix_mask *m;
341 		t = t->rn_parent;
342 		m = t->rn_mklist;
343 		/*
344 		 * If non-contiguous masks ever become important
345 		 * we can restore the masking and open coding of
346 		 * the search and satisfaction test and put the
347 		 * calculation of "off" back before the "do".
348 		 */
349 		while (m) {
350 			if (m->rm_flags & RNF_NORMAL) {
351 				if (rn_bit <= m->rm_bit)
352 					return (m->rm_leaf);
353 			} else {
354 				off = min(t->rn_offset, matched_off);
355 				x = rn_search_m(v, t, m->rm_mask);
356 				while (x && x->rn_mask != m->rm_mask)
357 					x = x->rn_dupedkey;
358 				if (x && rn_satisfies_leaf(v, x, off))
359 					return x;
360 			}
361 			m = m->rm_mklist;
362 		}
363 	} while (t != top);
364 	return 0;
365 }
366 
367 #ifdef RN_DEBUG
368 int	rn_nodenum;
369 struct	radix_node *rn_clist;
370 int	rn_saveinfo;
371 int	rn_debug =  1;
372 #endif
373 
374 /*
375  * Whenever we add a new leaf to the tree, we also add a parent node,
376  * so we allocate them as an array of two elements: the first one must be
377  * the leaf (see RNTORT() in route.c), the second one is the parent.
378  * This routine initializes the relevant fields of the nodes, so that
379  * the leaf is the left child of the parent node, and both nodes have
380  * (almost) all all fields filled as appropriate.
381  * (XXX some fields are left unset, see the '#if 0' section).
382  * The function returns a pointer to the parent node.
383  */
384 
385 static struct radix_node *
386 rn_newpair(v, b, nodes)
387 	void *v;
388 	int b;
389 	struct radix_node nodes[2];
390 {
391 	register struct radix_node *tt = nodes, *t = tt + 1;
392 	t->rn_bit = b;
393 	t->rn_bmask = 0x80 >> (b & 7);
394 	t->rn_left = tt;
395 	t->rn_offset = b >> 3;
396 
397 #if 0  /* XXX perhaps we should fill these fields as well. */
398 	t->rn_parent = t->rn_right = NULL;
399 
400 	tt->rn_mask = NULL;
401 	tt->rn_dupedkey = NULL;
402 	tt->rn_bmask = 0;
403 #endif
404 	tt->rn_bit = -1;
405 	tt->rn_key = (caddr_t)v;
406 	tt->rn_parent = t;
407 	tt->rn_flags = t->rn_flags = RNF_ACTIVE;
408 	tt->rn_mklist = t->rn_mklist = 0;
409 #ifdef RN_DEBUG
410 	tt->rn_info = rn_nodenum++; t->rn_info = rn_nodenum++;
411 	tt->rn_twin = t;
412 	tt->rn_ybro = rn_clist;
413 	rn_clist = tt;
414 #endif
415 	return t;
416 }
417 
418 static struct radix_node *
419 rn_insert(v_arg, head, dupentry, nodes)
420 	void *v_arg;
421 	struct radix_node_head *head;
422 	int *dupentry;
423 	struct radix_node nodes[2];
424 {
425 	caddr_t v = v_arg;
426 	struct radix_node *top = head->rnh_treetop;
427 	int head_off = top->rn_offset, vlen = (int)LEN(v);
428 	register struct radix_node *t = rn_search(v_arg, top);
429 	register caddr_t cp = v + head_off;
430 	register int b;
431 	struct radix_node *tt;
432     	/*
433 	 * Find first bit at which v and t->rn_key differ
434 	 */
435     {
436 	register caddr_t cp2 = t->rn_key + head_off;
437 	register int cmp_res;
438 	caddr_t cplim = v + vlen;
439 
440 	while (cp < cplim)
441 		if (*cp2++ != *cp++)
442 			goto on1;
443 	*dupentry = 1;
444 	return t;
445 on1:
446 	*dupentry = 0;
447 	cmp_res = (cp[-1] ^ cp2[-1]) & 0xff;
448 	for (b = (cp - v) << 3; cmp_res; b--)
449 		cmp_res >>= 1;
450     }
451     {
452 	register struct radix_node *p, *x = top;
453 	cp = v;
454 	do {
455 		p = x;
456 		if (cp[x->rn_offset] & x->rn_bmask)
457 			x = x->rn_right;
458 		else
459 			x = x->rn_left;
460 	} while (b > (unsigned) x->rn_bit);
461 				/* x->rn_bit < b && x->rn_bit >= 0 */
462 #ifdef RN_DEBUG
463 	if (rn_debug)
464 		log(LOG_DEBUG, "rn_insert: Going In:\n"), traverse(p);
465 #endif
466 	t = rn_newpair(v_arg, b, nodes);
467 	tt = t->rn_left;
468 	if ((cp[p->rn_offset] & p->rn_bmask) == 0)
469 		p->rn_left = t;
470 	else
471 		p->rn_right = t;
472 	x->rn_parent = t;
473 	t->rn_parent = p; /* frees x, p as temp vars below */
474 	if ((cp[t->rn_offset] & t->rn_bmask) == 0) {
475 		t->rn_right = x;
476 	} else {
477 		t->rn_right = tt;
478 		t->rn_left = x;
479 	}
480 #ifdef RN_DEBUG
481 	if (rn_debug)
482 		log(LOG_DEBUG, "rn_insert: Coming Out:\n"), traverse(p);
483 #endif
484     }
485 	return (tt);
486 }
487 
488 struct radix_node *
489 rn_addmask(n_arg, search, skip)
490 	int search, skip;
491 	void *n_arg;
492 {
493 	caddr_t netmask = (caddr_t)n_arg;
494 	register struct radix_node *x;
495 	register caddr_t cp, cplim;
496 	register int b = 0, mlen, j;
497 	int maskduplicated, m0, isnormal;
498 	struct radix_node *saved_x;
499 	static int last_zeroed = 0;
500 
501 	if ((mlen = LEN(netmask)) > max_keylen)
502 		mlen = max_keylen;
503 	if (skip == 0)
504 		skip = 1;
505 	if (mlen <= skip)
506 		return (mask_rnhead->rnh_nodes);
507 	if (skip > 1)
508 		bcopy(rn_ones + 1, addmask_key + 1, skip - 1);
509 	if ((m0 = mlen) > skip)
510 		bcopy(netmask + skip, addmask_key + skip, mlen - skip);
511 	/*
512 	 * Trim trailing zeroes.
513 	 */
514 	for (cp = addmask_key + mlen; (cp > addmask_key) && cp[-1] == 0;)
515 		cp--;
516 	mlen = cp - addmask_key;
517 	if (mlen <= skip) {
518 		if (m0 >= last_zeroed)
519 			last_zeroed = mlen;
520 		return (mask_rnhead->rnh_nodes);
521 	}
522 	if (m0 < last_zeroed)
523 		bzero(addmask_key + m0, last_zeroed - m0);
524 	*addmask_key = last_zeroed = mlen;
525 	x = rn_search(addmask_key, rn_masktop);
526 	if (bcmp(addmask_key, x->rn_key, mlen) != 0)
527 		x = 0;
528 	if (x || search)
529 		return (x);
530 	R_Zalloc(x, struct radix_node *, max_keylen + 2 * sizeof (*x));
531 	if ((saved_x = x) == 0)
532 		return (0);
533 	netmask = cp = (caddr_t)(x + 2);
534 	bcopy(addmask_key, cp, mlen);
535 	x = rn_insert(cp, mask_rnhead, &maskduplicated, x);
536 	if (maskduplicated) {
537 		log(LOG_ERR, "rn_addmask: mask impossibly already in tree");
538 		Free(saved_x);
539 		return (x);
540 	}
541 	/*
542 	 * Calculate index of mask, and check for normalcy.
543 	 * First find the first byte with a 0 bit, then if there are
544 	 * more bits left (remember we already trimmed the trailing 0's),
545 	 * the pattern must be one of those in normal_chars[], or we have
546 	 * a non-contiguous mask.
547 	 */
548 	cplim = netmask + mlen;
549 	isnormal = 1;
550 	for (cp = netmask + skip; (cp < cplim) && *(u_char *)cp == 0xff;)
551 		cp++;
552 	if (cp != cplim) {
553 		static char normal_chars[] = {
554 			0, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe, 0xff};
555 
556 		for (j = 0x80; (j & *cp) != 0; j >>= 1)
557 			b++;
558 		if (*cp != normal_chars[b] || cp != (cplim - 1))
559 			isnormal = 0;
560 	}
561 	b += (cp - netmask) << 3;
562 	x->rn_bit = -1 - b;
563 	if (isnormal)
564 		x->rn_flags |= RNF_NORMAL;
565 	return (x);
566 }
567 
568 static int	/* XXX: arbitrary ordering for non-contiguous masks */
569 rn_lexobetter(m_arg, n_arg)
570 	void *m_arg, *n_arg;
571 {
572 	register u_char *mp = m_arg, *np = n_arg, *lim;
573 
574 	if (LEN(mp) > LEN(np))
575 		return 1;  /* not really, but need to check longer one first */
576 	if (LEN(mp) == LEN(np))
577 		for (lim = mp + LEN(mp); mp < lim;)
578 			if (*mp++ > *np++)
579 				return 1;
580 	return 0;
581 }
582 
583 static struct radix_mask *
584 rn_new_radix_mask(tt, next)
585 	register struct radix_node *tt;
586 	register struct radix_mask *next;
587 {
588 	register struct radix_mask *m;
589 
590 	MKGet(m);
591 	if (m == 0) {
592 		log(LOG_ERR, "Mask for route not entered\n");
593 		return (0);
594 	}
595 	bzero(m, sizeof *m);
596 	m->rm_bit = tt->rn_bit;
597 	m->rm_flags = tt->rn_flags;
598 	if (tt->rn_flags & RNF_NORMAL)
599 		m->rm_leaf = tt;
600 	else
601 		m->rm_mask = tt->rn_mask;
602 	m->rm_mklist = next;
603 	tt->rn_mklist = m;
604 	return m;
605 }
606 
607 struct radix_node *
608 rn_addroute(v_arg, n_arg, head, treenodes)
609 	void *v_arg, *n_arg;
610 	struct radix_node_head *head;
611 	struct radix_node treenodes[2];
612 {
613 	caddr_t v = (caddr_t)v_arg, netmask = (caddr_t)n_arg;
614 	register struct radix_node *t, *x = 0, *tt;
615 	struct radix_node *saved_tt, *top = head->rnh_treetop;
616 	short b = 0, b_leaf = 0;
617 	int keyduplicated;
618 	caddr_t mmask;
619 	struct radix_mask *m, **mp;
620 
621 	/*
622 	 * In dealing with non-contiguous masks, there may be
623 	 * many different routes which have the same mask.
624 	 * We will find it useful to have a unique pointer to
625 	 * the mask to speed avoiding duplicate references at
626 	 * nodes and possibly save time in calculating indices.
627 	 */
628 	if (netmask)  {
629 		if ((x = rn_addmask(netmask, 0, top->rn_offset)) == 0)
630 			return (0);
631 		b_leaf = x->rn_bit;
632 		b = -1 - x->rn_bit;
633 		netmask = x->rn_key;
634 	}
635 	/*
636 	 * Deal with duplicated keys: attach node to previous instance
637 	 */
638 	saved_tt = tt = rn_insert(v, head, &keyduplicated, treenodes);
639 	if (keyduplicated) {
640 		for (t = tt; tt; t = tt, tt = tt->rn_dupedkey) {
641 #ifdef RADIX_MPATH
642 			/* permit multipath, if enabled for the family */
643 			if (rn_mpath_capable(head) && netmask == tt->rn_mask) {
644 				/*
645 				 * go down to the end of multipaths, so that
646 				 * new entry goes into the end of rn_dupedkey
647 				 * chain.
648 				 */
649 				do {
650 					t = tt;
651 					tt = tt->rn_dupedkey;
652 				} while (tt && t->rn_mask == tt->rn_mask);
653 				break;
654 			}
655 #endif
656 			if (tt->rn_mask == netmask)
657 				return (0);
658 			if (netmask == 0 ||
659 			    (tt->rn_mask &&
660 			     ((b_leaf < tt->rn_bit) /* index(netmask) > node */
661 			      || rn_refines(netmask, tt->rn_mask)
662 			      || rn_lexobetter(netmask, tt->rn_mask))))
663 				break;
664 		}
665 		/*
666 		 * If the mask is not duplicated, we wouldn't
667 		 * find it among possible duplicate key entries
668 		 * anyway, so the above test doesn't hurt.
669 		 *
670 		 * We sort the masks for a duplicated key the same way as
671 		 * in a masklist -- most specific to least specific.
672 		 * This may require the unfortunate nuisance of relocating
673 		 * the head of the list.
674 		 *
675 		 * We also reverse, or doubly link the list through the
676 		 * parent pointer.
677 		 */
678 		if (tt == saved_tt) {
679 			struct	radix_node *xx = x;
680 			/* link in at head of list */
681 			(tt = treenodes)->rn_dupedkey = t;
682 			tt->rn_flags = t->rn_flags;
683 			tt->rn_parent = x = t->rn_parent;
684 			t->rn_parent = tt;	 		/* parent */
685 			if (x->rn_left == t)
686 				x->rn_left = tt;
687 			else
688 				x->rn_right = tt;
689 			saved_tt = tt; x = xx;
690 		} else {
691 			(tt = treenodes)->rn_dupedkey = t->rn_dupedkey;
692 			t->rn_dupedkey = tt;
693 			tt->rn_parent = t;			/* parent */
694 			if (tt->rn_dupedkey)			/* parent */
695 				tt->rn_dupedkey->rn_parent = tt; /* parent */
696 		}
697 #ifdef RN_DEBUG
698 		t=tt+1; tt->rn_info = rn_nodenum++; t->rn_info = rn_nodenum++;
699 		tt->rn_twin = t; tt->rn_ybro = rn_clist; rn_clist = tt;
700 #endif
701 		tt->rn_key = (caddr_t) v;
702 		tt->rn_bit = -1;
703 		tt->rn_flags = RNF_ACTIVE;
704 	}
705 	/*
706 	 * Put mask in tree.
707 	 */
708 	if (netmask) {
709 		tt->rn_mask = netmask;
710 		tt->rn_bit = x->rn_bit;
711 		tt->rn_flags |= x->rn_flags & RNF_NORMAL;
712 	}
713 	t = saved_tt->rn_parent;
714 	if (keyduplicated)
715 		goto on2;
716 	b_leaf = -1 - t->rn_bit;
717 	if (t->rn_right == saved_tt)
718 		x = t->rn_left;
719 	else
720 		x = t->rn_right;
721 	/* Promote general routes from below */
722 	if (x->rn_bit < 0) {
723 	    for (mp = &t->rn_mklist; x; x = x->rn_dupedkey)
724 		if (x->rn_mask && (x->rn_bit >= b_leaf) && x->rn_mklist == 0) {
725 			*mp = m = rn_new_radix_mask(x, 0);
726 			if (m)
727 				mp = &m->rm_mklist;
728 		}
729 	} else if (x->rn_mklist) {
730 		/*
731 		 * Skip over masks whose index is > that of new node
732 		 */
733 		for (mp = &x->rn_mklist; (m = *mp); mp = &m->rm_mklist)
734 			if (m->rm_bit >= b_leaf)
735 				break;
736 		t->rn_mklist = m; *mp = 0;
737 	}
738 on2:
739 	/* Add new route to highest possible ancestor's list */
740 	if ((netmask == 0) || (b > t->rn_bit ))
741 		return tt; /* can't lift at all */
742 	b_leaf = tt->rn_bit;
743 	do {
744 		x = t;
745 		t = t->rn_parent;
746 	} while (b <= t->rn_bit && x != top);
747 	/*
748 	 * Search through routes associated with node to
749 	 * insert new route according to index.
750 	 * Need same criteria as when sorting dupedkeys to avoid
751 	 * double loop on deletion.
752 	 */
753 	for (mp = &x->rn_mklist; (m = *mp); mp = &m->rm_mklist) {
754 		if (m->rm_bit < b_leaf)
755 			continue;
756 		if (m->rm_bit > b_leaf)
757 			break;
758 		if (m->rm_flags & RNF_NORMAL) {
759 			mmask = m->rm_leaf->rn_mask;
760 			if (tt->rn_flags & RNF_NORMAL) {
761 			    log(LOG_ERR,
762 			        "Non-unique normal route, mask not entered\n");
763 				return tt;
764 			}
765 		} else
766 			mmask = m->rm_mask;
767 		if (mmask == netmask) {
768 			m->rm_refs++;
769 			tt->rn_mklist = m;
770 			return tt;
771 		}
772 		if (rn_refines(netmask, mmask)
773 		    || rn_lexobetter(netmask, mmask))
774 			break;
775 	}
776 	*mp = rn_new_radix_mask(tt, *mp);
777 	return tt;
778 }
779 
780 struct radix_node *
781 rn_delete(v_arg, netmask_arg, head)
782 	void *v_arg, *netmask_arg;
783 	struct radix_node_head *head;
784 {
785 	register struct radix_node *t, *p, *x, *tt;
786 	struct radix_mask *m, *saved_m, **mp;
787 	struct radix_node *dupedkey, *saved_tt, *top;
788 	caddr_t v, netmask;
789 	int b, head_off, vlen;
790 
791 	v = v_arg;
792 	netmask = netmask_arg;
793 	x = head->rnh_treetop;
794 	tt = rn_search(v, x);
795 	head_off = x->rn_offset;
796 	vlen =  LEN(v);
797 	saved_tt = tt;
798 	top = x;
799 	if (tt == 0 ||
800 	    bcmp(v + head_off, tt->rn_key + head_off, vlen - head_off))
801 		return (0);
802 	/*
803 	 * Delete our route from mask lists.
804 	 */
805 	if (netmask) {
806 		if ((x = rn_addmask(netmask, 1, head_off)) == 0)
807 			return (0);
808 		netmask = x->rn_key;
809 		while (tt->rn_mask != netmask)
810 			if ((tt = tt->rn_dupedkey) == 0)
811 				return (0);
812 	}
813 	if (tt->rn_mask == 0 || (saved_m = m = tt->rn_mklist) == 0)
814 		goto on1;
815 	if (tt->rn_flags & RNF_NORMAL) {
816 		if (m->rm_leaf != tt || m->rm_refs > 0) {
817 			log(LOG_ERR, "rn_delete: inconsistent annotation\n");
818 			return 0;  /* dangling ref could cause disaster */
819 		}
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_bit;
829 	t = saved_tt->rn_parent;
830 	if (b > t->rn_bit)
831 		goto on1; /* Wasn't lifted at all */
832 	do {
833 		x = t;
834 		t = t->rn_parent;
835 	} while (b <= t->rn_bit && 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 	if (t) t->rn_ybro = tt->rn_ybro;
857 #endif
858 	t = tt->rn_parent;
859 	dupedkey = saved_tt->rn_dupedkey;
860 	if (dupedkey) {
861 		/*
862 		 * Here, tt is the deletion target and
863 		 * saved_tt is the head of the dupekey chain.
864 		 */
865 		if (tt == saved_tt) {
866 			/* remove from head of chain */
867 			x = dupedkey; x->rn_parent = t;
868 			if (t->rn_left == tt)
869 				t->rn_left = x;
870 			else
871 				t->rn_right = x;
872 		} else {
873 			/* find node in front of tt on the chain */
874 			for (x = p = saved_tt; p && p->rn_dupedkey != tt;)
875 				p = p->rn_dupedkey;
876 			if (p) {
877 				p->rn_dupedkey = tt->rn_dupedkey;
878 				if (tt->rn_dupedkey)		/* parent */
879 					tt->rn_dupedkey->rn_parent = p;
880 								/* parent */
881 			} else log(LOG_ERR, "rn_delete: couldn't find us\n");
882 		}
883 		t = tt + 1;
884 		if  (t->rn_flags & RNF_ACTIVE) {
885 #ifndef RN_DEBUG
886 			*++x = *t;
887 			p = t->rn_parent;
888 #else
889 			b = t->rn_info;
890 			*++x = *t;
891 			t->rn_info = b;
892 			p = t->rn_parent;
893 #endif
894 			if (p->rn_left == t)
895 				p->rn_left = x;
896 			else
897 				p->rn_right = x;
898 			x->rn_left->rn_parent = x;
899 			x->rn_right->rn_parent = x;
900 		}
901 		goto out;
902 	}
903 	if (t->rn_left == tt)
904 		x = t->rn_right;
905 	else
906 		x = t->rn_left;
907 	p = t->rn_parent;
908 	if (p->rn_right == t)
909 		p->rn_right = x;
910 	else
911 		p->rn_left = x;
912 	x->rn_parent = p;
913 	/*
914 	 * Demote routes attached to us.
915 	 */
916 	if (t->rn_mklist) {
917 		if (x->rn_bit >= 0) {
918 			for (mp = &x->rn_mklist; (m = *mp);)
919 				mp = &m->rm_mklist;
920 			*mp = t->rn_mklist;
921 		} else {
922 			/* If there are any key,mask pairs in a sibling
923 			   duped-key chain, some subset will appear sorted
924 			   in the same order attached to our mklist */
925 			for (m = t->rn_mklist; m && x; x = x->rn_dupedkey)
926 				if (m == x->rn_mklist) {
927 					struct radix_mask *mm = m->rm_mklist;
928 					x->rn_mklist = 0;
929 					if (--(m->rm_refs) < 0)
930 						MKFree(m);
931 					m = mm;
932 				}
933 			if (m)
934 				log(LOG_ERR,
935 				    "rn_delete: Orphaned Mask %p at %p\n",
936 				    (void *)m, (void *)x);
937 		}
938 	}
939 	/*
940 	 * We may be holding an active internal node in the tree.
941 	 */
942 	x = tt + 1;
943 	if (t != x) {
944 #ifndef RN_DEBUG
945 		*t = *x;
946 #else
947 		b = t->rn_info;
948 		*t = *x;
949 		t->rn_info = b;
950 #endif
951 		t->rn_left->rn_parent = t;
952 		t->rn_right->rn_parent = t;
953 		p = x->rn_parent;
954 		if (p->rn_left == x)
955 			p->rn_left = t;
956 		else
957 			p->rn_right = t;
958 	}
959 out:
960 	tt->rn_flags &= ~RNF_ACTIVE;
961 	tt[1].rn_flags &= ~RNF_ACTIVE;
962 	return (tt);
963 }
964 
965 /*
966  * This is the same as rn_walktree() except for the parameters and the
967  * exit.
968  */
969 static int
970 rn_walktree_from(h, a, m, f, w)
971 	struct radix_node_head *h;
972 	void *a, *m;
973 	walktree_f_t *f;
974 	void *w;
975 {
976 	int error;
977 	struct radix_node *base, *next;
978 	u_char *xa = (u_char *)a;
979 	u_char *xm = (u_char *)m;
980 	register struct radix_node *rn, *last = 0 /* shut up gcc */;
981 	int stopping = 0;
982 	int lastb;
983 
984 	/*
985 	 * rn_search_m is sort-of-open-coded here. We cannot use the
986 	 * function because we need to keep track of the last node seen.
987 	 */
988 	/* printf("about to search\n"); */
989 	for (rn = h->rnh_treetop; rn->rn_bit >= 0; ) {
990 		last = rn;
991 		/* printf("rn_bit %d, rn_bmask %x, xm[rn_offset] %x\n",
992 		       rn->rn_bit, rn->rn_bmask, xm[rn->rn_offset]); */
993 		if (!(rn->rn_bmask & xm[rn->rn_offset])) {
994 			break;
995 		}
996 		if (rn->rn_bmask & xa[rn->rn_offset]) {
997 			rn = rn->rn_right;
998 		} else {
999 			rn = rn->rn_left;
1000 		}
1001 	}
1002 	/* printf("done searching\n"); */
1003 
1004 	/*
1005 	 * Two cases: either we stepped off the end of our mask,
1006 	 * in which case last == rn, or we reached a leaf, in which
1007 	 * case we want to start from the last node we looked at.
1008 	 * Either way, last is the node we want to start from.
1009 	 */
1010 	rn = last;
1011 	lastb = rn->rn_bit;
1012 
1013 	/* printf("rn %p, lastb %d\n", rn, lastb);*/
1014 
1015 	/*
1016 	 * This gets complicated because we may delete the node
1017 	 * while applying the function f to it, so we need to calculate
1018 	 * the successor node in advance.
1019 	 */
1020 	while (rn->rn_bit >= 0)
1021 		rn = rn->rn_left;
1022 
1023 	while (!stopping) {
1024 		/* printf("node %p (%d)\n", rn, rn->rn_bit); */
1025 		base = rn;
1026 		/* If at right child go back up, otherwise, go right */
1027 		while (rn->rn_parent->rn_right == rn
1028 		       && !(rn->rn_flags & RNF_ROOT)) {
1029 			rn = rn->rn_parent;
1030 
1031 			/* if went up beyond last, stop */
1032 			if (rn->rn_bit <= lastb) {
1033 				stopping = 1;
1034 				/* printf("up too far\n"); */
1035 				/*
1036 				 * XXX we should jump to the 'Process leaves'
1037 				 * part, because the values of 'rn' and 'next'
1038 				 * we compute will not be used. Not a big deal
1039 				 * because this loop will terminate, but it is
1040 				 * inefficient and hard to understand!
1041 				 */
1042 			}
1043 		}
1044 
1045 		/*
1046 		 * At the top of the tree, no need to traverse the right
1047 		 * half, prevent the traversal of the entire tree in the
1048 		 * case of default route.
1049 		 */
1050 		if (rn->rn_parent->rn_flags & RNF_ROOT)
1051 			stopping = 1;
1052 
1053 		/* Find the next *leaf* since next node might vanish, too */
1054 		for (rn = rn->rn_parent->rn_right; rn->rn_bit >= 0;)
1055 			rn = rn->rn_left;
1056 		next = rn;
1057 		/* Process leaves */
1058 		while ((rn = base) != 0) {
1059 			base = rn->rn_dupedkey;
1060 			/* printf("leaf %p\n", rn); */
1061 			if (!(rn->rn_flags & RNF_ROOT)
1062 			    && (error = (*f)(rn, w)))
1063 				return (error);
1064 		}
1065 		rn = next;
1066 
1067 		if (rn->rn_flags & RNF_ROOT) {
1068 			/* printf("root, stopping"); */
1069 			stopping = 1;
1070 		}
1071 
1072 	}
1073 	return 0;
1074 }
1075 
1076 static int
1077 rn_walktree(h, f, w)
1078 	struct radix_node_head *h;
1079 	walktree_f_t *f;
1080 	void *w;
1081 {
1082 	int error;
1083 	struct radix_node *base, *next;
1084 	register struct radix_node *rn = h->rnh_treetop;
1085 	/*
1086 	 * This gets complicated because we may delete the node
1087 	 * while applying the function f to it, so we need to calculate
1088 	 * the successor node in advance.
1089 	 */
1090 
1091 	/* First time through node, go left */
1092 	while (rn->rn_bit >= 0)
1093 		rn = rn->rn_left;
1094 	for (;;) {
1095 		base = rn;
1096 		/* If at right child go back up, otherwise, go right */
1097 		while (rn->rn_parent->rn_right == rn
1098 		       && (rn->rn_flags & RNF_ROOT) == 0)
1099 			rn = rn->rn_parent;
1100 		/* Find the next *leaf* since next node might vanish, too */
1101 		for (rn = rn->rn_parent->rn_right; rn->rn_bit >= 0;)
1102 			rn = rn->rn_left;
1103 		next = rn;
1104 		/* Process leaves */
1105 		while ((rn = base)) {
1106 			base = rn->rn_dupedkey;
1107 			if (!(rn->rn_flags & RNF_ROOT)
1108 			    && (error = (*f)(rn, w)))
1109 				return (error);
1110 		}
1111 		rn = next;
1112 		if (rn->rn_flags & RNF_ROOT)
1113 			return (0);
1114 	}
1115 	/* NOTREACHED */
1116 }
1117 
1118 /*
1119  * Allocate and initialize an empty tree. This has 3 nodes, which are
1120  * part of the radix_node_head (in the order <left,root,right>) and are
1121  * marked RNF_ROOT so they cannot be freed.
1122  * The leaves have all-zero and all-one keys, with significant
1123  * bits starting at 'off'.
1124  * Return 1 on success, 0 on error.
1125  */
1126 int
1127 rn_inithead(head, off)
1128 	void **head;
1129 	int off;
1130 {
1131 	register struct radix_node_head *rnh;
1132 	register struct radix_node *t, *tt, *ttt;
1133 	if (*head)
1134 		return (1);
1135 	R_Zalloc(rnh, struct radix_node_head *, sizeof (*rnh));
1136 	if (rnh == 0)
1137 		return (0);
1138 #ifdef _KERNEL
1139 	RADIX_NODE_HEAD_LOCK_INIT(rnh);
1140 #endif
1141 	*head = rnh;
1142 	t = rn_newpair(rn_zeros, off, rnh->rnh_nodes);
1143 	ttt = rnh->rnh_nodes + 2;
1144 	t->rn_right = ttt;
1145 	t->rn_parent = t;
1146 	tt = t->rn_left;	/* ... which in turn is rnh->rnh_nodes */
1147 	tt->rn_flags = t->rn_flags = RNF_ROOT | RNF_ACTIVE;
1148 	tt->rn_bit = -1 - off;
1149 	*ttt = *tt;
1150 	ttt->rn_key = rn_ones;
1151 	rnh->rnh_addaddr = rn_addroute;
1152 	rnh->rnh_deladdr = rn_delete;
1153 	rnh->rnh_matchaddr = rn_match;
1154 	rnh->rnh_lookup = rn_lookup;
1155 	rnh->rnh_walktree = rn_walktree;
1156 	rnh->rnh_walktree_from = rn_walktree_from;
1157 	rnh->rnh_treetop = t;
1158 	return (1);
1159 }
1160 
1161 void
1162 rn_init()
1163 {
1164 	char *cp, *cplim;
1165 #ifdef _KERNEL
1166 	struct domain *dom;
1167 
1168 	for (dom = domains; dom; dom = dom->dom_next)
1169 		if (dom->dom_maxrtkey > max_keylen)
1170 			max_keylen = dom->dom_maxrtkey;
1171 #endif
1172 	if (max_keylen == 0) {
1173 		log(LOG_ERR,
1174 		    "rn_init: radix functions require max_keylen be set\n");
1175 		return;
1176 	}
1177 	R_Malloc(rn_zeros, char *, 3 * max_keylen);
1178 	if (rn_zeros == NULL)
1179 		panic("rn_init");
1180 	bzero(rn_zeros, 3 * max_keylen);
1181 	rn_ones = cp = rn_zeros + max_keylen;
1182 	addmask_key = cplim = rn_ones + max_keylen;
1183 	while (cp < cplim)
1184 		*cp++ = -1;
1185 	if (rn_inithead((void **)(void *)&mask_rnhead, 0) == 0)
1186 		panic("rn_init 2");
1187 }
1188