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