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