xref: /freebsd/sys/net/radix.c (revision ab0b9f6b3073e6c4d1dfbf07444d7db67a189a96)
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 	unsigned char *netmask = n_arg;
488 	unsigned char *cp, *cplim;
489 	struct radix_node *x;
490 	int b = 0, mlen, j;
491 	int maskduplicated, isnormal;
492 	struct radix_node *saved_x;
493 	unsigned 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 bits should be contiguous, otherwise we have got
536 	 * a non-contiguous mask.
537 	 */
538 #define	CONTIG(_c)	(((~(_c) + 1) & (_c)) == (unsigned char)(~(_c) + 1))
539 	cplim = netmask + mlen;
540 	isnormal = 1;
541 	for (cp = netmask + skip; (cp < cplim) && *(u_char *)cp == 0xff;)
542 		cp++;
543 	if (cp != cplim) {
544 		for (j = 0x80; (j & *cp) != 0; j >>= 1)
545 			b++;
546 		if (!CONTIG(*cp) || cp != (cplim - 1))
547 			isnormal = 0;
548 	}
549 	b += (cp - netmask) << 3;
550 	x->rn_bit = -1 - b;
551 	if (isnormal)
552 		x->rn_flags |= RNF_NORMAL;
553 	return (x);
554 }
555 
556 static int	/* XXX: arbitrary ordering for non-contiguous masks */
557 rn_lexobetter(m_arg, n_arg)
558 	void *m_arg, *n_arg;
559 {
560 	register u_char *mp = m_arg, *np = n_arg, *lim;
561 
562 	if (LEN(mp) > LEN(np))
563 		return 1;  /* not really, but need to check longer one first */
564 	if (LEN(mp) == LEN(np))
565 		for (lim = mp + LEN(mp); mp < lim;)
566 			if (*mp++ > *np++)
567 				return 1;
568 	return 0;
569 }
570 
571 static struct radix_mask *
572 rn_new_radix_mask(tt, next)
573 	register struct radix_node *tt;
574 	register struct radix_mask *next;
575 {
576 	register struct radix_mask *m;
577 
578 	R_Malloc(m, struct radix_mask *, sizeof (struct radix_mask));
579 	if (m == 0) {
580 		log(LOG_ERR, "Failed to allocate route mask\n");
581 		return (0);
582 	}
583 	bzero(m, sizeof(*m));
584 	m->rm_bit = tt->rn_bit;
585 	m->rm_flags = tt->rn_flags;
586 	if (tt->rn_flags & RNF_NORMAL)
587 		m->rm_leaf = tt;
588 	else
589 		m->rm_mask = tt->rn_mask;
590 	m->rm_mklist = next;
591 	tt->rn_mklist = m;
592 	return m;
593 }
594 
595 struct radix_node *
596 rn_addroute(v_arg, n_arg, head, treenodes)
597 	void *v_arg, *n_arg;
598 	struct radix_node_head *head;
599 	struct radix_node treenodes[2];
600 {
601 	caddr_t v = (caddr_t)v_arg, netmask = (caddr_t)n_arg;
602 	register struct radix_node *t, *x = 0, *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 = 0;
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(v_arg, netmask_arg, head)
773 	void *v_arg, *netmask_arg;
774 	struct radix_node_head *head;
775 {
776 	register 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 == 0 ||
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) == 0)
803 				return (0);
804 	}
805 	if (tt->rn_mask == 0 || (saved_m = m = tt->rn_mklist) == 0)
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 			Free(m);
832 			break;
833 		}
834 	if (m == 0) {
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 						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 static int
962 rn_walktree_from(h, a, m, f, w)
963 	struct radix_node_head *h;
964 	void *a, *m;
965 	walktree_f_t *f;
966 	void *w;
967 {
968 	int error;
969 	struct radix_node *base, *next;
970 	u_char *xa = (u_char *)a;
971 	u_char *xm = (u_char *)m;
972 	register struct radix_node *rn, *last = 0 /* shut up gcc */;
973 	int stopping = 0;
974 	int lastb;
975 
976 	/*
977 	 * rn_search_m is sort-of-open-coded here. We cannot use the
978 	 * function because we need to keep track of the last node seen.
979 	 */
980 	/* printf("about to search\n"); */
981 	for (rn = h->rnh_treetop; rn->rn_bit >= 0; ) {
982 		last = rn;
983 		/* printf("rn_bit %d, rn_bmask %x, xm[rn_offset] %x\n",
984 		       rn->rn_bit, rn->rn_bmask, xm[rn->rn_offset]); */
985 		if (!(rn->rn_bmask & xm[rn->rn_offset])) {
986 			break;
987 		}
988 		if (rn->rn_bmask & xa[rn->rn_offset]) {
989 			rn = rn->rn_right;
990 		} else {
991 			rn = rn->rn_left;
992 		}
993 	}
994 	/* printf("done searching\n"); */
995 
996 	/*
997 	 * Two cases: either we stepped off the end of our mask,
998 	 * in which case last == rn, or we reached a leaf, in which
999 	 * case we want to start from the last node we looked at.
1000 	 * Either way, last is the node we want to start from.
1001 	 */
1002 	rn = last;
1003 	lastb = rn->rn_bit;
1004 
1005 	/* printf("rn %p, lastb %d\n", rn, lastb);*/
1006 
1007 	/*
1008 	 * This gets complicated because we may delete the node
1009 	 * while applying the function f to it, so we need to calculate
1010 	 * the successor node in advance.
1011 	 */
1012 	while (rn->rn_bit >= 0)
1013 		rn = rn->rn_left;
1014 
1015 	while (!stopping) {
1016 		/* printf("node %p (%d)\n", rn, rn->rn_bit); */
1017 		base = rn;
1018 		/* If at right child go back up, otherwise, go right */
1019 		while (rn->rn_parent->rn_right == rn
1020 		       && !(rn->rn_flags & RNF_ROOT)) {
1021 			rn = rn->rn_parent;
1022 
1023 			/* if went up beyond last, stop */
1024 			if (rn->rn_bit <= lastb) {
1025 				stopping = 1;
1026 				/* printf("up too far\n"); */
1027 				/*
1028 				 * XXX we should jump to the 'Process leaves'
1029 				 * part, because the values of 'rn' and 'next'
1030 				 * we compute will not be used. Not a big deal
1031 				 * because this loop will terminate, but it is
1032 				 * inefficient and hard to understand!
1033 				 */
1034 			}
1035 		}
1036 
1037 		/*
1038 		 * At the top of the tree, no need to traverse the right
1039 		 * half, prevent the traversal of the entire tree in the
1040 		 * case of default route.
1041 		 */
1042 		if (rn->rn_parent->rn_flags & RNF_ROOT)
1043 			stopping = 1;
1044 
1045 		/* Find the next *leaf* since next node might vanish, too */
1046 		for (rn = rn->rn_parent->rn_right; rn->rn_bit >= 0;)
1047 			rn = rn->rn_left;
1048 		next = rn;
1049 		/* Process leaves */
1050 		while ((rn = base) != 0) {
1051 			base = rn->rn_dupedkey;
1052 			/* printf("leaf %p\n", rn); */
1053 			if (!(rn->rn_flags & RNF_ROOT)
1054 			    && (error = (*f)(rn, w)))
1055 				return (error);
1056 		}
1057 		rn = next;
1058 
1059 		if (rn->rn_flags & RNF_ROOT) {
1060 			/* printf("root, stopping"); */
1061 			stopping = 1;
1062 		}
1063 
1064 	}
1065 	return 0;
1066 }
1067 
1068 static int
1069 rn_walktree(h, f, w)
1070 	struct radix_node_head *h;
1071 	walktree_f_t *f;
1072 	void *w;
1073 {
1074 	int error;
1075 	struct radix_node *base, *next;
1076 	register struct radix_node *rn = h->rnh_treetop;
1077 	/*
1078 	 * This gets complicated because we may delete the node
1079 	 * while applying the function f to it, so we need to calculate
1080 	 * the successor node in advance.
1081 	 */
1082 
1083 	/* First time through node, go left */
1084 	while (rn->rn_bit >= 0)
1085 		rn = rn->rn_left;
1086 	for (;;) {
1087 		base = rn;
1088 		/* If at right child go back up, otherwise, go right */
1089 		while (rn->rn_parent->rn_right == rn
1090 		       && (rn->rn_flags & RNF_ROOT) == 0)
1091 			rn = rn->rn_parent;
1092 		/* Find the next *leaf* since next node might vanish, too */
1093 		for (rn = rn->rn_parent->rn_right; rn->rn_bit >= 0;)
1094 			rn = rn->rn_left;
1095 		next = rn;
1096 		/* Process leaves */
1097 		while ((rn = base)) {
1098 			base = rn->rn_dupedkey;
1099 			if (!(rn->rn_flags & RNF_ROOT)
1100 			    && (error = (*f)(rn, w)))
1101 				return (error);
1102 		}
1103 		rn = next;
1104 		if (rn->rn_flags & RNF_ROOT)
1105 			return (0);
1106 	}
1107 	/* NOTREACHED */
1108 }
1109 
1110 /*
1111  * Allocate and initialize an empty tree. This has 3 nodes, which are
1112  * part of the radix_node_head (in the order <left,root,right>) and are
1113  * marked RNF_ROOT so they cannot be freed.
1114  * The leaves have all-zero and all-one keys, with significant
1115  * bits starting at 'off'.
1116  * Return 1 on success, 0 on error.
1117  */
1118 static int
1119 rn_inithead_internal(void **head, int off)
1120 {
1121 	register struct radix_node_head *rnh;
1122 	register struct radix_node *t, *tt, *ttt;
1123 	if (*head)
1124 		return (1);
1125 	R_Zalloc(rnh, struct radix_node_head *, sizeof (*rnh));
1126 	if (rnh == 0)
1127 		return (0);
1128 #ifdef _KERNEL
1129 	RADIX_NODE_HEAD_LOCK_INIT(rnh);
1130 #endif
1131 	*head = rnh;
1132 	t = rn_newpair(rn_zeros, off, rnh->rnh_nodes);
1133 	ttt = rnh->rnh_nodes + 2;
1134 	t->rn_right = ttt;
1135 	t->rn_parent = t;
1136 	tt = t->rn_left;	/* ... which in turn is rnh->rnh_nodes */
1137 	tt->rn_flags = t->rn_flags = RNF_ROOT | RNF_ACTIVE;
1138 	tt->rn_bit = -1 - off;
1139 	*ttt = *tt;
1140 	ttt->rn_key = rn_ones;
1141 	rnh->rnh_addaddr = rn_addroute;
1142 	rnh->rnh_deladdr = rn_delete;
1143 	rnh->rnh_matchaddr = rn_match;
1144 	rnh->rnh_lookup = rn_lookup;
1145 	rnh->rnh_walktree = rn_walktree;
1146 	rnh->rnh_walktree_from = rn_walktree_from;
1147 	rnh->rnh_treetop = t;
1148 	return (1);
1149 }
1150 
1151 static void
1152 rn_detachhead_internal(void **head)
1153 {
1154 	struct radix_node_head *rnh;
1155 
1156 	KASSERT((head != NULL && *head != NULL),
1157 	    ("%s: head already freed", __func__));
1158 	rnh = *head;
1159 
1160 	/* Free <left,root,right> nodes. */
1161 	Free(rnh);
1162 
1163 	*head = NULL;
1164 }
1165 
1166 int
1167 rn_inithead(void **head, int off)
1168 {
1169 	struct radix_node_head *rnh;
1170 
1171 	if (*head != NULL)
1172 		return (1);
1173 
1174 	if (rn_inithead_internal(head, off) == 0)
1175 		return (0);
1176 
1177 	rnh = (struct radix_node_head *)(*head);
1178 
1179 	if (rn_inithead_internal((void **)&rnh->rnh_masks, 0) == 0) {
1180 		rn_detachhead_internal(head);
1181 		return (0);
1182 	}
1183 
1184 	return (1);
1185 }
1186 
1187 int
1188 rn_detachhead(void **head)
1189 {
1190 	struct radix_node_head *rnh;
1191 
1192 	KASSERT((head != NULL && *head != NULL),
1193 	    ("%s: head already freed", __func__));
1194 
1195 	rnh = *head;
1196 
1197 	rn_detachhead_internal((void **)&rnh->rnh_masks);
1198 	rn_detachhead_internal(head);
1199 	return (1);
1200 }
1201 
1202