xref: /openbsd-src/sys/net/radix.c (revision 50b7afb2c2c0993b0894d4e34bf857cb13ed9c80)
1 /*	$OpenBSD: radix.c,v 1.42 2014/07/12 18:44:22 tedu Exp $	*/
2 /*	$NetBSD: radix.c,v 1.20 2003/08/07 16:32:56 agc Exp $	*/
3 
4 /*
5  * Copyright (c) 1988, 1989, 1993
6  *	The Regents of the University of California.  All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 3. Neither the name of the University nor the names of its contributors
17  *    may be used to endorse or promote products derived from this software
18  *    without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30  * SUCH DAMAGE.
31  *
32  *	@(#)radix.c	8.6 (Berkeley) 10/17/95
33  */
34 
35 /*
36  * Routines to build and maintain radix trees for routing lookups.
37  */
38 
39 #include <sys/param.h>
40 #include <sys/systm.h>
41 #include <sys/malloc.h>
42 #include <sys/domain.h>
43 #include <sys/syslog.h>
44 #include <sys/pool.h>
45 #include <net/radix.h>
46 
47 #ifndef SMALL_KERNEL
48 #include <sys/socket.h>
49 #include <net/route.h>
50 #include <net/radix_mpath.h>
51 #endif
52 
53 int	max_keylen;
54 struct radix_node_head *mask_rnhead;
55 static char *addmask_key;
56 static char normal_chars[] = {0, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe, -1};
57 static char *rn_zeros, *rn_ones;
58 
59 struct pool rtmask_pool;	/* pool for radix_mask structures */
60 
61 #define rn_masktop (mask_rnhead->rnh_treetop)
62 
63 static inline int rn_satisfies_leaf(char *, struct radix_node *, int);
64 static inline int rn_lexobetter(void *, void *);
65 static inline struct radix_mask *rn_new_radix_mask(struct radix_node *,
66     struct radix_mask *);
67 
68 struct radix_node *rn_insert(void *, struct radix_node_head *, int *,
69     struct radix_node [2]);
70 struct radix_node *rn_newpair(void *, int, struct radix_node[2]);
71 
72 static inline struct radix_node *rn_search(void *, struct radix_node *);
73 struct radix_node *rn_search_m(void *, struct radix_node *, void *);
74 int rn_add_dupedkey(struct radix_node *, struct radix_node_head *,
75     struct radix_node [2], u_int8_t);
76 void rn_fixup_nodes(struct radix_node *);
77 static inline struct radix_node *rn_lift_node(struct radix_node *);
78 void rn_add_radix_mask(struct radix_node *, int);
79 int rn_del_radix_mask(struct radix_node *);
80 static inline void rn_swap_nodes(struct radix_node *, struct radix_node *);
81 
82 /*
83  * The data structure for the keys is a radix tree with one way
84  * branching removed.  The index rn_b at an internal node n represents a bit
85  * position to be tested.  The tree is arranged so that all descendants
86  * of a node n have keys whose bits all agree up to position rn_b - 1.
87  * (We say the index of n is rn_b.)
88  *
89  * There is at least one descendant which has a one bit at position rn_b,
90  * and at least one with a zero there.
91  *
92  * A route is determined by a pair of key and mask.  We require that the
93  * bit-wise logical and of the key and mask to be the key.
94  * We define the index of a route to associated with the mask to be
95  * the first bit number in the mask where 0 occurs (with bit number 0
96  * representing the highest order bit).
97  *
98  * We say a mask is normal if every bit is 0, past the index of the mask.
99  * If a node n has a descendant (k, m) with index(m) == index(n) == rn_b,
100  * and m is a normal mask, then the route applies to every descendant of n.
101  * If the index(m) < rn_b, this implies the trailing last few bits of k
102  * before bit b are all 0, (and hence consequently true of every descendant
103  * of n), so the route applies to all descendants of the node as well.
104  *
105  * Similar logic shows that a non-normal mask m such that
106  * index(m) <= index(n) could potentially apply to many children of n.
107  * Thus, for each non-host route, we attach its mask to a list at an internal
108  * node as high in the tree as we can go.
109  *
110  * The present version of the code makes use of normal routes in short-
111  * circuiting an explicit mask and compare operation when testing whether
112  * a key satisfies a normal route, and also in remembering the unique leaf
113  * that governs a subtree.
114  */
115 
116 static inline struct radix_node *
117 rn_search(void *v_arg, struct radix_node *head)
118 {
119 	struct radix_node *x = head;
120 	caddr_t v = v_arg;
121 
122 	while (x->rn_b >= 0) {
123 		if (x->rn_bmask & v[x->rn_off])
124 			x = x->rn_r;
125 		else
126 			x = x->rn_l;
127 	}
128 	return (x);
129 }
130 
131 struct radix_node *
132 rn_search_m(void *v_arg, struct radix_node *head, void *m_arg)
133 {
134 	struct radix_node *x = head;
135 	caddr_t v = v_arg;
136 	caddr_t m = m_arg;
137 
138 	while (x->rn_b >= 0) {
139 		if ((x->rn_bmask & m[x->rn_off]) &&
140 		    (x->rn_bmask & v[x->rn_off]))
141 			x = x->rn_r;
142 		else
143 			x = x->rn_l;
144 	}
145 	return x;
146 }
147 
148 int
149 rn_refines(void *m_arg, void *n_arg)
150 {
151 	caddr_t m = m_arg;
152 	caddr_t n = n_arg;
153 	caddr_t lim, lim2;
154 	int longer;
155 	int masks_are_equal = 1;
156 
157 	lim2 = lim = n + *(u_char *)n;
158 	longer = (*(u_char *)n++) - (int)(*(u_char *)m++);
159 	if (longer > 0)
160 		lim -= longer;
161 	while (n < lim) {
162 		if (*n & ~(*m))
163 			return 0;
164 		if (*n++ != *m++)
165 			masks_are_equal = 0;
166 	}
167 	while (n < lim2)
168 		if (*n++)
169 			return 0;
170 	if (masks_are_equal && (longer < 0))
171 		for (lim2 = m - longer; m < lim2; )
172 			if (*m++)
173 				return 1;
174 	return (!masks_are_equal);
175 }
176 
177 /* return a perfect match if m_arg is set, else do a regular rn_match */
178 struct radix_node *
179 rn_lookup(void *v_arg, void *m_arg, struct radix_node_head *head)
180 {
181 	struct radix_node *x, *tm;
182 	caddr_t netmask = 0;
183 
184 	if (m_arg) {
185 		tm = rn_addmask(m_arg, 1, head->rnh_treetop->rn_off);
186 		if (tm == NULL)
187 			return (NULL);
188 		netmask = tm->rn_key;
189 	}
190 	x = rn_match(v_arg, head);
191 	if (x && netmask) {
192 		while (x && x->rn_mask != netmask)
193 			x = x->rn_dupedkey;
194 	}
195 	return x;
196 }
197 
198 static inline int
199 rn_satisfies_leaf(char *trial, struct radix_node *leaf, int skip)
200 {
201 	char *cp = trial;
202 	char *cp2 = leaf->rn_key;
203 	char *cp3 = leaf->rn_mask;
204 	char *cplim;
205 	int length;
206 
207 	length = min(*(u_char *)cp, *(u_char *)cp2);
208 	if (cp3 == NULL)
209 		cp3 = rn_ones;
210 	else
211 		length = min(length, *(u_char *)cp3);
212 	cplim = cp + length;
213 	cp += skip;
214 	cp2 += skip;
215 	cp3 += skip;
216 	while (cp < cplim) {
217 		if ((*cp ^ *cp2) & *cp3)
218 			return 0;
219 		cp++, cp2++, cp3++;
220 	}
221 	return 1;
222 }
223 
224 struct radix_node *
225 rn_match(void *v_arg, struct radix_node_head *head)
226 {
227 	caddr_t v = v_arg;
228 	caddr_t cp, cp2, cplim;
229 	struct radix_node *top = head->rnh_treetop;
230 	struct radix_node *saved_t, *t;
231 	int off = top->rn_off;
232 	int vlen, matched_off;
233 	int test, b, rn_b;
234 
235 	t = rn_search(v, top);
236 	/*
237 	 * See if we match exactly as a host destination
238 	 * or at least learn how many bits match, for normal mask finesse.
239 	 *
240 	 * It doesn't hurt us to limit how many bytes to check
241 	 * to the length of the mask, since if it matches we had a genuine
242 	 * match and the leaf we have is the most specific one anyway;
243 	 * if it didn't match with a shorter length it would fail
244 	 * with a long one.  This wins big for class B&C netmasks which
245 	 * are probably the most common case...
246 	 */
247 	if (t->rn_mask)
248 		vlen = *(u_char *)t->rn_mask;
249 	else
250 		vlen = *(u_char *)v;
251 	cp = v + off;
252 	cp2 = t->rn_key + off;
253 	cplim = v + vlen;
254 	for (; cp < cplim; cp++, cp2++)
255 		if (*cp != *cp2)
256 			goto on1;
257 	/*
258 	 * This extra grot is in case we are explicitly asked
259 	 * to look up the default.  Ugh!
260 	 */
261 	if ((t->rn_flags & RNF_ROOT) && t->rn_dupedkey)
262 		t = t->rn_dupedkey;
263 	return t;
264 on1:
265 	test = (*cp ^ *cp2) & 0xff; /* find first bit that differs */
266 	for (b = 7; (test >>= 1) > 0;)
267 		b--;
268 	matched_off = cp - v;
269 	b += matched_off << 3;
270 	rn_b = -1 - b;
271 	/*
272 	 * If there is a host route in a duped-key chain, it will be first.
273 	 */
274 	saved_t = t;
275 	if (t->rn_mask == NULL)
276 		t = t->rn_dupedkey;
277 	for (; t; t = t->rn_dupedkey)
278 		/*
279 		 * Even if we don't match exactly as a host,
280 		 * we may match if the leaf we wound up at is
281 		 * a route to a net.
282 		 */
283 		if (t->rn_flags & RNF_NORMAL) {
284 			if (rn_b <= t->rn_b)
285 				return t;
286 		} else if (rn_satisfies_leaf(v, t, matched_off))
287 				return t;
288 	t = saved_t;
289 	/* start searching up the tree */
290 	do {
291 		struct radix_mask *m;
292 		t = t->rn_p;
293 		m = t->rn_mklist;
294 		while (m) {
295 			/*
296 			 * If non-contiguous masks ever become important
297 			 * we can restore the masking and open coding of
298 			 * the search and satisfaction test and put the
299 			 * calculation of "off" back before the "do".
300 			 */
301 			if (m->rm_flags & RNF_NORMAL) {
302 				if (rn_b <= m->rm_b)
303 					return (m->rm_leaf);
304 			} else {
305 				struct radix_node *x;
306 				off = min(t->rn_off, matched_off);
307 				x = rn_search_m(v, t, m->rm_mask);
308 				while (x && x->rn_mask != m->rm_mask)
309 					x = x->rn_dupedkey;
310 				if (x && rn_satisfies_leaf(v, x, off))
311 					return x;
312 			}
313 			m = m->rm_mklist;
314 		}
315 	} while (t != top);
316 	return NULL;
317 }
318 
319 struct radix_node *
320 rn_newpair(void *v, int b, struct radix_node nodes[2])
321 {
322 	struct radix_node *tt = nodes, *t = nodes + 1;
323 	t->rn_b = b;
324 	t->rn_bmask = 0x80 >> (b & 7);
325 	t->rn_l = tt;
326 	t->rn_off = b >> 3;
327 	tt->rn_b = -1;
328 	tt->rn_key = v;
329 	tt->rn_p = t;
330 	tt->rn_flags = t->rn_flags = RNF_ACTIVE;
331 	return t;
332 }
333 
334 struct radix_node *
335 rn_insert(void *v_arg, struct radix_node_head *head,
336     int *dupentry, struct radix_node nodes[2])
337 {
338 	caddr_t v = v_arg;
339 	struct radix_node *top = head->rnh_treetop;
340 	struct radix_node *t, *tt;
341 	int off = top->rn_off;
342 	int b;
343 
344 	t = rn_search(v_arg, top);
345 	/*
346 	 * Find first bit at which v and t->rn_key differ
347 	 */
348     {
349 	caddr_t cp, cp2, cplim;
350 	int vlen, cmp_res;
351 
352 	vlen =  *(u_char *)v;
353 	cp = v + off;
354 	cp2 = t->rn_key + off;
355 	cplim = v + vlen;
356 
357 	while (cp < cplim)
358 		if (*cp2++ != *cp++)
359 			goto on1;
360 	*dupentry = 1;
361 	return t;
362 on1:
363 	*dupentry = 0;
364 	cmp_res = (cp[-1] ^ cp2[-1]) & 0xff;
365 	for (b = (cp - v) << 3; cmp_res; b--)
366 		cmp_res >>= 1;
367     }
368     {
369 	struct radix_node *p, *x = top;
370 	caddr_t cp = v;
371 	do {
372 		p = x;
373 		if (cp[x->rn_off] & x->rn_bmask)
374 			x = x->rn_r;
375 		else
376 			x = x->rn_l;
377 	} while (b > (unsigned int) x->rn_b); /* x->rn_b < b && x->rn_b >= 0 */
378 	t = rn_newpair(v_arg, b, nodes);
379 	tt = t->rn_l;
380 	if ((cp[p->rn_off] & p->rn_bmask) == 0)
381 		p->rn_l = t;
382 	else
383 		p->rn_r = t;
384 	x->rn_p = t;
385 	t->rn_p = p; /* frees x, p as temp vars below */
386 	if ((cp[t->rn_off] & t->rn_bmask) == 0) {
387 		t->rn_r = x;
388 	} else {
389 		t->rn_r = tt;
390 		t->rn_l = x;
391 	}
392     }
393 	return (tt);
394 }
395 
396 struct radix_node *
397 rn_addmask(void *n_arg, int search, int skip)
398 {
399 	caddr_t netmask = n_arg;
400 	struct radix_node *tm, *saved_tm;
401 	caddr_t cp, cplim;
402 	int b = 0, mlen, j;
403 	int maskduplicated, m0, isnormal;
404 	static int last_zeroed = 0;
405 
406 	if ((mlen = *(u_char *)netmask) > max_keylen)
407 		mlen = max_keylen;
408 	if (skip == 0)
409 		skip = 1;
410 	if (mlen <= skip)
411 		return (mask_rnhead->rnh_nodes);	/* rn_zero root node */
412 	if (skip > 1)
413 		memcpy(addmask_key + 1, rn_ones + 1, skip - 1);
414 	if ((m0 = mlen) > skip)
415 		memcpy(addmask_key + skip, netmask + skip, mlen - skip);
416 	/*
417 	 * Trim trailing zeroes.
418 	 */
419 	for (cp = addmask_key + mlen; (cp > addmask_key) && cp[-1] == 0;)
420 		cp--;
421 	mlen = cp - addmask_key;
422 	if (mlen <= skip) {
423 		if (m0 >= last_zeroed)
424 			last_zeroed = mlen;
425 		return (mask_rnhead->rnh_nodes);
426 	}
427 	if (m0 < last_zeroed)
428 		memset(addmask_key + m0, 0, last_zeroed - m0);
429 	*addmask_key = last_zeroed = mlen;
430 	tm = rn_search(addmask_key, rn_masktop);
431 	if (memcmp(addmask_key, tm->rn_key, mlen) != 0)
432 		tm = NULL;
433 	if (tm || search)
434 		return (tm);
435 	tm = malloc(max_keylen + 2 * sizeof (*tm), M_RTABLE, M_NOWAIT | M_ZERO);
436 	if (tm == NULL)
437 		return (0);
438 	saved_tm = tm;
439 	netmask = cp = (caddr_t)(tm + 2);
440 	memcpy(cp, addmask_key, mlen);
441 	tm = rn_insert(cp, mask_rnhead, &maskduplicated, tm);
442 	if (maskduplicated) {
443 		log(LOG_ERR, "rn_addmask: mask impossibly already in tree\n");
444 		free(saved_tm, M_RTABLE, 0);
445 		return (tm);
446 	}
447 	/*
448 	 * Calculate index of mask, and check for normalcy.
449 	 */
450 	cplim = netmask + mlen;
451 	isnormal = 1;
452 	for (cp = netmask + skip; (cp < cplim) && *(u_char *)cp == 0xff;)
453 		cp++;
454 	if (cp != cplim) {
455 		for (j = 0x80; (j & *cp) != 0; j >>= 1)
456 			b++;
457 		if (*cp != normal_chars[b] || cp != (cplim - 1))
458 			isnormal = 0;
459 	}
460 	b += (cp - netmask) << 3;
461 	tm->rn_b = -1 - b;
462 	if (isnormal)
463 		tm->rn_flags |= RNF_NORMAL;
464 	return (tm);
465 }
466 
467 /* rn_lexobetter: return a arbitrary ordering for non-contiguous masks */
468 static inline int
469 rn_lexobetter(void *m_arg, void *n_arg)
470 {
471 	u_char *mp = m_arg, *np = n_arg;
472 
473 	/*
474 	 * Longer masks might not really be lexicographically better,
475 	 * but longer masks always have precedence since they must be checked
476 	 * first. The netmasks were normalized before calling this function and
477 	 * don't have unneeded trailing zeros.
478 	 */
479 	if (*mp > *np)
480 		return 1;
481 	if (*mp < *np)
482 		return 0;
483 	/*
484 	 * Must return the first difference between the masks
485 	 * to ensure deterministic sorting.
486 	 */
487 	return (memcmp(mp, np, *mp) > 0);
488 }
489 
490 static inline struct radix_mask *
491 rn_new_radix_mask(struct radix_node *tt, struct radix_mask *next)
492 {
493 	struct radix_mask *m;
494 
495 	m = pool_get(&rtmask_pool, PR_NOWAIT | PR_ZERO);
496 	if (m == NULL) {
497 		log(LOG_ERR, "Mask for route not entered\n");
498 		return (0);
499 	}
500 	m->rm_b = tt->rn_b;
501 	m->rm_flags = tt->rn_flags;
502 	if (tt->rn_flags & RNF_NORMAL)
503 		m->rm_leaf = tt;
504 	else
505 		m->rm_mask = tt->rn_mask;
506 	m->rm_mklist = next;
507 	tt->rn_mklist = m;
508 	return m;
509 }
510 
511 /*
512  * Find the point where the rn_mklist needs to be changed.
513  */
514 static inline struct radix_node *
515 rn_lift_node(struct radix_node *t)
516 {
517 	struct radix_node *x = t;
518 	int b = -1 - t->rn_b;
519 
520 	/* rewind possible dupedkey list to head */
521 	while (t->rn_b < 0)
522 		t = t->rn_p;
523 
524 	/* can't lift node above head of dupedkey list, give up */
525 	if (b > t->rn_b)
526 		return (NULL);
527 
528 	do {
529 		x = t;
530 		t = t->rn_p;
531 	} while (b <= t->rn_b && x != t);
532 
533 	return (x);
534 }
535 
536 void
537 rn_add_radix_mask(struct radix_node *tt, int keyduplicated)
538 {
539 	caddr_t netmask, mmask;
540 	struct radix_node *x;
541 	struct radix_mask *m, **mp;
542 	int b_leaf = tt->rn_b;
543 
544 	/* Add new route to highest possible ancestor's list */
545 	if (tt->rn_mask == NULL)
546 		return; /* can't lift at all */
547 	x = rn_lift_node(tt);
548 	if (x == NULL)
549 		return; /* didn't lift either */
550 
551 	/*
552 	 * Search through routes associated with node to
553 	 * insert new route according to index.
554 	 * Need same criteria as when sorting dupedkeys to avoid
555 	 * double loop on deletion.
556 	 */
557 	netmask = tt->rn_mask;
558 	for (mp = &x->rn_mklist; (m = *mp); mp = &m->rm_mklist) {
559 		if (m->rm_b < b_leaf)
560 			continue;
561 		if (m->rm_b > b_leaf)
562 			break;
563 		if (m->rm_flags & RNF_NORMAL) {
564 			if (keyduplicated) {
565 				if (m->rm_leaf->rn_p == tt)
566 					/* new route is better */
567 					m->rm_leaf = tt;
568 #ifdef DIAGNOSTIC
569 				else {
570 					struct radix_node *t;
571 
572 					for (t = m->rm_leaf;
573 					    t && t->rn_mklist == m;
574 					    t = t->rn_dupedkey)
575 						if (t == tt)
576 							break;
577 					if (t == NULL) {
578 						log(LOG_ERR, "Non-unique "
579 						    "normal route on dupedkey, "
580 						    "mask not entered\n");
581 						return;
582 					}
583 				}
584 #endif
585 				m->rm_refs++;
586 				tt->rn_mklist = m;
587 				return;
588 			} else if (tt->rn_flags & RNF_NORMAL) {
589 				log(LOG_ERR, "Non-unique normal route,"
590 				    " mask not entered\n");
591 				return;
592 			}
593 			mmask = m->rm_leaf->rn_mask;
594 		} else
595 			mmask = m->rm_mask;
596 		if (mmask == netmask) {
597 			m->rm_refs++;
598 			tt->rn_mklist = m;
599 			return;
600 		}
601 		if (rn_refines(netmask, mmask) || rn_lexobetter(netmask, mmask))
602 			break;
603 	}
604 	*mp = rn_new_radix_mask(tt, *mp);
605 }
606 
607 int
608 rn_add_dupedkey(struct radix_node *saved_tt, struct radix_node_head *head,
609     struct radix_node *tt, u_int8_t prio)
610 {
611 	caddr_t netmask = tt->rn_mask;
612 	struct radix_node *x = saved_tt, *xp;
613 #ifndef SMALL_KERNEL
614 	struct radix_node *dupedkey_tt = NULL;
615 #endif
616 	int before = -1;
617 	int b_leaf = 0;
618 
619 	if (netmask)
620 		b_leaf = tt->rn_b;
621 
622 	for (xp = x; x; xp = x, x = x->rn_dupedkey) {
623 #ifndef SMALL_KERNEL
624 		/* permit multipath, if enabled for the family */
625 		if (rn_mpath_capable(head) && netmask == x->rn_mask) {
626 			int mid;
627 			/*
628 			 * Try to insert the new node in the middle
629 			 * of the list of any preexisting multipaths,
630 			 * to reduce the number of path disruptions
631 			 * that occur as a result of an insertion,
632 			 * per RFC2992.
633 			 * Additionally keep the list sorted by route
634 			 * priority.
635 			 */
636 			before = 0;
637 
638 			dupedkey_tt = x;
639 			x = rn_mpath_prio(x, prio);
640 			if (((struct rtentry *)x)->rt_priority !=
641 			    prio) {
642 				/*
643 				 * rn_mpath_prio returns the previous
644 				 * element if no element with the
645 				 * requested priority exists. It could
646 				 * be that the previous element comes
647 				 * with a bigger priority.
648 				 */
649 				if (((struct rtentry *)x)->rt_priority > prio)
650 					before = 1;
651 				xp = x;
652 				break;
653 			}
654 
655 			mid = rn_mpath_active_count(x) / 2;
656 			do {
657 				xp = x;
658 				x = rn_mpath_next(x, RMP_MODE_BYPRIO);
659 			} while (x && --mid > 0);
660 			break;
661 		}
662 #endif
663 		if (x->rn_mask == netmask)
664 			return (-1);
665 		if (netmask == NULL ||
666 		    (x->rn_mask &&
667 		     ((b_leaf < x->rn_b) || /* index(netmask) > node */
668 		       rn_refines(netmask, x->rn_mask) ||
669 		       rn_lexobetter(netmask, x->rn_mask))))
670 			break;
671 	}
672 	/*
673 	 * If the mask is not duplicated, we wouldn't
674 	 * find it among possible duplicate key entries
675 	 * anyway, so the above test doesn't hurt.
676 	 *
677 	 * We sort the masks for a duplicated key the same way as
678 	 * in a masklist -- most specific to least specific.
679 	 * This may require the unfortunate nuisance of relocating
680 	 * the head of the list.
681 	 *
682 	 * We also reverse, or doubly link the list through the
683 	 * parent pointer.
684 	 */
685 
686 	if ((x == saved_tt && before) || before == 1)
687 		before = 1;
688 	else
689 		before = 0;
690 	rn_link_dupedkey(tt, xp, before);
691 
692 
693 #ifndef SMALL_KERNEL
694 	/* adjust the flags of the possible multipath chain */
695 	if (!dupedkey_tt)
696 		dupedkey_tt = tt;
697 	if (rn_mpath_capable(head))
698 		rn_mpath_adj_mpflag(dupedkey_tt, prio);
699 #endif
700 	return (0);
701 }
702 
703 /*
704  * Insert tt after x or in place of x if before is true.
705  */
706 void
707 rn_link_dupedkey(struct radix_node *tt, struct radix_node *x, int before)
708 {
709 	if (before) {
710 		if (x->rn_p->rn_b > 0) {
711 			/* link in at head of list */
712 			tt->rn_dupedkey = x;
713 			tt->rn_flags = x->rn_flags;
714 			tt->rn_p = x->rn_p;
715 			x->rn_p = tt;
716 			if (tt->rn_p->rn_l == x)
717 				tt->rn_p->rn_l = tt;
718 			else
719 				tt->rn_p->rn_r = tt;
720 		} else {
721 			tt->rn_dupedkey = x;
722 			x->rn_p->rn_dupedkey = tt;
723 			tt->rn_p = x->rn_p;
724 			x->rn_p = tt;
725 		}
726 	} else {
727 		tt->rn_dupedkey = x->rn_dupedkey;
728 		x->rn_dupedkey = tt;
729 		tt->rn_p = x;
730 		if (tt->rn_dupedkey)
731 			tt->rn_dupedkey->rn_p = tt;
732 	}
733 }
734 
735 /*
736  * This function ensures that routes are properly promoted upwards.
737  * It adjusts the rn_mklist of the parent node to make sure overlapping
738  * routes can be found.
739  *
740  * There are two cases:
741  * - leaf nodes with possible rn_dupedkey list
742  * - internal nodes with maybe their own mklist
743  * If the mask of the route is bigger than the current branch bit then
744  * a rn_mklist entrie needs to be made.
745  */
746 void
747 rn_fixup_nodes(struct radix_node *tt)
748 {
749 	struct radix_node *tp, *x;
750 	struct radix_mask *m, **mp;
751 	int b_leaf;
752 
753 	tp = tt->rn_p;
754 	if (tp->rn_r == tt)
755 		x = tp->rn_l;
756 	else
757 		x = tp->rn_r;
758 
759 	b_leaf = -1 - tp->rn_b;
760 	if (x->rn_b < 0) {	/* x is a leaf node */
761 		struct	radix_node *xx = NULL;
762 
763 		for (mp = &tp->rn_mklist; x; xx = x, x = x->rn_dupedkey) {
764 			if (xx && xx->rn_mklist && xx->rn_mask == x->rn_mask &&
765 			    x->rn_mklist == 0) {
766 				/* multipath route */
767 				x->rn_mklist = xx->rn_mklist;
768 				x->rn_mklist->rm_refs++;
769 			}
770 			if (x->rn_mask && (x->rn_b >= b_leaf) &&
771 			    x->rn_mklist == 0) {
772 				*mp = m = rn_new_radix_mask(x, 0);
773 				if (m)
774 					mp = &m->rm_mklist;
775 			}
776 		}
777 	} else if (x->rn_mklist) {	/* x is an internal node */
778 		/*
779 		 * Skip over masks whose index is > that of new node
780 		 */
781 		for (mp = &x->rn_mklist; (m = *mp); mp = &m->rm_mklist)
782 			if (m->rm_b >= b_leaf)
783 				break;
784 		tp->rn_mklist = m;
785 		*mp = 0;
786 	}
787 }
788 
789 struct radix_node *
790 rn_addroute(void *v_arg, void *n_arg, struct radix_node_head *head,
791     struct radix_node treenodes[2], u_int8_t prio)
792 {
793 	caddr_t v = v_arg;
794 	struct radix_node *top = head->rnh_treetop;
795 	struct radix_node *tt, *saved_tt, *tm = NULL;
796 	int keyduplicated;
797 
798 	/*
799 	 * In dealing with non-contiguous masks, there may be
800 	 * many different routes which have the same mask.
801 	 * We will find it useful to have a unique pointer to
802 	 * the mask to speed avoiding duplicate references at
803 	 * nodes and possibly save time in calculating indices.
804 	 */
805 	if (n_arg)  {
806 		if ((tm = rn_addmask(n_arg, 0, top->rn_off)) == 0)
807 			return (0);
808 	}
809 
810 	tt = rn_insert(v, head, &keyduplicated, treenodes);
811 
812 	if (keyduplicated) {
813 		saved_tt = tt;
814 		tt = treenodes;
815 
816 		tt->rn_key = v_arg;
817 		tt->rn_b = -1;
818 		tt->rn_flags = RNF_ACTIVE;
819 	}
820 
821 	/* Put mask into the node. */
822 	if (tm) {
823 		tt->rn_mask = tm->rn_key;
824 		tt->rn_b = tm->rn_b;
825 		tt->rn_flags |= tm->rn_flags & RNF_NORMAL;
826 	}
827 
828 	/* Either insert into dupedkey list or as a leaf node.  */
829 	if (keyduplicated) {
830 		if (rn_add_dupedkey(saved_tt, head, tt, prio))
831 			return (NULL);
832 	} else {
833 		rn_fixup_nodes(tt);
834 #ifndef SMALL_KERNEL
835 		if (rn_mpath_capable(head))
836 			rn_mpath_adj_mpflag(tt, prio);
837 #endif
838 	}
839 
840 	/* finally insert a radix_mask element if needed */
841 	rn_add_radix_mask(tt, keyduplicated);
842 	return (tt);
843 }
844 
845 /*
846  * Cleanup mask list, tt points to route that needs to be cleaned
847  */
848 int
849 rn_del_radix_mask(struct radix_node *tt)
850 {
851 	struct radix_node *x;
852 	struct radix_mask *m, *saved_m, **mp;
853 
854 	/*
855 	 * Cleanup mask list from possible references to this route.
856 	 */
857 	saved_m = m = tt->rn_mklist;
858 	if (tt->rn_mask == NULL || m == NULL)
859 		return (0);
860 
861 	if (tt->rn_flags & RNF_NORMAL) {
862 		if (m->rm_leaf != tt && m->rm_refs == 0) {
863 			log(LOG_ERR, "rn_delete: inconsistent normal "
864 			    "annotation\n");
865 			return (-1);
866 		}
867 		if (m->rm_leaf != tt) {
868 			if (--m->rm_refs >= 0)
869 				return (0);
870 			else
871 				log(LOG_ERR, "rn_delete: "
872 				    "inconsistent mklist refcount\n");
873 		}
874 		/*
875 		 * If we end up here tt should be m->rm_leaf and therefor
876 		 * tt should be the head of a multipath chain.
877 		 * If this is not the case the table is no longer consistent.
878 		 */
879 		if (m->rm_refs > 0) {
880 			if (tt->rn_dupedkey == NULL ||
881 			    tt->rn_dupedkey->rn_mklist != m) {
882 				log(LOG_ERR, "rn_delete: inconsistent "
883 				    "dupedkey list\n");
884 				return (-1);
885 			}
886 			m->rm_leaf = tt->rn_dupedkey;
887 			--m->rm_refs;
888 			return (0);
889 		}
890 		/* else tt is last and only route */
891 	} else {
892 		if (m->rm_mask != tt->rn_mask) {
893 			log(LOG_ERR, "rn_delete: inconsistent annotation\n");
894 			return (0);
895 		}
896 		if (--m->rm_refs >= 0)
897 			return (0);
898 	}
899 
900 	/*
901 	 * No other references hold to the radix_mask remove it from
902 	 * the tree.
903 	 */
904 	x = rn_lift_node(tt);
905 	if (x == NULL)
906 		return (0);	/* Wasn't lifted at all */
907 
908 	/* Finally eliminate the radix_mask from the tree */
909 	for (mp = &x->rn_mklist; (m = *mp); mp = &m->rm_mklist)
910 		if (m == saved_m) {
911 			*mp = m->rm_mklist;
912 			pool_put(&rtmask_pool, m);
913 			break;
914 		}
915 
916 	if (m == NULL) {
917 		log(LOG_ERR, "rn_delete: couldn't find our annotation\n");
918 		if (tt->rn_flags & RNF_NORMAL)
919 			return (-1); /* Dangling ref to us */
920 	}
921 
922 	return (0);
923 }
924 
925 /* swap two internal nodes and fixup the parent and child pointers */
926 static inline void
927 rn_swap_nodes(struct radix_node *from, struct radix_node *to)
928 {
929 	*to = *from;
930 	if (from->rn_p->rn_l == from)
931 		from->rn_p->rn_l = to;
932 	else
933 		from->rn_p->rn_r = to;
934 
935 	to->rn_l->rn_p = to;
936 	to->rn_r->rn_p = to;
937 }
938 
939 struct radix_node *
940 rn_delete(void *v_arg, void *n_arg, struct radix_node_head *head,
941     struct radix_node *rn)
942 {
943 	caddr_t v = v_arg;
944 	caddr_t netmask = n_arg;
945 	struct radix_node *top = head->rnh_treetop;
946 	struct radix_node *tt, *tp, *pp, *x;
947 	struct radix_node *dupedkey_tt, *saved_tt;
948 	int off = top->rn_off;
949 	int vlen;
950 
951 	vlen =  *(u_char *)v;
952 
953 	/*
954 	 * Implement a lookup similar to rn_lookup but we need to save
955 	 * the radix leaf node (where th rn_dupedkey list starts) so
956 	 * it is not possible to use rn_lookup.
957 	 */
958 	tt = rn_search(v, top);
959 	/* make sure the key is a perfect match */
960 	if (memcmp(v + off, tt->rn_key + off, vlen - off))
961 		return (0);
962 
963 	/*
964 	 * Here, tt is the deletion target, and
965 	 * saved_tt is the head of the dupedkey chain.
966 	 * dupedkey_tt will point to the start of the multipath chain.
967 	 */
968 	saved_tt = tt;
969 
970 	/*
971 	 * make tt point to the start of the rn_dupedkey list of multipath
972 	 * routes.
973 	 */
974 	if (netmask) {
975 		struct radix_node *tm;
976 
977 		if ((tm = rn_addmask(netmask, 1, off)) == NULL)
978 			return (0);
979 		netmask = tm->rn_key;
980 		while (tt->rn_mask != netmask)
981 			if ((tt = tt->rn_dupedkey) == NULL)
982 				return (0);
983 	}
984 
985 	/* save start of multi path chain for later use */
986 	dupedkey_tt = tt;
987 
988 #ifndef SMALL_KERNEL
989 	/* if we got a hint use the hint from now on */
990 	if (rn)
991 		tt = rn;
992 #endif
993 
994 	KASSERT((tt->rn_flags & RNF_ROOT) == 0);
995 
996 	/* remove possible radix_mask */
997 	if (rn_del_radix_mask(tt))
998 		return (0);
999 
1000 	/*
1001 	 * Finally eliminate us from tree
1002 	 */
1003 	tp = tt->rn_p;
1004 	if (saved_tt->rn_dupedkey) {
1005 		if (tt == saved_tt) {
1006 			x = saved_tt->rn_dupedkey;
1007 			x->rn_p = tp;
1008 			if (tp->rn_l == tt)
1009 				tp->rn_l = x;
1010 			else
1011 				tp->rn_r = x;
1012 		} else {
1013 			x = saved_tt;
1014 			tp->rn_dupedkey = tt->rn_dupedkey;
1015 			if (tt->rn_dupedkey)
1016 				tt->rn_dupedkey->rn_p = tp;
1017 		}
1018 
1019 		/*
1020 		 * We may be holding an active internal node in the tree.
1021 		 */
1022 		if  (tt[1].rn_flags & RNF_ACTIVE)
1023 			rn_swap_nodes(&tt[1], &x[1]);
1024 
1025 #ifndef SMALL_KERNEL
1026 		/* adjust the flags of the multipath chain */
1027 		if (rn_mpath_capable(head))
1028 			rn_mpath_adj_mpflag(dupedkey_tt,
1029 			    ((struct rtentry *)tt)->rt_priority);
1030 #endif
1031 		/* over and out */
1032 		goto out;
1033 	}
1034 
1035 	/* non-rn_dupedkey case, remove tt and tp node from the tree */
1036 	if (tp->rn_l == tt)
1037 		x = tp->rn_r;
1038 	else
1039 		x = tp->rn_l;
1040 	pp = tp->rn_p;
1041 	if (pp->rn_r == tp)
1042 		pp->rn_r = x;
1043 	else
1044 		pp->rn_l = x;
1045 	x->rn_p = pp;
1046 
1047 	/*
1048 	 * Demote routes attached to us (actually on the internal parent node).
1049 	 */
1050 	if (tp->rn_mklist) {
1051 		struct radix_mask *m, **mp;
1052 		if (x->rn_b >= 0) {
1053 			for (mp = &x->rn_mklist; (m = *mp);)
1054 				mp = &m->rm_mklist;
1055 			*mp = tp->rn_mklist;
1056 		} else {
1057 			/* If there are any key,mask pairs in a sibling
1058 			   duped-key chain, some subset will appear sorted
1059 			   in the same order attached to our mklist */
1060 			for (m = tp->rn_mklist; m && x; x = x->rn_dupedkey)
1061 				if (m == x->rn_mklist) {
1062 					struct radix_mask *mm = m->rm_mklist;
1063 					x->rn_mklist = 0;
1064 					if (--(m->rm_refs) < 0)
1065 						pool_put(&rtmask_pool, m);
1066 					else if (m->rm_flags & RNF_NORMAL)
1067 						/*
1068 						 * don't progress because this
1069 						 * a multipath route. Next
1070 						 * route will use the same m.
1071 						 */
1072 						mm = m;
1073 					m = mm;
1074 				}
1075 			if (m)
1076 				log(LOG_ERR, "%s %p at %p\n",
1077 				    "rn_delete: Orphaned Mask", m, x);
1078 		}
1079 	}
1080 
1081 	/*
1082 	 * We may be holding an active internal node in the tree.
1083 	 * If so swap our internal node (t) with the parent node (tp)
1084 	 * since that one was just removed from the tree.
1085 	 */
1086 	if (tp != &tt[1])
1087 		rn_swap_nodes(&tt[1], tp);
1088 
1089 	/* no rn_dupedkey list so no need to fixup multipath chains */
1090 out:
1091 	tt[0].rn_flags &= ~RNF_ACTIVE;
1092 	tt[1].rn_flags &= ~RNF_ACTIVE;
1093 	return (tt);
1094 }
1095 
1096 int
1097 rn_walktree(struct radix_node_head *h, int (*f)(struct radix_node *, void *,
1098     u_int), void *w)
1099 {
1100 	int error;
1101 	struct radix_node *base, *next;
1102 	struct radix_node *rn = h->rnh_treetop;
1103 	/*
1104 	 * This gets complicated because we may delete the node
1105 	 * while applying the function f to it, so we need to calculate
1106 	 * the successor node in advance.
1107 	 */
1108 	/* First time through node, go left */
1109 	while (rn->rn_b >= 0)
1110 		rn = rn->rn_l;
1111 	for (;;) {
1112 		base = rn;
1113 		/* If at right child go back up, otherwise, go right */
1114 		while (rn->rn_p->rn_r == rn && (rn->rn_flags & RNF_ROOT) == 0)
1115 			rn = rn->rn_p;
1116 		/* Find the next *leaf* since next node might vanish, too */
1117 		for (rn = rn->rn_p->rn_r; rn->rn_b >= 0;)
1118 			rn = rn->rn_l;
1119 		next = rn;
1120 		/* Process leaves */
1121 		while ((rn = base) != NULL) {
1122 			base = rn->rn_dupedkey;
1123 			if (!(rn->rn_flags & RNF_ROOT) &&
1124 			    (error = (*f)(rn, w, h->rnh_rtableid)))
1125 				return (error);
1126 		}
1127 		rn = next;
1128 		if (rn->rn_flags & RNF_ROOT)
1129 			return (0);
1130 	}
1131 	/* NOTREACHED */
1132 }
1133 
1134 int
1135 rn_inithead(void **head, int off)
1136 {
1137 	struct radix_node_head *rnh;
1138 
1139 	if (*head)
1140 		return (1);
1141 	rnh = malloc(sizeof(*rnh), M_RTABLE, M_NOWAIT);
1142 	if (rnh == NULL)
1143 		return (0);
1144 	*head = rnh;
1145 	return rn_inithead0(rnh, off);
1146 }
1147 
1148 int
1149 rn_inithead0(struct radix_node_head *rnh, int off)
1150 {
1151 	struct radix_node *t, *tt, *ttt;
1152 
1153 	memset(rnh, 0, sizeof(*rnh));
1154 	t = rn_newpair(rn_zeros, off, rnh->rnh_nodes);
1155 	ttt = rnh->rnh_nodes + 2;
1156 	t->rn_r = ttt;
1157 	t->rn_p = t;
1158 	tt = t->rn_l;
1159 	tt->rn_flags = t->rn_flags = RNF_ROOT | RNF_ACTIVE;
1160 	tt->rn_b = -1 - off;
1161 	*ttt = *tt;
1162 	ttt->rn_key = rn_ones;
1163 	rnh->rnh_addaddr = rn_addroute;
1164 	rnh->rnh_deladdr = rn_delete;
1165 	rnh->rnh_matchaddr = rn_match;
1166 	rnh->rnh_lookup = rn_lookup;
1167 	rnh->rnh_walktree = rn_walktree;
1168 	rnh->rnh_treetop = t;
1169 	return (1);
1170 }
1171 
1172 void
1173 rn_init(void)
1174 {
1175 	char *cp, *cplim;
1176 	struct domain *dom;
1177 
1178 	pool_init(&rtmask_pool, sizeof(struct radix_mask), 0, 0, 0, "rtmask",
1179 	    NULL);
1180 	for (dom = domains; dom; dom = dom->dom_next)
1181 		if (dom->dom_maxrtkey > max_keylen)
1182 			max_keylen = dom->dom_maxrtkey;
1183 	if (max_keylen == 0) {
1184 		log(LOG_ERR,
1185 		    "rn_init: radix functions require max_keylen be set\n");
1186 		return;
1187 	}
1188 	rn_zeros = malloc(3 * max_keylen, M_RTABLE, M_NOWAIT | M_ZERO);
1189 	if (rn_zeros == NULL)
1190 		panic("rn_init");
1191 	rn_ones = cp = rn_zeros + max_keylen;
1192 	addmask_key = cplim = rn_ones + max_keylen;
1193 	while (cp < cplim)
1194 		*cp++ = -1;
1195 	if (rn_inithead((void *)&mask_rnhead, 0) == 0)
1196 		panic("rn_init 2");
1197 }
1198