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