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