2 * SPDX-License-Identifier: BSD-3-Clause
4 * Copyright (c) 1988, 1989, 1993
5 * The Regents of the University of California. All rights reserved.
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
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.
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
33 * Routines to build and maintain radix trees for routing lookups.
35 #include <sys/param.h>
38 #include <sys/mutex.h>
39 #include <sys/rmlock.h>
40 #include <sys/systm.h>
41 #include <sys/malloc.h>
42 #include <sys/syslog.h>
43 #include <net/radix.h>
48 #define log(x, arg...) fprintf(stderr, ## arg)
49 #define panic(x) fprintf(stderr, "PANIC: %s", x), exit(1)
50 #define min(a, b) ((a) < (b) ? (a) : (b) )
51 #include <net/radix.h>
54 static struct radix_node
55 *rn_insert(void *, struct radix_head *, int *,
56 struct radix_node [2]),
57 *rn_newpair(void *, int, struct radix_node[2]),
58 *rn_search(const void *, struct radix_node *),
59 *rn_search_m(const void *, struct radix_node *, void *);
60 static struct radix_node *rn_addmask(const void *, struct radix_mask_head *, int,int);
62 static void rn_detachhead_internal(struct radix_head *);
64 #define RADIX_MAX_KEY_LEN 32
66 static char rn_zeros[RADIX_MAX_KEY_LEN];
67 static char rn_ones[RADIX_MAX_KEY_LEN] = {
68 -1, -1, -1, -1, -1, -1, -1, -1,
69 -1, -1, -1, -1, -1, -1, -1, -1,
70 -1, -1, -1, -1, -1, -1, -1, -1,
71 -1, -1, -1, -1, -1, -1, -1, -1,
74 static int rn_lexobetter(const void *m_arg, const void *n_arg);
75 static struct radix_mask *
76 rn_new_radix_mask(struct radix_node *tt,
77 struct radix_mask *next);
78 static int rn_satisfies_leaf(const char *trial, struct radix_node *leaf,
82 * The data structure for the keys is a radix tree with one way
83 * branching removed. The index rn_bit at an internal node n represents a bit
84 * position to be tested. The tree is arranged so that all descendants
85 * of a node n have keys whose bits all agree up to position rn_bit - 1.
86 * (We say the index of n is rn_bit.)
88 * There is at least one descendant which has a one bit at position rn_bit,
89 * and at least one with a zero there.
91 * A route is determined by a pair of key and mask. We require that the
92 * bit-wise logical and of the key and mask to be the key.
93 * We define the index of a route to associated with the mask to be
94 * the first bit number in the mask where 0 occurs (with bit number 0
95 * representing the highest order bit).
97 * We say a mask is normal if every bit is 0, past the index of the mask.
98 * If a node n has a descendant (k, m) with index(m) == index(n) == rn_bit,
99 * and m is a normal mask, then the route applies to every descendant of n.
100 * If the index(m) < rn_bit, this implies the trailing last few bits of k
101 * before bit b are all 0, (and hence consequently true of every descendant
102 * of n), so the route applies to all descendants of the node as well.
104 * Similar logic shows that a non-normal mask m such that
105 * index(m) <= index(n) could potentially apply to many children of n.
106 * Thus, for each non-host route, we attach its mask to a list at an internal
107 * node as high in the tree as we can go.
109 * The present version of the code makes use of normal routes in short-
110 * circuiting an explict mask and compare operation when testing whether
111 * a key satisfies a normal route, and also in remembering the unique leaf
112 * that governs a subtree.
116 * Most of the functions in this code assume that the key/mask arguments
117 * are sockaddr-like structures, where the first byte is an u_char
118 * indicating the size of the entire structure.
120 * To make the assumption more explicit, we use the LEN() macro to access
121 * this field. It is safe to pass an expression with side effects
122 * to LEN() as the argument is evaluated only once.
123 * We cast the result to int as this is the dominant usage.
125 #define LEN(x) ( (int) (*(const u_char *)(x)) )
128 * XXX THIS NEEDS TO BE FIXED
129 * In the code, pointers to keys and masks are passed as either
130 * 'void *' (because callers use to pass pointers of various kinds), or
131 * 'caddr_t' (which is fine for pointer arithmetics, but not very
132 * clean when you dereference it to access data). Furthermore, caddr_t
133 * is really 'char *', while the natural type to operate on keys and
134 * masks would be 'u_char'. This mismatch require a lot of casts and
135 * intermediate variables to adapt types that clutter the code.
139 * Search a node in the tree matching the key.
141 static struct radix_node *
142 rn_search(const void *v_arg, struct radix_node *head)
144 struct radix_node *x;
147 for (x = head, v = v_arg; x->rn_bit >= 0;) {
148 if (x->rn_bmask & v[x->rn_offset])
157 * Same as above, but with an additional mask.
158 * XXX note this function is used only once.
160 static struct radix_node *
161 rn_search_m(const void *v_arg, struct radix_node *head, void *m_arg)
163 struct radix_node *x;
164 c_caddr_t v = v_arg, m = m_arg;
166 for (x = head; x->rn_bit >= 0;) {
167 if ((x->rn_bmask & m[x->rn_offset]) &&
168 (x->rn_bmask & v[x->rn_offset]))
177 rn_refines(const void *m_arg, const void *n_arg)
179 c_caddr_t m = m_arg, n = n_arg;
180 c_caddr_t lim, lim2 = lim = n + LEN(n);
181 int longer = LEN(n++) - LEN(m++);
182 int masks_are_equal = 1;
195 if (masks_are_equal && (longer < 0))
196 for (lim2 = m - longer; m < lim2; )
199 return (!masks_are_equal);
203 * Search for exact match in given @head.
204 * Assume host bits are cleared in @v_arg if @m_arg is not NULL
205 * Note that prefixes with /32 or /128 masks are treated differently
209 rn_lookup(const void *v_arg, const void *m_arg, struct radix_head *head)
211 struct radix_node *x;
216 * Most common case: search exact prefix/mask
218 x = rn_addmask(m_arg, head->rnh_masks, 1,
219 head->rnh_treetop->rn_offset);
224 x = rn_match(v_arg, head);
226 while (x != NULL && x->rn_mask != netmask)
233 * Search for host address.
235 if ((x = rn_match(v_arg, head)) == NULL)
238 /* Check if found key is the same */
239 if (LEN(x->rn_key) != LEN(v_arg) || bcmp(x->rn_key, v_arg, LEN(v_arg)))
242 /* Check if this is not host route */
243 if (x->rn_mask != NULL)
250 rn_satisfies_leaf(const char *trial, struct radix_node *leaf, int skip)
252 const char *cp = trial, *cp2 = leaf->rn_key, *cp3 = leaf->rn_mask;
254 int length = min(LEN(cp), LEN(cp2));
259 length = min(length, LEN(cp3));
260 cplim = cp + length; cp3 += skip; cp2 += skip;
261 for (cp += skip; cp < cplim; cp++, cp2++, cp3++)
262 if ((*cp ^ *cp2) & *cp3)
268 * Search for longest-prefix match in given @head
271 rn_match(const void *v_arg, struct radix_head *head)
274 struct radix_node *t = head->rnh_treetop, *x;
275 c_caddr_t cp = v, cp2;
277 struct radix_node *saved_t, *top = t;
278 int off = t->rn_offset, vlen = LEN(cp), matched_off;
282 * Open code rn_search(v, top) to avoid overhead of extra
285 for (; t->rn_bit >= 0; ) {
286 if (t->rn_bmask & cp[t->rn_offset])
292 * See if we match exactly as a host destination
293 * or at least learn how many bits match, for normal mask finesse.
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...
303 vlen = *(u_char *)t->rn_mask;
304 cp += off; cp2 = t->rn_key + off; cplim = v + vlen;
305 for (; cp < cplim; cp++, cp2++)
309 * This extra grot is in case we are explicitly asked
310 * to look up the default. Ugh!
312 * Never return the root node itself, it seems to cause a
315 if (t->rn_flags & RNF_ROOT)
319 test = (*cp ^ *cp2) & 0xff; /* find first bit that differs */
320 for (b = 7; (test >>= 1) > 0;)
322 matched_off = cp - v;
323 b += matched_off << 3;
326 * If there is a host route in a duped-key chain, it will be first.
328 if ((saved_t = t)->rn_mask == 0)
330 for (; t; t = t->rn_dupedkey)
332 * Even if we don't match exactly as a host,
333 * we may match if the leaf we wound up at is
336 if (t->rn_flags & RNF_NORMAL) {
337 if (rn_bit <= t->rn_bit)
339 } else if (rn_satisfies_leaf(v, t, matched_off))
342 /* start searching up the tree */
344 struct radix_mask *m;
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".
354 if (m->rm_flags & RNF_NORMAL) {
355 if (rn_bit <= m->rm_bit)
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)
362 if (x && rn_satisfies_leaf(v, x, off))
372 * Returns the next (wider) prefix for the key defined by @rn
376 rn_nextprefix(struct radix_node *rn)
378 for (rn = rn->rn_dupedkey; rn != NULL; rn = rn->rn_dupedkey) {
379 if (!(rn->rn_flags & RNF_ROOT))
387 struct radix_node *rn_clist;
393 * Whenever we add a new leaf to the tree, we also add a parent node,
394 * so we allocate them as an array of two elements: the first one must be
395 * the leaf (see RNTORT() in route.c), the second one is the parent.
396 * This routine initializes the relevant fields of the nodes, so that
397 * the leaf is the left child of the parent node, and both nodes have
398 * (almost) all all fields filled as appropriate.
399 * (XXX some fields are left unset, see the '#if 0' section).
400 * The function returns a pointer to the parent node.
403 static struct radix_node *
404 rn_newpair(void *v, int b, struct radix_node nodes[2])
406 struct radix_node *tt = nodes, *t = tt + 1;
408 t->rn_bmask = 0x80 >> (b & 7);
410 t->rn_offset = b >> 3;
412 #if 0 /* XXX perhaps we should fill these fields as well. */
413 t->rn_parent = t->rn_right = NULL;
416 tt->rn_dupedkey = NULL;
420 tt->rn_key = (caddr_t)v;
422 tt->rn_flags = t->rn_flags = RNF_ACTIVE;
423 tt->rn_mklist = t->rn_mklist = 0;
425 tt->rn_info = rn_nodenum++; t->rn_info = rn_nodenum++;
427 tt->rn_ybro = rn_clist;
433 static struct radix_node *
434 rn_insert(void *v_arg, struct radix_head *head, int *dupentry,
435 struct radix_node nodes[2])
438 struct radix_node *top = head->rnh_treetop;
439 int head_off = top->rn_offset, vlen = LEN(v);
440 struct radix_node *t = rn_search(v_arg, top);
441 caddr_t cp = v + head_off;
443 struct radix_node *p, *tt, *x;
445 * Find first bit at which v and t->rn_key differ
447 caddr_t cp2 = t->rn_key + head_off;
449 caddr_t cplim = v + vlen;
458 cmp_res = (cp[-1] ^ cp2[-1]) & 0xff;
459 for (b = (cp - v) << 3; cmp_res; b--)
466 if (cp[x->rn_offset] & x->rn_bmask)
470 } while (b > (unsigned) x->rn_bit);
471 /* x->rn_bit < b && x->rn_bit >= 0 */
474 log(LOG_DEBUG, "rn_insert: Going In:\n"), traverse(p);
476 t = rn_newpair(v_arg, b, nodes);
478 if ((cp[p->rn_offset] & p->rn_bmask) == 0)
483 t->rn_parent = p; /* frees x, p as temp vars below */
484 if ((cp[t->rn_offset] & t->rn_bmask) == 0) {
492 log(LOG_DEBUG, "rn_insert: Coming Out:\n"), traverse(p);
497 static struct radix_node *
498 rn_addmask(const void *n_arg, struct radix_mask_head *maskhead, int search, int skip)
500 const unsigned char *netmask = n_arg;
501 const unsigned char *c, *clim;
503 struct radix_node *x;
505 int maskduplicated, isnormal;
506 struct radix_node *saved_x;
507 unsigned char addmask_key[RADIX_MAX_KEY_LEN];
509 if ((mlen = LEN(netmask)) > RADIX_MAX_KEY_LEN)
510 mlen = RADIX_MAX_KEY_LEN;
514 return (maskhead->mask_nodes);
516 bzero(addmask_key, RADIX_MAX_KEY_LEN);
518 bcopy(rn_ones + 1, addmask_key + 1, skip - 1);
519 bcopy(netmask + skip, addmask_key + skip, mlen - skip);
521 * Trim trailing zeroes.
523 for (cp = addmask_key + mlen; (cp > addmask_key) && cp[-1] == 0;)
525 mlen = cp - addmask_key;
527 return (maskhead->mask_nodes);
529 x = rn_search(addmask_key, maskhead->head.rnh_treetop);
530 if (bcmp(addmask_key, x->rn_key, mlen) != 0)
534 R_Zalloc(x, struct radix_node *, RADIX_MAX_KEY_LEN + 2 * sizeof (*x));
535 if ((saved_x = x) == NULL)
537 netmask = cp = (unsigned char *)(x + 2);
538 bcopy(addmask_key, cp, mlen);
539 x = rn_insert(cp, &maskhead->head, &maskduplicated, x);
540 if (maskduplicated) {
541 log(LOG_ERR, "rn_addmask: mask impossibly already in tree");
546 * Calculate index of mask, and check for normalcy.
547 * First find the first byte with a 0 bit, then if there are
548 * more bits left (remember we already trimmed the trailing 0's),
549 * the bits should be contiguous, otherwise we have got
550 * a non-contiguous mask.
552 #define CONTIG(_c) (((~(_c) + 1) & (_c)) == (unsigned char)(~(_c) + 1))
553 clim = netmask + mlen;
555 for (c = netmask + skip; (c < clim) && *(const u_char *)c == 0xff;)
558 for (j = 0x80; (j & *c) != 0; j >>= 1)
560 if (!CONTIG(*c) || c != (clim - 1))
563 b += (c - netmask) << 3;
566 x->rn_flags |= RNF_NORMAL;
570 static int /* XXX: arbitrary ordering for non-contiguous masks */
571 rn_lexobetter(const void *m_arg, const void *n_arg)
573 const u_char *mp = m_arg, *np = n_arg, *lim;
575 if (LEN(mp) > LEN(np))
576 return (1); /* not really, but need to check longer one first */
577 if (LEN(mp) == LEN(np))
578 for (lim = mp + LEN(mp); mp < lim;)
584 static struct radix_mask *
585 rn_new_radix_mask(struct radix_node *tt, struct radix_mask *next)
587 struct radix_mask *m;
589 R_Malloc(m, struct radix_mask *, sizeof (struct radix_mask));
591 log(LOG_ERR, "Failed to allocate route mask\n");
594 bzero(m, sizeof(*m));
595 m->rm_bit = tt->rn_bit;
596 m->rm_flags = tt->rn_flags;
597 if (tt->rn_flags & RNF_NORMAL)
600 m->rm_mask = tt->rn_mask;
607 rn_addroute(void *v_arg, const void *n_arg, struct radix_head *head,
608 struct radix_node treenodes[2])
610 caddr_t v = (caddr_t)v_arg, netmask = NULL;
611 struct radix_node *t, *x = NULL, *tt;
612 struct radix_node *saved_tt, *top = head->rnh_treetop;
613 short b = 0, b_leaf = 0;
616 struct radix_mask *m, **mp;
619 * In dealing with non-contiguous masks, there may be
620 * many different routes which have the same mask.
621 * We will find it useful to have a unique pointer to
622 * the mask to speed avoiding duplicate references at
623 * nodes and possibly save time in calculating indices.
626 x = rn_addmask(n_arg, head->rnh_masks, 0, top->rn_offset);
634 * Deal with duplicated keys: attach node to previous instance
636 saved_tt = tt = rn_insert(v, head, &keyduplicated, treenodes);
638 for (t = tt; tt; t = tt, tt = tt->rn_dupedkey) {
639 if (tt->rn_mask == netmask)
643 ((b_leaf < tt->rn_bit) /* index(netmask) > node */
644 || rn_refines(netmask, tt->rn_mask)
645 || rn_lexobetter(netmask, tt->rn_mask))))
649 * If the mask is not duplicated, we wouldn't
650 * find it among possible duplicate key entries
651 * anyway, so the above test doesn't hurt.
653 * We sort the masks for a duplicated key the same way as
654 * in a masklist -- most specific to least specific.
655 * This may require the unfortunate nuisance of relocating
656 * the head of the list.
658 * We also reverse, or doubly link the list through the
661 if (tt == saved_tt) {
662 struct radix_node *xx = x;
663 /* link in at head of list */
664 (tt = treenodes)->rn_dupedkey = t;
665 tt->rn_flags = t->rn_flags;
666 tt->rn_parent = x = t->rn_parent;
667 t->rn_parent = tt; /* parent */
672 saved_tt = tt; x = xx;
674 (tt = treenodes)->rn_dupedkey = t->rn_dupedkey;
676 tt->rn_parent = t; /* parent */
677 if (tt->rn_dupedkey) /* parent */
678 tt->rn_dupedkey->rn_parent = tt; /* parent */
681 t=tt+1; tt->rn_info = rn_nodenum++; t->rn_info = rn_nodenum++;
682 tt->rn_twin = t; tt->rn_ybro = rn_clist; rn_clist = tt;
684 tt->rn_key = (caddr_t) v;
686 tt->rn_flags = RNF_ACTIVE;
692 tt->rn_mask = netmask;
693 tt->rn_bit = x->rn_bit;
694 tt->rn_flags |= x->rn_flags & RNF_NORMAL;
696 t = saved_tt->rn_parent;
699 b_leaf = -1 - t->rn_bit;
700 if (t->rn_right == saved_tt)
704 /* Promote general routes from below */
706 for (mp = &t->rn_mklist; x; x = x->rn_dupedkey)
707 if (x->rn_mask && (x->rn_bit >= b_leaf) && x->rn_mklist == 0) {
708 *mp = m = rn_new_radix_mask(x, 0);
712 } else if (x->rn_mklist) {
714 * Skip over masks whose index is > that of new node
716 for (mp = &x->rn_mklist; (m = *mp); mp = &m->rm_mklist)
717 if (m->rm_bit >= b_leaf)
719 t->rn_mklist = m; *mp = NULL;
722 /* Add new route to highest possible ancestor's list */
723 if ((netmask == 0) || (b > t->rn_bit ))
724 return (tt); /* can't lift at all */
729 } while (b <= t->rn_bit && x != top);
731 * Search through routes associated with node to
732 * insert new route according to index.
733 * Need same criteria as when sorting dupedkeys to avoid
734 * double loop on deletion.
736 for (mp = &x->rn_mklist; (m = *mp); mp = &m->rm_mklist) {
737 if (m->rm_bit < b_leaf)
739 if (m->rm_bit > b_leaf)
741 if (m->rm_flags & RNF_NORMAL) {
742 mmask = m->rm_leaf->rn_mask;
743 if (tt->rn_flags & RNF_NORMAL) {
745 "Non-unique normal route, mask not entered\n");
750 if (mmask == netmask) {
755 if (rn_refines(netmask, mmask)
756 || rn_lexobetter(netmask, mmask))
759 *mp = rn_new_radix_mask(tt, *mp);
764 rn_delete(const void *v_arg, const void *netmask_arg, struct radix_head *head)
766 struct radix_node *t, *p, *x, *tt;
767 struct radix_mask *m, *saved_m, **mp;
768 struct radix_node *dupedkey, *saved_tt, *top;
771 int b, head_off, vlen;
774 netmask = netmask_arg;
775 x = head->rnh_treetop;
776 tt = rn_search(v, x);
777 head_off = x->rn_offset;
782 bcmp(v + head_off, tt->rn_key + head_off, vlen - head_off))
785 * Delete our route from mask lists.
788 x = rn_addmask(netmask, head->rnh_masks, 1, head_off);
792 while (tt->rn_mask != netmask)
793 if ((tt = tt->rn_dupedkey) == NULL)
796 if (tt->rn_mask == 0 || (saved_m = m = tt->rn_mklist) == NULL)
798 if (tt->rn_flags & RNF_NORMAL) {
799 if (m->rm_leaf != tt || m->rm_refs > 0) {
800 log(LOG_ERR, "rn_delete: inconsistent annotation\n");
801 return (0); /* dangling ref could cause disaster */
804 if (m->rm_mask != tt->rn_mask) {
805 log(LOG_ERR, "rn_delete: inconsistent annotation\n");
808 if (--m->rm_refs >= 0)
812 t = saved_tt->rn_parent;
814 goto on1; /* Wasn't lifted at all */
818 } while (b <= t->rn_bit && x != top);
819 for (mp = &x->rn_mklist; (m = *mp); mp = &m->rm_mklist)
826 log(LOG_ERR, "rn_delete: couldn't find our annotation\n");
827 if (tt->rn_flags & RNF_NORMAL)
828 return (0); /* Dangling ref to us */
832 * Eliminate us from tree
834 if (tt->rn_flags & RNF_ROOT)
837 /* Get us out of the creation list */
838 for (t = rn_clist; t && t->rn_ybro != tt; t = t->rn_ybro) {}
839 if (t) t->rn_ybro = tt->rn_ybro;
842 dupedkey = saved_tt->rn_dupedkey;
845 * Here, tt is the deletion target and
846 * saved_tt is the head of the dupekey chain.
848 if (tt == saved_tt) {
849 /* remove from head of chain */
850 x = dupedkey; x->rn_parent = t;
851 if (t->rn_left == tt)
856 /* find node in front of tt on the chain */
857 for (x = p = saved_tt; p && p->rn_dupedkey != tt;)
860 p->rn_dupedkey = tt->rn_dupedkey;
861 if (tt->rn_dupedkey) /* parent */
862 tt->rn_dupedkey->rn_parent = p;
864 } else log(LOG_ERR, "rn_delete: couldn't find us\n");
867 if (t->rn_flags & RNF_ACTIVE) {
881 x->rn_left->rn_parent = x;
882 x->rn_right->rn_parent = x;
886 if (t->rn_left == tt)
891 if (p->rn_right == t)
897 * Demote routes attached to us.
900 if (x->rn_bit >= 0) {
901 for (mp = &x->rn_mklist; (m = *mp);)
905 /* If there are any key,mask pairs in a sibling
906 duped-key chain, some subset will appear sorted
907 in the same order attached to our mklist */
908 for (m = t->rn_mklist; m && x; x = x->rn_dupedkey)
909 if (m == x->rn_mklist) {
910 struct radix_mask *mm = m->rm_mklist;
912 if (--(m->rm_refs) < 0)
918 "rn_delete: Orphaned Mask %p at %p\n",
923 * We may be holding an active internal node in the tree.
934 t->rn_left->rn_parent = t;
935 t->rn_right->rn_parent = t;
943 tt->rn_flags &= ~RNF_ACTIVE;
944 tt[1].rn_flags &= ~RNF_ACTIVE;
949 * This is the same as rn_walktree() except for the parameters and the
953 rn_walktree_from(struct radix_head *h, void *a, void *m,
954 walktree_f_t *f, void *w)
957 struct radix_node *base, *next;
958 u_char *xa = (u_char *)a;
959 u_char *xm = (u_char *)m;
960 struct radix_node *rn, *last = NULL; /* shut up gcc */
964 KASSERT(m != NULL, ("%s: mask needs to be specified", __func__));
967 * rn_search_m is sort-of-open-coded here. We cannot use the
968 * function because we need to keep track of the last node seen.
970 /* printf("about to search\n"); */
971 for (rn = h->rnh_treetop; rn->rn_bit >= 0; ) {
973 /* printf("rn_bit %d, rn_bmask %x, xm[rn_offset] %x\n",
974 rn->rn_bit, rn->rn_bmask, xm[rn->rn_offset]); */
975 if (!(rn->rn_bmask & xm[rn->rn_offset])) {
978 if (rn->rn_bmask & xa[rn->rn_offset]) {
984 /* printf("done searching\n"); */
987 * Two cases: either we stepped off the end of our mask,
988 * in which case last == rn, or we reached a leaf, in which
989 * case we want to start from the leaf.
993 lastb = last->rn_bit;
995 /* printf("rn %p, lastb %d\n", rn, lastb);*/
998 * This gets complicated because we may delete the node
999 * while applying the function f to it, so we need to calculate
1000 * the successor node in advance.
1002 while (rn->rn_bit >= 0)
1006 /* printf("node %p (%d)\n", rn, rn->rn_bit); */
1008 /* If at right child go back up, otherwise, go right */
1009 while (rn->rn_parent->rn_right == rn
1010 && !(rn->rn_flags & RNF_ROOT)) {
1013 /* if went up beyond last, stop */
1014 if (rn->rn_bit <= lastb) {
1016 /* printf("up too far\n"); */
1018 * XXX we should jump to the 'Process leaves'
1019 * part, because the values of 'rn' and 'next'
1020 * we compute will not be used. Not a big deal
1021 * because this loop will terminate, but it is
1022 * inefficient and hard to understand!
1028 * At the top of the tree, no need to traverse the right
1029 * half, prevent the traversal of the entire tree in the
1030 * case of default route.
1032 if (rn->rn_parent->rn_flags & RNF_ROOT)
1035 /* Find the next *leaf* since next node might vanish, too */
1036 for (rn = rn->rn_parent->rn_right; rn->rn_bit >= 0;)
1039 /* Process leaves */
1040 while ((rn = base) != NULL) {
1041 base = rn->rn_dupedkey;
1042 /* printf("leaf %p\n", rn); */
1043 if (!(rn->rn_flags & RNF_ROOT)
1044 && (error = (*f)(rn, w)))
1049 if (rn->rn_flags & RNF_ROOT) {
1050 /* printf("root, stopping"); */
1058 rn_walktree(struct radix_head *h, walktree_f_t *f, void *w)
1061 struct radix_node *base, *next;
1062 struct radix_node *rn = h->rnh_treetop;
1064 * This gets complicated because we may delete the node
1065 * while applying the function f to it, so we need to calculate
1066 * the successor node in advance.
1069 /* First time through node, go left */
1070 while (rn->rn_bit >= 0)
1074 /* If at right child go back up, otherwise, go right */
1075 while (rn->rn_parent->rn_right == rn
1076 && (rn->rn_flags & RNF_ROOT) == 0)
1078 /* Find the next *leaf* since next node might vanish, too */
1079 for (rn = rn->rn_parent->rn_right; rn->rn_bit >= 0;)
1082 /* Process leaves */
1083 while ((rn = base)) {
1084 base = rn->rn_dupedkey;
1085 if (!(rn->rn_flags & RNF_ROOT)
1086 && (error = (*f)(rn, w)))
1090 if (rn->rn_flags & RNF_ROOT)
1097 * Initialize an empty tree. This has 3 nodes, which are passed
1098 * via base_nodes (in the order <left,root,right>) and are
1099 * marked RNF_ROOT so they cannot be freed.
1100 * The leaves have all-zero and all-one keys, with significant
1101 * bits starting at 'off'.
1104 rn_inithead_internal(struct radix_head *rh, struct radix_node *base_nodes, int off)
1106 struct radix_node *t, *tt, *ttt;
1108 t = rn_newpair(rn_zeros, off, base_nodes);
1109 ttt = base_nodes + 2;
1112 tt = t->rn_left; /* ... which in turn is base_nodes */
1113 tt->rn_flags = t->rn_flags = RNF_ROOT | RNF_ACTIVE;
1114 tt->rn_bit = -1 - off;
1116 ttt->rn_key = rn_ones;
1118 rh->rnh_treetop = t;
1122 rn_detachhead_internal(struct radix_head *head)
1125 KASSERT((head != NULL),
1126 ("%s: head already freed", __func__));
1128 /* Free <left,root,right> nodes. */
1132 /* Functions used by 'struct radix_node_head' users */
1135 rn_inithead(void **head, int off)
1137 struct radix_node_head *rnh;
1138 struct radix_mask_head *rmh;
1146 R_Zalloc(rnh, struct radix_node_head *, sizeof (*rnh));
1147 R_Zalloc(rmh, struct radix_mask_head *, sizeof (*rmh));
1148 if (rnh == NULL || rmh == NULL) {
1157 rn_inithead_internal(&rnh->rh, rnh->rnh_nodes, off);
1158 rn_inithead_internal(&rmh->head, rmh->mask_nodes, 0);
1160 rnh->rh.rnh_masks = rmh;
1162 /* Finally, set base callbacks */
1163 rnh->rnh_addaddr = rn_addroute;
1164 rnh->rnh_deladdr = rn_delete;
1165 rnh->rnh_matchaddr = rn_match;
1166 rnh->rnh_lookup = rn_lookup;
1167 rnh->rnh_walktree = rn_walktree;
1168 rnh->rnh_walktree_from = rn_walktree_from;
1174 rn_freeentry(struct radix_node *rn, void *arg)
1176 struct radix_head * const rnh = arg;
1177 struct radix_node *x;
1179 x = (struct radix_node *)rn_delete(rn + 2, NULL, rnh);
1186 rn_detachhead(void **head)
1188 struct radix_node_head *rnh;
1190 KASSERT((head != NULL && *head != NULL),
1191 ("%s: head already freed", __func__));
1193 rnh = (struct radix_node_head *)(*head);
1195 rn_walktree(&rnh->rh.rnh_masks->head, rn_freeentry, rnh->rh.rnh_masks);
1196 rn_detachhead_internal(&rnh->rh.rnh_masks->head);
1197 rn_detachhead_internal(&rnh->rh);