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