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