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