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