]> CyberLeo.Net >> Repos - FreeBSD/releng/10.0.git/blob - sys/net/radix.c
- Copy stable/10 (r259064) to releng/10.0 as part of the
[FreeBSD/releng/10.0.git] / sys / net / radix.c
1 /*-
2  * Copyright (c) 1988, 1989, 1993
3  *      The Regents of the University of California.  All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 4. Neither the name of the University nor the names of its contributors
14  *    may be used to endorse or promote products derived from this software
15  *    without specific prior written permission.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
21  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  *
29  *      @(#)radix.c     8.5 (Berkeley) 5/19/95
30  * $FreeBSD$
31  */
32
33 /*
34  * Routines to build and maintain radix trees for routing lookups.
35  */
36 #include <sys/param.h>
37 #ifdef  _KERNEL
38 #include <sys/lock.h>
39 #include <sys/mutex.h>
40 #include <sys/rwlock.h>
41 #include <sys/systm.h>
42 #include <sys/malloc.h>
43 #include <sys/syslog.h>
44 #include <net/radix.h>
45 #include "opt_mpath.h"
46 #ifdef RADIX_MPATH
47 #include <net/radix_mpath.h>
48 #endif
49 #else /* !_KERNEL */
50 #include <stdio.h>
51 #include <strings.h>
52 #include <stdlib.h>
53 #define log(x, arg...)  fprintf(stderr, ## arg)
54 #define panic(x)        fprintf(stderr, "PANIC: %s", x), exit(1)
55 #define min(a, b) ((a) < (b) ? (a) : (b) )
56 #include <net/radix.h>
57 #endif /* !_KERNEL */
58
59 static int      rn_walktree_from(struct radix_node_head *h, void *a, void *m,
60                     walktree_f_t *f, void *w);
61 static int rn_walktree(struct radix_node_head *, walktree_f_t *, void *);
62 static struct radix_node
63          *rn_insert(void *, struct radix_node_head *, int *,
64              struct radix_node [2]),
65          *rn_newpair(void *, int, struct radix_node[2]),
66          *rn_search(void *, struct radix_node *),
67          *rn_search_m(void *, struct radix_node *, void *);
68
69 static void rn_detachhead_internal(void **head);
70 static int rn_inithead_internal(void **head, int off);
71
72 #define RADIX_MAX_KEY_LEN       32
73
74 static char rn_zeros[RADIX_MAX_KEY_LEN];
75 static char rn_ones[RADIX_MAX_KEY_LEN] = {
76         -1, -1, -1, -1, -1, -1, -1, -1,
77         -1, -1, -1, -1, -1, -1, -1, -1,
78         -1, -1, -1, -1, -1, -1, -1, -1,
79         -1, -1, -1, -1, -1, -1, -1, -1,
80 };
81
82 /*
83  * XXX: Compat stuff for old rn_addmask() users
84  */
85 static struct radix_node_head *mask_rnhead_compat;
86 #ifdef  _KERNEL
87 static struct mtx mask_mtx;
88 #endif
89
90
91 static int      rn_lexobetter(void *m_arg, void *n_arg);
92 static struct radix_mask *
93                 rn_new_radix_mask(struct radix_node *tt,
94                     struct radix_mask *next);
95 static int      rn_satisfies_leaf(char *trial, struct radix_node *leaf,
96                     int skip);
97
98 /*
99  * The data structure for the keys is a radix tree with one way
100  * branching removed.  The index rn_bit at an internal node n represents a bit
101  * position to be tested.  The tree is arranged so that all descendants
102  * of a node n have keys whose bits all agree up to position rn_bit - 1.
103  * (We say the index of n is rn_bit.)
104  *
105  * There is at least one descendant which has a one bit at position rn_bit,
106  * and at least one with a zero there.
107  *
108  * A route is determined by a pair of key and mask.  We require that the
109  * bit-wise logical and of the key and mask to be the key.
110  * We define the index of a route to associated with the mask to be
111  * the first bit number in the mask where 0 occurs (with bit number 0
112  * representing the highest order bit).
113  *
114  * We say a mask is normal if every bit is 0, past the index of the mask.
115  * If a node n has a descendant (k, m) with index(m) == index(n) == rn_bit,
116  * and m is a normal mask, then the route applies to every descendant of n.
117  * If the index(m) < rn_bit, this implies the trailing last few bits of k
118  * before bit b are all 0, (and hence consequently true of every descendant
119  * of n), so the route applies to all descendants of the node as well.
120  *
121  * Similar logic shows that a non-normal mask m such that
122  * index(m) <= index(n) could potentially apply to many children of n.
123  * Thus, for each non-host route, we attach its mask to a list at an internal
124  * node as high in the tree as we can go.
125  *
126  * The present version of the code makes use of normal routes in short-
127  * circuiting an explict mask and compare operation when testing whether
128  * a key satisfies a normal route, and also in remembering the unique leaf
129  * that governs a subtree.
130  */
131
132 /*
133  * Most of the functions in this code assume that the key/mask arguments
134  * are sockaddr-like structures, where the first byte is an u_char
135  * indicating the size of the entire structure.
136  *
137  * To make the assumption more explicit, we use the LEN() macro to access
138  * this field. It is safe to pass an expression with side effects
139  * to LEN() as the argument is evaluated only once.
140  * We cast the result to int as this is the dominant usage.
141  */
142 #define LEN(x) ( (int) (*(const u_char *)(x)) )
143
144 /*
145  * XXX THIS NEEDS TO BE FIXED
146  * In the code, pointers to keys and masks are passed as either
147  * 'void *' (because callers use to pass pointers of various kinds), or
148  * 'caddr_t' (which is fine for pointer arithmetics, but not very
149  * clean when you dereference it to access data). Furthermore, caddr_t
150  * is really 'char *', while the natural type to operate on keys and
151  * masks would be 'u_char'. This mismatch require a lot of casts and
152  * intermediate variables to adapt types that clutter the code.
153  */
154
155 /*
156  * Search a node in the tree matching the key.
157  */
158 static struct radix_node *
159 rn_search(v_arg, head)
160         void *v_arg;
161         struct radix_node *head;
162 {
163         register struct radix_node *x;
164         register caddr_t v;
165
166         for (x = head, v = v_arg; x->rn_bit >= 0;) {
167                 if (x->rn_bmask & v[x->rn_offset])
168                         x = x->rn_right;
169                 else
170                         x = x->rn_left;
171         }
172         return (x);
173 }
174
175 /*
176  * Same as above, but with an additional mask.
177  * XXX note this function is used only once.
178  */
179 static struct radix_node *
180 rn_search_m(v_arg, head, m_arg)
181         struct radix_node *head;
182         void *v_arg, *m_arg;
183 {
184         register struct radix_node *x;
185         register caddr_t v = v_arg, m = m_arg;
186
187         for (x = head; x->rn_bit >= 0;) {
188                 if ((x->rn_bmask & m[x->rn_offset]) &&
189                     (x->rn_bmask & v[x->rn_offset]))
190                         x = x->rn_right;
191                 else
192                         x = x->rn_left;
193         }
194         return x;
195 }
196
197 int
198 rn_refines(m_arg, n_arg)
199         void *m_arg, *n_arg;
200 {
201         register caddr_t m = m_arg, n = n_arg;
202         register caddr_t lim, lim2 = lim = n + LEN(n);
203         int longer = LEN(n++) - LEN(m++);
204         int masks_are_equal = 1;
205
206         if (longer > 0)
207                 lim -= longer;
208         while (n < lim) {
209                 if (*n & ~(*m))
210                         return 0;
211                 if (*n++ != *m++)
212                         masks_are_equal = 0;
213         }
214         while (n < lim2)
215                 if (*n++)
216                         return 0;
217         if (masks_are_equal && (longer < 0))
218                 for (lim2 = m - longer; m < lim2; )
219                         if (*m++)
220                                 return 1;
221         return (!masks_are_equal);
222 }
223
224 struct radix_node *
225 rn_lookup(v_arg, m_arg, head)
226         void *v_arg, *m_arg;
227         struct radix_node_head *head;
228 {
229         register struct radix_node *x;
230         caddr_t netmask = 0;
231
232         if (m_arg) {
233                 x = rn_addmask_r(m_arg, head->rnh_masks, 1,
234                     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_r(void *arg, struct radix_node_head *maskhead, int search, int skip)
494 {
495         caddr_t netmask = (caddr_t)arg;
496         register struct radix_node *x;
497         register caddr_t cp, cplim;
498         register int b = 0, mlen, j;
499         int maskduplicated, isnormal;
500         struct radix_node *saved_x;
501         char addmask_key[RADIX_MAX_KEY_LEN];
502
503         if ((mlen = LEN(netmask)) > RADIX_MAX_KEY_LEN)
504                 mlen = RADIX_MAX_KEY_LEN;
505         if (skip == 0)
506                 skip = 1;
507         if (mlen <= skip)
508                 return (maskhead->rnh_nodes);
509
510         bzero(addmask_key, RADIX_MAX_KEY_LEN);
511         if (skip > 1)
512                 bcopy(rn_ones + 1, addmask_key + 1, skip - 1);
513         bcopy(netmask + skip, addmask_key + skip, mlen - skip);
514         /*
515          * Trim trailing zeroes.
516          */
517         for (cp = addmask_key + mlen; (cp > addmask_key) && cp[-1] == 0;)
518                 cp--;
519         mlen = cp - addmask_key;
520         if (mlen <= skip)
521                 return (maskhead->rnh_nodes);
522         *addmask_key = mlen;
523         x = rn_search(addmask_key, maskhead->rnh_treetop);
524         if (bcmp(addmask_key, x->rn_key, mlen) != 0)
525                 x = 0;
526         if (x || search)
527                 return (x);
528         R_Zalloc(x, struct radix_node *, RADIX_MAX_KEY_LEN + 2 * sizeof (*x));
529         if ((saved_x = x) == 0)
530                 return (0);
531         netmask = cp = (caddr_t)(x + 2);
532         bcopy(addmask_key, cp, mlen);
533         x = rn_insert(cp, maskhead, &maskduplicated, x);
534         if (maskduplicated) {
535                 log(LOG_ERR, "rn_addmask: mask impossibly already in tree");
536                 Free(saved_x);
537                 return (x);
538         }
539         /*
540          * Calculate index of mask, and check for normalcy.
541          * First find the first byte with a 0 bit, then if there are
542          * more bits left (remember we already trimmed the trailing 0's),
543          * the pattern must be one of those in normal_chars[], or we have
544          * a non-contiguous mask.
545          */
546         cplim = netmask + mlen;
547         isnormal = 1;
548         for (cp = netmask + skip; (cp < cplim) && *(u_char *)cp == 0xff;)
549                 cp++;
550         if (cp != cplim) {
551                 static char normal_chars[] = {
552                         0, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe, 0xff};
553
554                 for (j = 0x80; (j & *cp) != 0; j >>= 1)
555                         b++;
556                 if (*cp != normal_chars[b] || cp != (cplim - 1))
557                         isnormal = 0;
558         }
559         b += (cp - netmask) << 3;
560         x->rn_bit = -1 - b;
561         if (isnormal)
562                 x->rn_flags |= RNF_NORMAL;
563         return (x);
564 }
565
566 struct radix_node *
567 rn_addmask(void *n_arg, int search, int skip)
568 {
569         struct radix_node *tt;
570
571 #ifdef _KERNEL
572         mtx_lock(&mask_mtx);
573 #endif
574         tt = rn_addmask_r(&mask_rnhead_compat, n_arg, search, skip);
575
576 #ifdef _KERNEL
577         mtx_unlock(&mask_mtx);
578 #endif
579
580         return (tt);
581 }
582
583 static int      /* XXX: arbitrary ordering for non-contiguous masks */
584 rn_lexobetter(m_arg, n_arg)
585         void *m_arg, *n_arg;
586 {
587         register u_char *mp = m_arg, *np = n_arg, *lim;
588
589         if (LEN(mp) > LEN(np))
590                 return 1;  /* not really, but need to check longer one first */
591         if (LEN(mp) == LEN(np))
592                 for (lim = mp + LEN(mp); mp < lim;)
593                         if (*mp++ > *np++)
594                                 return 1;
595         return 0;
596 }
597
598 static struct radix_mask *
599 rn_new_radix_mask(tt, next)
600         register struct radix_node *tt;
601         register struct radix_mask *next;
602 {
603         register struct radix_mask *m;
604
605         R_Malloc(m, struct radix_mask *, sizeof (struct radix_mask));
606         if (m == 0) {
607                 log(LOG_ERR, "Failed to allocate route mask\n");
608                 return (0);
609         }
610         bzero(m, sizeof(*m));
611         m->rm_bit = tt->rn_bit;
612         m->rm_flags = tt->rn_flags;
613         if (tt->rn_flags & RNF_NORMAL)
614                 m->rm_leaf = tt;
615         else
616                 m->rm_mask = tt->rn_mask;
617         m->rm_mklist = next;
618         tt->rn_mklist = m;
619         return m;
620 }
621
622 struct radix_node *
623 rn_addroute(v_arg, n_arg, head, treenodes)
624         void *v_arg, *n_arg;
625         struct radix_node_head *head;
626         struct radix_node treenodes[2];
627 {
628         caddr_t v = (caddr_t)v_arg, netmask = (caddr_t)n_arg;
629         register struct radix_node *t, *x = 0, *tt;
630         struct radix_node *saved_tt, *top = head->rnh_treetop;
631         short b = 0, b_leaf = 0;
632         int keyduplicated;
633         caddr_t mmask;
634         struct radix_mask *m, **mp;
635
636         /*
637          * In dealing with non-contiguous masks, there may be
638          * many different routes which have the same mask.
639          * We will find it useful to have a unique pointer to
640          * the mask to speed avoiding duplicate references at
641          * nodes and possibly save time in calculating indices.
642          */
643         if (netmask)  {
644                 x = rn_addmask_r(netmask, head->rnh_masks, 0, top->rn_offset);
645                 if (x == NULL)
646                         return (0);
647                 b_leaf = x->rn_bit;
648                 b = -1 - x->rn_bit;
649                 netmask = x->rn_key;
650         }
651         /*
652          * Deal with duplicated keys: attach node to previous instance
653          */
654         saved_tt = tt = rn_insert(v, head, &keyduplicated, treenodes);
655         if (keyduplicated) {
656                 for (t = tt; tt; t = tt, tt = tt->rn_dupedkey) {
657 #ifdef RADIX_MPATH
658                         /* permit multipath, if enabled for the family */
659                         if (rn_mpath_capable(head) && netmask == tt->rn_mask) {
660                                 /*
661                                  * go down to the end of multipaths, so that
662                                  * new entry goes into the end of rn_dupedkey
663                                  * chain.
664                                  */
665                                 do {
666                                         t = tt;
667                                         tt = tt->rn_dupedkey;
668                                 } while (tt && t->rn_mask == tt->rn_mask);
669                                 break;
670                         }
671 #endif
672                         if (tt->rn_mask == netmask)
673                                 return (0);
674                         if (netmask == 0 ||
675                             (tt->rn_mask &&
676                              ((b_leaf < tt->rn_bit) /* index(netmask) > node */
677                               || rn_refines(netmask, tt->rn_mask)
678                               || rn_lexobetter(netmask, tt->rn_mask))))
679                                 break;
680                 }
681                 /*
682                  * If the mask is not duplicated, we wouldn't
683                  * find it among possible duplicate key entries
684                  * anyway, so the above test doesn't hurt.
685                  *
686                  * We sort the masks for a duplicated key the same way as
687                  * in a masklist -- most specific to least specific.
688                  * This may require the unfortunate nuisance of relocating
689                  * the head of the list.
690                  *
691                  * We also reverse, or doubly link the list through the
692                  * parent pointer.
693                  */
694                 if (tt == saved_tt) {
695                         struct  radix_node *xx = x;
696                         /* link in at head of list */
697                         (tt = treenodes)->rn_dupedkey = t;
698                         tt->rn_flags = t->rn_flags;
699                         tt->rn_parent = x = t->rn_parent;
700                         t->rn_parent = tt;                      /* parent */
701                         if (x->rn_left == t)
702                                 x->rn_left = tt;
703                         else
704                                 x->rn_right = tt;
705                         saved_tt = tt; x = xx;
706                 } else {
707                         (tt = treenodes)->rn_dupedkey = t->rn_dupedkey;
708                         t->rn_dupedkey = tt;
709                         tt->rn_parent = t;                      /* parent */
710                         if (tt->rn_dupedkey)                    /* parent */
711                                 tt->rn_dupedkey->rn_parent = tt; /* parent */
712                 }
713 #ifdef RN_DEBUG
714                 t=tt+1; tt->rn_info = rn_nodenum++; t->rn_info = rn_nodenum++;
715                 tt->rn_twin = t; tt->rn_ybro = rn_clist; rn_clist = tt;
716 #endif
717                 tt->rn_key = (caddr_t) v;
718                 tt->rn_bit = -1;
719                 tt->rn_flags = RNF_ACTIVE;
720         }
721         /*
722          * Put mask in tree.
723          */
724         if (netmask) {
725                 tt->rn_mask = netmask;
726                 tt->rn_bit = x->rn_bit;
727                 tt->rn_flags |= x->rn_flags & RNF_NORMAL;
728         }
729         t = saved_tt->rn_parent;
730         if (keyduplicated)
731                 goto on2;
732         b_leaf = -1 - t->rn_bit;
733         if (t->rn_right == saved_tt)
734                 x = t->rn_left;
735         else
736                 x = t->rn_right;
737         /* Promote general routes from below */
738         if (x->rn_bit < 0) {
739             for (mp = &t->rn_mklist; x; x = x->rn_dupedkey)
740                 if (x->rn_mask && (x->rn_bit >= b_leaf) && x->rn_mklist == 0) {
741                         *mp = m = rn_new_radix_mask(x, 0);
742                         if (m)
743                                 mp = &m->rm_mklist;
744                 }
745         } else if (x->rn_mklist) {
746                 /*
747                  * Skip over masks whose index is > that of new node
748                  */
749                 for (mp = &x->rn_mklist; (m = *mp); mp = &m->rm_mklist)
750                         if (m->rm_bit >= b_leaf)
751                                 break;
752                 t->rn_mklist = m; *mp = 0;
753         }
754 on2:
755         /* Add new route to highest possible ancestor's list */
756         if ((netmask == 0) || (b > t->rn_bit ))
757                 return tt; /* can't lift at all */
758         b_leaf = tt->rn_bit;
759         do {
760                 x = t;
761                 t = t->rn_parent;
762         } while (b <= t->rn_bit && x != top);
763         /*
764          * Search through routes associated with node to
765          * insert new route according to index.
766          * Need same criteria as when sorting dupedkeys to avoid
767          * double loop on deletion.
768          */
769         for (mp = &x->rn_mklist; (m = *mp); mp = &m->rm_mklist) {
770                 if (m->rm_bit < b_leaf)
771                         continue;
772                 if (m->rm_bit > b_leaf)
773                         break;
774                 if (m->rm_flags & RNF_NORMAL) {
775                         mmask = m->rm_leaf->rn_mask;
776                         if (tt->rn_flags & RNF_NORMAL) {
777 #if !defined(RADIX_MPATH)
778                             log(LOG_ERR,
779                                 "Non-unique normal route, mask not entered\n");
780 #endif
781                                 return tt;
782                         }
783                 } else
784                         mmask = m->rm_mask;
785                 if (mmask == netmask) {
786                         m->rm_refs++;
787                         tt->rn_mklist = m;
788                         return tt;
789                 }
790                 if (rn_refines(netmask, mmask)
791                     || rn_lexobetter(netmask, mmask))
792                         break;
793         }
794         *mp = rn_new_radix_mask(tt, *mp);
795         return tt;
796 }
797
798 struct radix_node *
799 rn_delete(v_arg, netmask_arg, head)
800         void *v_arg, *netmask_arg;
801         struct radix_node_head *head;
802 {
803         register struct radix_node *t, *p, *x, *tt;
804         struct radix_mask *m, *saved_m, **mp;
805         struct radix_node *dupedkey, *saved_tt, *top;
806         caddr_t v, netmask;
807         int b, head_off, vlen;
808
809         v = v_arg;
810         netmask = netmask_arg;
811         x = head->rnh_treetop;
812         tt = rn_search(v, x);
813         head_off = x->rn_offset;
814         vlen =  LEN(v);
815         saved_tt = tt;
816         top = x;
817         if (tt == 0 ||
818             bcmp(v + head_off, tt->rn_key + head_off, vlen - head_off))
819                 return (0);
820         /*
821          * Delete our route from mask lists.
822          */
823         if (netmask) {
824                 x = rn_addmask_r(netmask, head->rnh_masks, 1, head_off);
825                 if (x == NULL)
826                         return (0);
827                 netmask = x->rn_key;
828                 while (tt->rn_mask != netmask)
829                         if ((tt = tt->rn_dupedkey) == 0)
830                                 return (0);
831         }
832         if (tt->rn_mask == 0 || (saved_m = m = tt->rn_mklist) == 0)
833                 goto on1;
834         if (tt->rn_flags & RNF_NORMAL) {
835                 if (m->rm_leaf != tt || m->rm_refs > 0) {
836                         log(LOG_ERR, "rn_delete: inconsistent annotation\n");
837                         return 0;  /* dangling ref could cause disaster */
838                 }
839         } else {
840                 if (m->rm_mask != tt->rn_mask) {
841                         log(LOG_ERR, "rn_delete: inconsistent annotation\n");
842                         goto on1;
843                 }
844                 if (--m->rm_refs >= 0)
845                         goto on1;
846         }
847         b = -1 - tt->rn_bit;
848         t = saved_tt->rn_parent;
849         if (b > t->rn_bit)
850                 goto on1; /* Wasn't lifted at all */
851         do {
852                 x = t;
853                 t = t->rn_parent;
854         } while (b <= t->rn_bit && x != top);
855         for (mp = &x->rn_mklist; (m = *mp); mp = &m->rm_mklist)
856                 if (m == saved_m) {
857                         *mp = m->rm_mklist;
858                         Free(m);
859                         break;
860                 }
861         if (m == 0) {
862                 log(LOG_ERR, "rn_delete: couldn't find our annotation\n");
863                 if (tt->rn_flags & RNF_NORMAL)
864                         return (0); /* Dangling ref to us */
865         }
866 on1:
867         /*
868          * Eliminate us from tree
869          */
870         if (tt->rn_flags & RNF_ROOT)
871                 return (0);
872 #ifdef RN_DEBUG
873         /* Get us out of the creation list */
874         for (t = rn_clist; t && t->rn_ybro != tt; t = t->rn_ybro) {}
875         if (t) t->rn_ybro = tt->rn_ybro;
876 #endif
877         t = tt->rn_parent;
878         dupedkey = saved_tt->rn_dupedkey;
879         if (dupedkey) {
880                 /*
881                  * Here, tt is the deletion target and
882                  * saved_tt is the head of the dupekey chain.
883                  */
884                 if (tt == saved_tt) {
885                         /* remove from head of chain */
886                         x = dupedkey; x->rn_parent = t;
887                         if (t->rn_left == tt)
888                                 t->rn_left = x;
889                         else
890                                 t->rn_right = x;
891                 } else {
892                         /* find node in front of tt on the chain */
893                         for (x = p = saved_tt; p && p->rn_dupedkey != tt;)
894                                 p = p->rn_dupedkey;
895                         if (p) {
896                                 p->rn_dupedkey = tt->rn_dupedkey;
897                                 if (tt->rn_dupedkey)            /* parent */
898                                         tt->rn_dupedkey->rn_parent = p;
899                                                                 /* parent */
900                         } else log(LOG_ERR, "rn_delete: couldn't find us\n");
901                 }
902                 t = tt + 1;
903                 if  (t->rn_flags & RNF_ACTIVE) {
904 #ifndef RN_DEBUG
905                         *++x = *t;
906                         p = t->rn_parent;
907 #else
908                         b = t->rn_info;
909                         *++x = *t;
910                         t->rn_info = b;
911                         p = t->rn_parent;
912 #endif
913                         if (p->rn_left == t)
914                                 p->rn_left = x;
915                         else
916                                 p->rn_right = x;
917                         x->rn_left->rn_parent = x;
918                         x->rn_right->rn_parent = x;
919                 }
920                 goto out;
921         }
922         if (t->rn_left == tt)
923                 x = t->rn_right;
924         else
925                 x = t->rn_left;
926         p = t->rn_parent;
927         if (p->rn_right == t)
928                 p->rn_right = x;
929         else
930                 p->rn_left = x;
931         x->rn_parent = p;
932         /*
933          * Demote routes attached to us.
934          */
935         if (t->rn_mklist) {
936                 if (x->rn_bit >= 0) {
937                         for (mp = &x->rn_mklist; (m = *mp);)
938                                 mp = &m->rm_mklist;
939                         *mp = t->rn_mklist;
940                 } else {
941                         /* If there are any key,mask pairs in a sibling
942                            duped-key chain, some subset will appear sorted
943                            in the same order attached to our mklist */
944                         for (m = t->rn_mklist; m && x; x = x->rn_dupedkey)
945                                 if (m == x->rn_mklist) {
946                                         struct radix_mask *mm = m->rm_mklist;
947                                         x->rn_mklist = 0;
948                                         if (--(m->rm_refs) < 0)
949                                                 Free(m);
950                                         m = mm;
951                                 }
952                         if (m)
953                                 log(LOG_ERR,
954                                     "rn_delete: Orphaned Mask %p at %p\n",
955                                     m, x);
956                 }
957         }
958         /*
959          * We may be holding an active internal node in the tree.
960          */
961         x = tt + 1;
962         if (t != x) {
963 #ifndef RN_DEBUG
964                 *t = *x;
965 #else
966                 b = t->rn_info;
967                 *t = *x;
968                 t->rn_info = b;
969 #endif
970                 t->rn_left->rn_parent = t;
971                 t->rn_right->rn_parent = t;
972                 p = x->rn_parent;
973                 if (p->rn_left == x)
974                         p->rn_left = t;
975                 else
976                         p->rn_right = t;
977         }
978 out:
979         tt->rn_flags &= ~RNF_ACTIVE;
980         tt[1].rn_flags &= ~RNF_ACTIVE;
981         return (tt);
982 }
983
984 /*
985  * This is the same as rn_walktree() except for the parameters and the
986  * exit.
987  */
988 static int
989 rn_walktree_from(h, a, m, f, w)
990         struct radix_node_head *h;
991         void *a, *m;
992         walktree_f_t *f;
993         void *w;
994 {
995         int error;
996         struct radix_node *base, *next;
997         u_char *xa = (u_char *)a;
998         u_char *xm = (u_char *)m;
999         register struct radix_node *rn, *last = 0 /* shut up gcc */;
1000         int stopping = 0;
1001         int lastb;
1002
1003         /*
1004          * rn_search_m is sort-of-open-coded here. We cannot use the
1005          * function because we need to keep track of the last node seen.
1006          */
1007         /* printf("about to search\n"); */
1008         for (rn = h->rnh_treetop; rn->rn_bit >= 0; ) {
1009                 last = rn;
1010                 /* printf("rn_bit %d, rn_bmask %x, xm[rn_offset] %x\n",
1011                        rn->rn_bit, rn->rn_bmask, xm[rn->rn_offset]); */
1012                 if (!(rn->rn_bmask & xm[rn->rn_offset])) {
1013                         break;
1014                 }
1015                 if (rn->rn_bmask & xa[rn->rn_offset]) {
1016                         rn = rn->rn_right;
1017                 } else {
1018                         rn = rn->rn_left;
1019                 }
1020         }
1021         /* printf("done searching\n"); */
1022
1023         /*
1024          * Two cases: either we stepped off the end of our mask,
1025          * in which case last == rn, or we reached a leaf, in which
1026          * case we want to start from the last node we looked at.
1027          * Either way, last is the node we want to start from.
1028          */
1029         rn = last;
1030         lastb = rn->rn_bit;
1031
1032         /* printf("rn %p, lastb %d\n", rn, lastb);*/
1033
1034         /*
1035          * This gets complicated because we may delete the node
1036          * while applying the function f to it, so we need to calculate
1037          * the successor node in advance.
1038          */
1039         while (rn->rn_bit >= 0)
1040                 rn = rn->rn_left;
1041
1042         while (!stopping) {
1043                 /* printf("node %p (%d)\n", rn, rn->rn_bit); */
1044                 base = rn;
1045                 /* If at right child go back up, otherwise, go right */
1046                 while (rn->rn_parent->rn_right == rn
1047                        && !(rn->rn_flags & RNF_ROOT)) {
1048                         rn = rn->rn_parent;
1049
1050                         /* if went up beyond last, stop */
1051                         if (rn->rn_bit <= lastb) {
1052                                 stopping = 1;
1053                                 /* printf("up too far\n"); */
1054                                 /*
1055                                  * XXX we should jump to the 'Process leaves'
1056                                  * part, because the values of 'rn' and 'next'
1057                                  * we compute will not be used. Not a big deal
1058                                  * because this loop will terminate, but it is
1059                                  * inefficient and hard to understand!
1060                                  */
1061                         }
1062                 }
1063                 
1064                 /* 
1065                  * At the top of the tree, no need to traverse the right
1066                  * half, prevent the traversal of the entire tree in the
1067                  * case of default route.
1068                  */
1069                 if (rn->rn_parent->rn_flags & RNF_ROOT)
1070                         stopping = 1;
1071
1072                 /* Find the next *leaf* since next node might vanish, too */
1073                 for (rn = rn->rn_parent->rn_right; rn->rn_bit >= 0;)
1074                         rn = rn->rn_left;
1075                 next = rn;
1076                 /* Process leaves */
1077                 while ((rn = base) != 0) {
1078                         base = rn->rn_dupedkey;
1079                         /* printf("leaf %p\n", rn); */
1080                         if (!(rn->rn_flags & RNF_ROOT)
1081                             && (error = (*f)(rn, w)))
1082                                 return (error);
1083                 }
1084                 rn = next;
1085
1086                 if (rn->rn_flags & RNF_ROOT) {
1087                         /* printf("root, stopping"); */
1088                         stopping = 1;
1089                 }
1090
1091         }
1092         return 0;
1093 }
1094
1095 static int
1096 rn_walktree(h, f, w)
1097         struct radix_node_head *h;
1098         walktree_f_t *f;
1099         void *w;
1100 {
1101         int error;
1102         struct radix_node *base, *next;
1103         register struct radix_node *rn = h->rnh_treetop;
1104         /*
1105          * This gets complicated because we may delete the node
1106          * while applying the function f to it, so we need to calculate
1107          * the successor node in advance.
1108          */
1109
1110         /* First time through node, go left */
1111         while (rn->rn_bit >= 0)
1112                 rn = rn->rn_left;
1113         for (;;) {
1114                 base = rn;
1115                 /* If at right child go back up, otherwise, go right */
1116                 while (rn->rn_parent->rn_right == rn
1117                        && (rn->rn_flags & RNF_ROOT) == 0)
1118                         rn = rn->rn_parent;
1119                 /* Find the next *leaf* since next node might vanish, too */
1120                 for (rn = rn->rn_parent->rn_right; rn->rn_bit >= 0;)
1121                         rn = rn->rn_left;
1122                 next = rn;
1123                 /* Process leaves */
1124                 while ((rn = base)) {
1125                         base = rn->rn_dupedkey;
1126                         if (!(rn->rn_flags & RNF_ROOT)
1127                             && (error = (*f)(rn, w)))
1128                                 return (error);
1129                 }
1130                 rn = next;
1131                 if (rn->rn_flags & RNF_ROOT)
1132                         return (0);
1133         }
1134         /* NOTREACHED */
1135 }
1136
1137 /*
1138  * Allocate and initialize an empty tree. This has 3 nodes, which are
1139  * part of the radix_node_head (in the order <left,root,right>) and are
1140  * marked RNF_ROOT so they cannot be freed.
1141  * The leaves have all-zero and all-one keys, with significant
1142  * bits starting at 'off'.
1143  * Return 1 on success, 0 on error.
1144  */
1145 static int
1146 rn_inithead_internal(void **head, int off)
1147 {
1148         register struct radix_node_head *rnh;
1149         register struct radix_node *t, *tt, *ttt;
1150         if (*head)
1151                 return (1);
1152         R_Zalloc(rnh, struct radix_node_head *, sizeof (*rnh));
1153         if (rnh == 0)
1154                 return (0);
1155 #ifdef _KERNEL
1156         RADIX_NODE_HEAD_LOCK_INIT(rnh);
1157 #endif
1158         *head = rnh;
1159         t = rn_newpair(rn_zeros, off, rnh->rnh_nodes);
1160         ttt = rnh->rnh_nodes + 2;
1161         t->rn_right = ttt;
1162         t->rn_parent = t;
1163         tt = t->rn_left;        /* ... which in turn is rnh->rnh_nodes */
1164         tt->rn_flags = t->rn_flags = RNF_ROOT | RNF_ACTIVE;
1165         tt->rn_bit = -1 - off;
1166         *ttt = *tt;
1167         ttt->rn_key = rn_ones;
1168         rnh->rnh_addaddr = rn_addroute;
1169         rnh->rnh_deladdr = rn_delete;
1170         rnh->rnh_matchaddr = rn_match;
1171         rnh->rnh_lookup = rn_lookup;
1172         rnh->rnh_walktree = rn_walktree;
1173         rnh->rnh_walktree_from = rn_walktree_from;
1174         rnh->rnh_treetop = t;
1175         return (1);
1176 }
1177
1178 static void
1179 rn_detachhead_internal(void **head)
1180 {
1181         struct radix_node_head *rnh;
1182
1183         KASSERT((head != NULL && *head != NULL),
1184             ("%s: head already freed", __func__));
1185         rnh = *head;
1186         
1187         /* Free <left,root,right> nodes. */
1188         Free(rnh);
1189
1190         *head = NULL;
1191 }
1192
1193 int
1194 rn_inithead(void **head, int off)
1195 {
1196         struct radix_node_head *rnh;
1197
1198         if (*head != NULL)
1199                 return (1);
1200
1201         if (rn_inithead_internal(head, off) == 0)
1202                 return (0);
1203
1204         rnh = (struct radix_node_head *)(*head);
1205
1206         if (rn_inithead_internal((void **)&rnh->rnh_masks, 0) == 0) {
1207                 rn_detachhead_internal(head);
1208                 return (0);
1209         }
1210
1211         return (1);
1212 }
1213
1214 int
1215 rn_detachhead(void **head)
1216 {
1217         struct radix_node_head *rnh;
1218
1219         KASSERT((head != NULL && *head != NULL),
1220             ("%s: head already freed", __func__));
1221
1222         rnh = *head;
1223
1224         rn_detachhead_internal((void **)&rnh->rnh_masks);
1225         rn_detachhead_internal(head);
1226         return (1);
1227 }
1228
1229 void
1230 rn_init(int maxk)
1231 {
1232         if ((maxk <= 0) || (maxk > RADIX_MAX_KEY_LEN)) {
1233                 log(LOG_ERR,
1234                     "rn_init: max_keylen must be within 1..%d\n",
1235                     RADIX_MAX_KEY_LEN);
1236                 return;
1237         }
1238
1239         /*
1240          * XXX: Compat for old rn_addmask() users
1241          */
1242         if (rn_inithead((void **)(void *)&mask_rnhead_compat, 0) == 0)
1243                 panic("rn_init 2");
1244 #ifdef _KERNEL
1245         mtx_init(&mask_mtx, "radix_mask", NULL, MTX_DEF);
1246 #endif
1247 }