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