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