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