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