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