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