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