1 /*
2 * Copyright (c) 2000-2013 Apple Inc. All rights reserved.
3 *
4 * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
5 *
6 * This file contains Original Code and/or Modifications of Original Code
7 * as defined in and that are subject to the Apple Public Source License
8 * Version 2.0 (the 'License'). You may not use this file except in
9 * compliance with the License. The rights granted to you under the License
10 * may not be used to create, or enable the creation or redistribution of,
11 * unlawful or unlicensed copies of an Apple operating system, or to
12 * circumvent, violate, or enable the circumvention or violation of, any
13 * terms of an Apple operating system software license agreement.
14 *
15 * Please obtain a copy of the License at
16 * http://www.opensource.apple.com/apsl/ and read it before using this file.
17 *
18 * The Original Code and all software distributed under the License are
19 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
20 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
21 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
22 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
23 * Please see the License for the specific language governing rights and
24 * limitations under the License.
25 *
26 * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
27 */
28 /*
29 * Copyright (c) 1988, 1989, 1993
30 * The Regents of the University of California. All rights reserved.
31 *
32 * Redistribution and use in source and binary forms, with or without
33 * modification, are permitted provided that the following conditions
34 * are met:
35 * 1. Redistributions of source code must retain the above copyright
36 * notice, this list of conditions and the following disclaimer.
37 * 2. Redistributions in binary form must reproduce the above copyright
38 * notice, this list of conditions and the following disclaimer in the
39 * documentation and/or other materials provided with the distribution.
40 * 3. All advertising materials mentioning features or use of this software
41 * must display the following acknowledgement:
42 * This product includes software developed by the University of
43 * California, Berkeley and its contributors.
44 * 4. Neither the name of the University nor the names of its contributors
45 * may be used to endorse or promote products derived from this software
46 * without specific prior written permission.
47 *
48 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
49 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
50 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
51 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
52 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
53 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
54 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
55 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
56 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
57 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
58 * SUCH DAMAGE.
59 *
60 * @(#)radix.c 8.4 (Berkeley) 11/2/94
61 * $FreeBSD: src/sys/net/radix.c,v 1.20.2.2 2001/03/06 00:56:50 obrien Exp $
62 */
63
64 /*
65 * Routines to build and maintain radix trees for routing lookups.
66 */
67 #ifndef _RADIX_H_
68 #include <sys/param.h>
69 #include <sys/systm.h>
70 #include <sys/domain.h>
71 #include <sys/syslog.h>
72 #include <net/radix.h>
73 #include <sys/socket.h>
74 #include <sys/socketvar.h>
75 #include <kern/locks.h>
76 #endif
77
78 static int rn_walktree_from(struct radix_node_head *h, void *a,
79 void *m, walktree_f_t *f, void *w);
80 static int rn_walktree(struct radix_node_head *, walktree_f_t *, void *);
81 static struct radix_node *rn_insert(void *, struct radix_node_head *, int *, struct radix_node[2]);
82 static struct radix_node *rn_newpair(void *, int, struct radix_node[2]);
83 static struct radix_node *rn_search(void *, struct radix_node *);
84 static struct radix_node *rn_search_m(void *, struct radix_node *, void *);
85
86 static int max_keylen;
87 static struct radix_mask *rn_mkfreelist;
88 static struct radix_node_head *mask_rnhead;
89 static char *addmask_key;
90 static char normal_chars[] = {0, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe, -1};
91 static char *rn_zeros, *rn_ones;
92
93 static zone_t radix_node_zone;
94 KALLOC_TYPE_DEFINE(radix_node_head_zone, struct radix_node_head, KT_DEFAULT);
95
96 #define rn_masktop (mask_rnhead->rnh_treetop)
97 #undef Bcmp
98 #define Bcmp(a, b, l) \
99 (l == 0 ? 0 : bcmp((caddr_t)(a), (caddr_t)(b), (uint32_t)l))
100
101 static int rn_lexobetter(void *m_arg, void *n_arg);
102 static struct radix_mask *
103 rn_new_radix_mask(struct radix_node *tt,
104 struct radix_mask *next);
105 static int rn_satisfies_leaf(char *trial, struct radix_node *leaf, int skip,
106 rn_matchf_t *f, void *w);
107
108 #define RN_MATCHF(rn, f, arg) (f == NULL || (*f)((rn), arg))
109
110 /*
111 * The data structure for the keys is a radix tree with one way
112 * branching removed. The index rn_bit at an internal node n represents a bit
113 * position to be tested. The tree is arranged so that all descendants
114 * of a node n have keys whose bits all agree up to position rn_bit - 1.
115 * (We say the index of n is rn_bit.)
116 *
117 * There is at least one descendant which has a one bit at position rn_bit,
118 * and at least one with a zero there.
119 *
120 * A route is determined by a pair of key and mask. We require that the
121 * bit-wise logical and of the key and mask to be the key.
122 * We define the index of a route to associated with the mask to be
123 * the first bit number in the mask where 0 occurs (with bit number 0
124 * representing the highest order bit).
125 *
126 * We say a mask is normal if every bit is 0, past the index of the mask.
127 * If a node n has a descendant (k, m) with index(m) == index(n) == rn_bit,
128 * and m is a normal mask, then the route applies to every descendant of n.
129 * If the index(m) < rn_bit, this implies the trailing last few bits of k
130 * before bit b are all 0, (and hence consequently true of every descendant
131 * of n), so the route applies to all descendants of the node as well.
132 *
133 * Similar logic shows that a non-normal mask m such that
134 * index(m) <= index(n) could potentially apply to many children of n.
135 * Thus, for each non-host route, we attach its mask to a list at an internal
136 * node as high in the tree as we can go.
137 *
138 * The present version of the code makes use of normal routes in short-
139 * circuiting an explict mask and compare operation when testing whether
140 * a key satisfies a normal route, and also in remembering the unique leaf
141 * that governs a subtree.
142 */
143
144 static struct radix_node *
rn_search(void * v_arg,struct radix_node * head)145 rn_search(void *v_arg, struct radix_node *head)
146 {
147 struct radix_node *x;
148 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 }
157 return x;
158 }
159
160 static struct radix_node *
rn_search_m(void * v_arg,struct radix_node * head,void * m_arg)161 rn_search_m(void *v_arg, struct radix_node *head, void *m_arg)
162 {
163 struct radix_node *x;
164 caddr_t v = v_arg, m = m_arg;
165
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])) {
169 x = x->rn_right;
170 } else {
171 x = x->rn_left;
172 }
173 }
174 return x;
175 }
176
177 int
rn_refines(void * m_arg,void * n_arg)178 rn_refines(void *m_arg, void *n_arg)
179 {
180 caddr_t m = m_arg, n = n_arg;
181 caddr_t lim, lim2 = lim = n + *(u_char *)n;
182 int longer = (*(u_char *)n++) - (int)(*(u_char *)m++);
183 int masks_are_equal = 1;
184
185 if (longer > 0) {
186 lim -= longer;
187 }
188 while (n < lim) {
189 if (*n & ~(*m)) {
190 return 0;
191 }
192 if (*n++ != *m++) {
193 masks_are_equal = 0;
194 }
195 }
196 while (n < lim2) {
197 if (*n++) {
198 return 0;
199 }
200 }
201 if (masks_are_equal && (longer < 0)) {
202 for (lim2 = m - longer; m < lim2;) {
203 if (*m++) {
204 return 1;
205 }
206 }
207 }
208 return !masks_are_equal;
209 }
210
211 struct radix_node *
rn_lookup(void * v_arg,void * m_arg,struct radix_node_head * head)212 rn_lookup(void *v_arg, void *m_arg, struct radix_node_head *head)
213 {
214 return rn_lookup_args(v_arg, m_arg, head, NULL, NULL);
215 }
216
217 struct radix_node *
rn_lookup_args(void * v_arg,void * m_arg,struct radix_node_head * head,rn_matchf_t * f,void * w)218 rn_lookup_args(void *v_arg, void *m_arg, struct radix_node_head *head,
219 rn_matchf_t *f, void *w)
220 {
221 struct radix_node *x;
222 caddr_t netmask = NULL;
223
224 if (m_arg) {
225 x = rn_addmask(m_arg, 1, head->rnh_treetop->rn_offset);
226 if (x == 0) {
227 return NULL;
228 }
229 netmask = x->rn_key;
230 }
231 x = rn_match_args(v_arg, head, f, w);
232 if (x && netmask) {
233 while (x && x->rn_mask != netmask) {
234 x = x->rn_dupedkey;
235 }
236 }
237 return x;
238 }
239
240 /*
241 * Returns true if address 'trial' has no bits differing from the
242 * leaf's key when compared under the leaf's mask. In other words,
243 * returns true when 'trial' matches leaf. If a leaf-matching
244 * routine is passed in, it is also used to find a match on the
245 * conditions defined by the caller of rn_match.
246 */
247 static int
rn_satisfies_leaf(char * trial,struct radix_node * leaf,int skip,rn_matchf_t * f,void * w)248 rn_satisfies_leaf(char *trial, struct radix_node *leaf, int skip,
249 rn_matchf_t *f, void *w)
250 {
251 char *cp = trial, *cp2 = leaf->rn_key, *cp3 = leaf->rn_mask;
252 char *cplim;
253 int length = min(*(u_char *)cp, *(u_char *)cp2);
254
255 if (cp3 == 0) {
256 cp3 = rn_ones;
257 } else {
258 length = min(length, *(u_char *)cp3);
259 }
260 cplim = cp + length; cp3 += skip; cp2 += skip;
261 for (cp += skip; cp < cplim; cp++, cp2++, cp3++) {
262 if ((*cp ^ *cp2) & *cp3) {
263 return 0;
264 }
265 }
266
267 return RN_MATCHF(leaf, f, w);
268 }
269
270 struct radix_node *
rn_match(void * v_arg,struct radix_node_head * head)271 rn_match(void *v_arg, struct radix_node_head *head)
272 {
273 return rn_match_args(v_arg, head, NULL, NULL);
274 }
275
276 struct radix_node *
rn_match_args(void * v_arg,struct radix_node_head * head,rn_matchf_t * f,void * w)277 rn_match_args(void *v_arg, struct radix_node_head *head,
278 rn_matchf_t *f, void *w)
279 {
280 caddr_t v = v_arg;
281 struct radix_node *t = head->rnh_treetop, *x;
282 caddr_t cp = v, cp2;
283 caddr_t cplim;
284 struct radix_node *saved_t, *top = t;
285 int off = t->rn_offset, vlen = *(u_char *)cp, matched_off;
286 int test, b, rn_bit;
287
288 /*
289 * Open code rn_search(v, top) to avoid overhead of extra
290 * subroutine call.
291 */
292 for (; t->rn_bit >= 0;) {
293 if (t->rn_bmask & cp[t->rn_offset]) {
294 t = t->rn_right;
295 } else {
296 t = t->rn_left;
297 }
298 }
299 /*
300 * See if we match exactly as a host destination
301 * or at least learn how many bits match, for normal mask finesse.
302 *
303 * It doesn't hurt us to limit how many bytes to check
304 * to the length of the mask, since if it matches we had a genuine
305 * match and the leaf we have is the most specific one anyway;
306 * if it didn't match with a shorter length it would fail
307 * with a long one. This wins big for class B&C netmasks which
308 * are probably the most common case...
309 */
310 if (t->rn_mask) {
311 vlen = *(u_char *)t->rn_mask;
312 }
313 cp += off; cp2 = t->rn_key + off; cplim = v + vlen;
314 for (; cp < cplim; cp++, cp2++) {
315 if (*cp != *cp2) {
316 goto on1;
317 }
318 }
319 /*
320 * This extra grot is in case we are explicitly asked
321 * to look up the default. Ugh!
322 *
323 * Never return the root node itself, it seems to cause a
324 * lot of confusion.
325 */
326 if (t->rn_flags & RNF_ROOT) {
327 t = t->rn_dupedkey;
328 }
329 if (t == NULL || RN_MATCHF(t, f, w)) {
330 return t;
331 } else {
332 /*
333 * Although we found an exact match on the key,
334 * f() is looking for some other criteria as well.
335 * Continue looking as if the exact match failed.
336 */
337 if (t->rn_parent->rn_flags & RNF_ROOT) {
338 /* Hit the top; have to give up */
339 return NULL;
340 }
341 b = 0;
342 goto keeplooking;
343 }
344 on1:
345 test = (*cp ^ *cp2) & 0xff; /* find first bit that differs */
346 for (b = 7; (test >>= 1) > 0;) {
347 b--;
348 }
349 keeplooking:
350 matched_off = (int)(cp - v);
351 b += matched_off << 3;
352 rn_bit = -1 - b;
353 /*
354 * If there is a host route in a duped-key chain, it will be first.
355 */
356 if ((saved_t = t)->rn_mask == 0) {
357 t = t->rn_dupedkey;
358 }
359 for (; t; t = t->rn_dupedkey) {
360 /*
361 * Even if we don't match exactly as a host,
362 * we may match if the leaf we wound up at is
363 * a route to a net.
364 */
365 if (t->rn_flags & RNF_NORMAL) {
366 if ((rn_bit <= t->rn_bit) && RN_MATCHF(t, f, w)) {
367 return t;
368 }
369 } else if (rn_satisfies_leaf(v, t, matched_off, f, w)) {
370 return t;
371 }
372 }
373 t = saved_t;
374 /* start searching up the tree */
375 do {
376 struct radix_mask *m;
377 t = t->rn_parent;
378 m = t->rn_mklist;
379 /*
380 * If non-contiguous masks ever become important
381 * we can restore the masking and open coding of
382 * the search and satisfaction test and put the
383 * calculation of "off" back before the "do".
384 */
385 while (m) {
386 if (m->rm_flags & RNF_NORMAL) {
387 if ((rn_bit <= m->rm_bit) &&
388 RN_MATCHF(m->rm_leaf, f, w)) {
389 return m->rm_leaf;
390 }
391 } else {
392 off = min(t->rn_offset, matched_off);
393 x = rn_search_m(v, t, m->rm_mask);
394 while (x && x->rn_mask != m->rm_mask) {
395 x = x->rn_dupedkey;
396 }
397 if (x && rn_satisfies_leaf(v, x, off, f, w)) {
398 return x;
399 }
400 }
401 m = m->rm_mklist;
402 }
403 } while (t != top);
404 return NULL;
405 }
406
407 #ifdef RN_DEBUG
408 int rn_nodenum;
409 struct radix_node *rn_clist;
410 int rn_saveinfo;
411 int rn_debug = 1;
412 #endif
413
414 static struct radix_node *
rn_newpair(void * v,int b,struct radix_node nodes[2])415 rn_newpair(void *v, int b, struct radix_node nodes[2])
416 {
417 struct radix_node *tt = nodes, *t = tt + 1;
418 t->rn_bit = (short)b;
419 t->rn_bmask = 0x80 >> (b & 7);
420 t->rn_left = tt;
421 t->rn_offset = b >> 3;
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 = NULL;
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 *
rn_insert(void * v_arg,struct radix_node_head * head,int * dupentry,struct radix_node nodes[2])437 rn_insert(void *v_arg, struct radix_node_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 = (int)*((u_char *)v);
443 struct radix_node *t = rn_search(v_arg, top);
444 caddr_t cp = v + head_off;
445 int b;
446 struct radix_node *tt;
447 /*
448 * Find first bit at which v and t->rn_key differ
449 */
450 {
451 caddr_t cp2 = t->rn_key + head_off;
452 int cmp_res;
453 caddr_t cplim = v + vlen;
454
455 while (cp < cplim) {
456 if (*cp2++ != *cp++) {
457 goto on1;
458 }
459 }
460 *dupentry = 1;
461 return t;
462 on1:
463 *dupentry = 0;
464 cmp_res = (cp[-1] ^ cp2[-1]) & 0xff;
465 for (b = (int)(cp - v) << 3; cmp_res; b--) {
466 cmp_res >>= 1;
467 }
468 }
469 {
470 struct radix_node *p, *x = top;
471 cp = v;
472 do {
473 p = x;
474 if (cp[x->rn_offset] & x->rn_bmask) {
475 x = x->rn_right;
476 } else {
477 x = x->rn_left;
478 }
479 } while (b > (unsigned) x->rn_bit);
480 /* x->rn_bit < b && x->rn_bit >= 0 */
481 #ifdef RN_DEBUG
482 if (rn_debug) {
483 log(LOG_DEBUG, "rn_insert: Going In:\n"), traverse(p);
484 }
485 #endif
486 t = rn_newpair(v_arg, b, nodes);
487 tt = t->rn_left;
488 if ((cp[p->rn_offset] & p->rn_bmask) == 0) {
489 p->rn_left = t;
490 } else {
491 p->rn_right = t;
492 }
493 x->rn_parent = t;
494 t->rn_parent = p; /* frees x, p as temp vars below */
495 if ((cp[t->rn_offset] & t->rn_bmask) == 0) {
496 t->rn_right = x;
497 } else {
498 t->rn_right = tt;
499 t->rn_left = x;
500 }
501 #ifdef RN_DEBUG
502 if (rn_debug) {
503 log(LOG_DEBUG, "rn_insert: Coming Out:\n"), traverse(p);
504 }
505 #endif
506 }
507 return tt;
508 }
509
510 struct radix_node *
rn_addmask(void * n_arg,int search,int skip)511 rn_addmask(void *n_arg, int search, int skip)
512 {
513 caddr_t netmask = (caddr_t)n_arg;
514 struct radix_node *x;
515 caddr_t cp, cplim;
516 int b = 0, mlen, j;
517 int maskduplicated, m0, isnormal;
518 struct radix_node *saved_x;
519 static int last_zeroed = 0;
520
521 if ((mlen = *(u_char *)netmask) > max_keylen) {
522 mlen = max_keylen;
523 }
524 if (skip == 0) {
525 skip = 1;
526 }
527 if (mlen <= skip) {
528 return mask_rnhead->rnh_nodes;
529 }
530 if (skip > 1) {
531 Bcopy(rn_ones + 1, addmask_key + 1, skip - 1);
532 }
533 if ((m0 = mlen) > skip) {
534 Bcopy(netmask + skip, addmask_key + skip, mlen - skip);
535 }
536 /*
537 * Trim trailing zeroes.
538 */
539 for (cp = addmask_key + mlen; (cp > addmask_key) && cp[-1] == 0;) {
540 cp--;
541 }
542 mlen = (int)(cp - addmask_key);
543 if (mlen <= skip) {
544 if (m0 >= last_zeroed) {
545 last_zeroed = mlen;
546 }
547 return mask_rnhead->rnh_nodes;
548 }
549 if (m0 < last_zeroed) {
550 Bzero(addmask_key + m0, last_zeroed - m0);
551 }
552 *addmask_key = last_zeroed = (char)mlen;
553 x = rn_search(addmask_key, rn_masktop);
554 if (Bcmp(addmask_key, x->rn_key, mlen) != 0) {
555 x = NULL;
556 }
557 if (x || search) {
558 return x;
559 }
560 x = saved_x = zalloc_flags(radix_node_zone, Z_WAITOK_ZERO_NOFAIL);
561 netmask = cp = (caddr_t)(x + 2);
562 Bcopy(addmask_key, cp, mlen);
563 x = rn_insert(cp, mask_rnhead, &maskduplicated, x);
564 if (maskduplicated) {
565 log(LOG_ERR, "rn_addmask: mask impossibly already in tree");
566 zfree(radix_node_zone, saved_x);
567 return x;
568 }
569 mask_rnhead->rnh_cnt++;
570 /*
571 * Calculate index of mask, and check for normalcy.
572 */
573 cplim = netmask + mlen; isnormal = 1;
574 for (cp = netmask + skip; (cp < cplim) && *(u_char *)cp == 0xff;) {
575 cp++;
576 }
577 if (cp != cplim) {
578 for (j = 0x80; (j & *cp) != 0; j >>= 1) {
579 b++;
580 }
581 if (*cp != normal_chars[b] || cp != (cplim - 1)) {
582 isnormal = 0;
583 }
584 }
585 b += (cp - netmask) << 3;
586 x->rn_bit = (short)(-1 - b);
587 if (isnormal) {
588 x->rn_flags |= RNF_NORMAL;
589 }
590 return x;
591 }
592
593 static int
594 /* XXX: arbitrary ordering for non-contiguous masks */
rn_lexobetter(void * m_arg,void * n_arg)595 rn_lexobetter(void *m_arg, void *n_arg)
596 {
597 u_char *mp = m_arg, *np = n_arg, *lim;
598
599 if (*mp > *np) {
600 return 1; /* not really, but need to check longer one first */
601 }
602 if (*mp == *np) {
603 for (lim = mp + *mp; mp < lim;) {
604 if (*mp++ > *np++) {
605 return 1;
606 }
607 }
608 }
609 return 0;
610 }
611
612 static struct radix_mask *
rn_new_radix_mask(struct radix_node * tt,struct radix_mask * next)613 rn_new_radix_mask(struct radix_node *tt, struct radix_mask *next)
614 {
615 struct radix_mask *m;
616
617 MKGet(m);
618 m->rm_bit = tt->rn_bit;
619 m->rm_flags = tt->rn_flags;
620 if (tt->rn_flags & RNF_NORMAL) {
621 m->rm_leaf = tt;
622 } else {
623 m->rm_mask = tt->rn_mask;
624 }
625 m->rm_mklist = next;
626 tt->rn_mklist = m;
627 return m;
628 }
629
630 struct radix_node *
rn_addroute(void * v_arg,void * n_arg,struct radix_node_head * head,struct radix_node treenodes[2])631 rn_addroute(void *v_arg, void *n_arg, struct radix_node_head *head,
632 struct radix_node treenodes[2])
633 {
634 caddr_t v = (caddr_t)v_arg, netmask = (caddr_t)n_arg;
635 struct radix_node *t, *x = NULL, *tt;
636 struct radix_node *saved_tt, *top = head->rnh_treetop;
637 short b = 0, b_leaf = 0;
638 int keyduplicated;
639 caddr_t mmask;
640 struct radix_mask *m, **mp;
641
642 /*
643 * In dealing with non-contiguous masks, there may be
644 * many different routes which have the same mask.
645 * We will find it useful to have a unique pointer to
646 * the mask to speed avoiding duplicate references at
647 * nodes and possibly save time in calculating indices.
648 */
649 if (netmask) {
650 if ((x = rn_addmask(netmask, 0, top->rn_offset)) == 0) {
651 return NULL;
652 }
653 b_leaf = x->rn_bit;
654 b = -1 - x->rn_bit;
655 netmask = x->rn_key;
656 }
657 /*
658 * Deal with duplicated keys: attach node to previous instance
659 */
660 saved_tt = tt = rn_insert(v, head, &keyduplicated, treenodes);
661 if (keyduplicated) {
662 for (t = tt; tt; t = tt, tt = tt->rn_dupedkey) {
663 if (tt->rn_mask == netmask) {
664 return NULL;
665 }
666 if (netmask == 0 ||
667 (tt->rn_mask &&
668 ((b_leaf < tt->rn_bit) /* index(netmask) > node */
669 || rn_refines(netmask, tt->rn_mask)
670 || rn_lexobetter(netmask, tt->rn_mask)))) {
671 break;
672 }
673 }
674 /*
675 * If the mask is not duplicated, we wouldn't
676 * find it among possible duplicate key entries
677 * anyway, so the above test doesn't hurt.
678 *
679 * We sort the masks for a duplicated key the same way as
680 * in a masklist -- most specific to least specific.
681 * This may require the unfortunate nuisance of relocating
682 * the head of the list.
683 */
684 if (tt == saved_tt) {
685 struct radix_node *xx = x;
686 /* link in at head of list */
687 (tt = treenodes)->rn_dupedkey = t;
688 tt->rn_flags = t->rn_flags;
689 tt->rn_parent = x = t->rn_parent;
690 t->rn_parent = tt; /* parent */
691 if (x->rn_left == t) {
692 x->rn_left = tt;
693 } else {
694 x->rn_right = tt;
695 }
696 saved_tt = tt; x = xx;
697 } else {
698 (tt = treenodes)->rn_dupedkey = t->rn_dupedkey;
699 t->rn_dupedkey = tt;
700 tt->rn_parent = t; /* parent */
701 if (tt->rn_dupedkey) { /* parent */
702 tt->rn_dupedkey->rn_parent = tt; /* parent */
703 }
704 }
705 #ifdef RN_DEBUG
706 t = tt + 1; tt->rn_info = rn_nodenum++; t->rn_info = rn_nodenum++;
707 tt->rn_twin = t; tt->rn_ybro = rn_clist; rn_clist = tt;
708 #endif
709 tt->rn_key = (caddr_t) v;
710 tt->rn_bit = -1;
711 tt->rn_flags = RNF_ACTIVE;
712 }
713 head->rnh_cnt++;
714 /*
715 * Put mask in tree.
716 */
717 if (netmask) {
718 tt->rn_mask = netmask;
719 tt->rn_bit = x->rn_bit;
720 tt->rn_flags |= x->rn_flags & RNF_NORMAL;
721 }
722 t = saved_tt->rn_parent;
723 if (keyduplicated) {
724 goto on2;
725 }
726 b_leaf = -1 - t->rn_bit;
727 if (t->rn_right == saved_tt) {
728 x = t->rn_left;
729 } else {
730 x = t->rn_right;
731 }
732 /* Promote general routes from below */
733 if (x->rn_bit < 0) {
734 for (mp = &t->rn_mklist; x; x = x->rn_dupedkey) {
735 if (x->rn_mask && (x->rn_bit >= b_leaf) && x->rn_mklist == 0) {
736 *mp = m = rn_new_radix_mask(x, NULL);
737 if (m) {
738 mp = &m->rm_mklist;
739 }
740 }
741 }
742 } else if (x->rn_mklist) {
743 /*
744 * Skip over masks whose index is > that of new node
745 */
746 for (mp = &x->rn_mklist; (m = *mp); mp = &m->rm_mklist) {
747 if (m->rm_bit >= b_leaf) {
748 break;
749 }
750 }
751 t->rn_mklist = m; *mp = NULL;
752 }
753 on2:
754 /* Add new route to highest possible ancestor's list */
755 if ((netmask == 0) || (b > t->rn_bit)) {
756 return tt; /* can't lift at all */
757 }
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 }
773 if (m->rm_bit > b_leaf) {
774 break;
775 }
776 if (m->rm_flags & RNF_NORMAL) {
777 mmask = m->rm_leaf->rn_mask;
778 if (tt->rn_flags & RNF_NORMAL) {
779 log(LOG_ERR,
780 "Non-unique normal route, mask not entered");
781 return tt;
782 }
783 } else {
784 mmask = m->rm_mask;
785 }
786 if (mmask == netmask) {
787 m->rm_refs++;
788 tt->rn_mklist = m;
789 return tt;
790 }
791 if (rn_refines(netmask, mmask)
792 || rn_lexobetter(netmask, mmask)) {
793 break;
794 }
795 }
796 *mp = rn_new_radix_mask(tt, *mp);
797 return tt;
798 }
799
800 struct radix_node *
rn_delete(void * v_arg,void * netmask_arg,struct radix_node_head * head)801 rn_delete(void *v_arg, void *netmask_arg, struct radix_node_head *head)
802 {
803 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 = *(u_char *)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 NULL;
820 }
821 /*
822 * Delete our route from mask lists.
823 */
824 if (netmask) {
825 if ((x = rn_addmask(netmask, 1, head_off)) == 0) {
826 return NULL;
827 }
828 netmask = x->rn_key;
829 while (tt->rn_mask != netmask) {
830 if ((tt = tt->rn_dupedkey) == 0) {
831 return NULL;
832 }
833 }
834 }
835 if (tt->rn_mask == 0 || (saved_m = m = tt->rn_mklist) == 0) {
836 goto on1;
837 }
838 if (tt->rn_flags & RNF_NORMAL) {
839 if (m->rm_leaf != tt || m->rm_refs > 0) {
840 log(LOG_ERR, "rn_delete: inconsistent annotation\n");
841 return NULL; /* dangling ref could cause disaster */
842 }
843 } else {
844 if (m->rm_mask != tt->rn_mask) {
845 log(LOG_ERR, "rn_delete: inconsistent annotation\n");
846 goto on1;
847 }
848 if (--m->rm_refs >= 0) {
849 goto on1;
850 }
851 }
852 b = -1 - tt->rn_bit;
853 t = saved_tt->rn_parent;
854 if (b > t->rn_bit) {
855 goto on1; /* Wasn't lifted at all */
856 }
857 do {
858 x = t;
859 t = t->rn_parent;
860 } while (b <= t->rn_bit && x != top);
861 for (mp = &x->rn_mklist; (m = *mp); mp = &m->rm_mklist) {
862 if (m == saved_m) {
863 *mp = m->rm_mklist;
864 if (tt->rn_mklist == m) {
865 tt->rn_mklist = *mp;
866 }
867 MKFree(m);
868 break;
869 }
870 }
871 if (m == 0) {
872 log(LOG_ERR, "rn_delete: couldn't find our annotation\n");
873 if (tt->rn_flags & RNF_NORMAL) {
874 return NULL; /* Dangling ref to us */
875 }
876 }
877 on1:
878 /*
879 * Eliminate us from tree
880 */
881 if (tt->rn_flags & RNF_ROOT) {
882 return NULL;
883 }
884 head->rnh_cnt--;
885 #ifdef RN_DEBUG
886 /* Get us out of the creation list */
887 for (t = rn_clist; t && t->rn_ybro != tt; t = t->rn_ybro) {
888 }
889 if (t) {
890 t->rn_ybro = tt->rn_ybro;
891 }
892 #endif
893 t = tt->rn_parent;
894 dupedkey = saved_tt->rn_dupedkey;
895 if (dupedkey) {
896 /*
897 * at this point, tt is the deletion target and saved_tt
898 * is the head of the dupekey chain
899 */
900 if (tt == saved_tt) {
901 /* remove from head of chain */
902 x = dupedkey; x->rn_parent = t;
903 if (t->rn_left == tt) {
904 t->rn_left = x;
905 } else {
906 t->rn_right = x;
907 }
908 } else {
909 /* find node in front of tt on the chain */
910 for (x = p = saved_tt; p && p->rn_dupedkey != tt;) {
911 p = p->rn_dupedkey;
912 }
913 if (p) {
914 p->rn_dupedkey = tt->rn_dupedkey;
915 if (tt->rn_dupedkey) { /* parent */
916 tt->rn_dupedkey->rn_parent = p;
917 }
918 /* parent */
919 } else {
920 log(LOG_ERR, "rn_delete: couldn't find us\n");
921 }
922 }
923 t = tt + 1;
924 if (t->rn_flags & RNF_ACTIVE) {
925 #ifndef RN_DEBUG
926 *++x = *t;
927 p = t->rn_parent;
928 #else
929 b = t->rn_info;
930 *++x = *t;
931 t->rn_info = b;
932 p = t->rn_parent;
933 #endif
934 if (p->rn_left == t) {
935 p->rn_left = x;
936 } else {
937 p->rn_right = x;
938 }
939 x->rn_left->rn_parent = x;
940 x->rn_right->rn_parent = x;
941 }
942 goto out;
943 }
944 if (t->rn_left == tt) {
945 x = t->rn_right;
946 } else {
947 x = t->rn_left;
948 }
949 p = t->rn_parent;
950 if (p->rn_right == t) {
951 p->rn_right = x;
952 } else {
953 p->rn_left = x;
954 }
955 x->rn_parent = p;
956 /*
957 * Demote routes attached to us.
958 */
959 if (t->rn_mklist) {
960 if (x->rn_bit >= 0) {
961 for (mp = &x->rn_mklist; (m = *mp);) {
962 mp = &m->rm_mklist;
963 }
964 *mp = t->rn_mklist;
965 } else {
966 /* If there are any key,mask pairs in a sibling
967 * duped-key chain, some subset will appear sorted
968 * in the same order attached to our mklist */
969 for (m = t->rn_mklist; m && x; x = x->rn_dupedkey) {
970 if (m == x->rn_mklist) {
971 struct radix_mask *mm = m->rm_mklist;
972 x->rn_mklist = NULL;
973 if (--(m->rm_refs) < 0) {
974 MKFree(m);
975 }
976 m = mm;
977 }
978 }
979 if (m) {
980 log(LOG_ERR, "rn_delete: Orphaned Mask "
981 "0x%llx at 0x%llx\n",
982 (uint64_t)VM_KERNEL_ADDRPERM(m),
983 (uint64_t)VM_KERNEL_ADDRPERM(x));
984 }
985 }
986 }
987 /*
988 * We may be holding an active internal node in the tree.
989 */
990 x = tt + 1;
991 if (t != x) {
992 #ifndef RN_DEBUG
993 *t = *x;
994 #else
995 b = t->rn_info;
996 *t = *x;
997 t->rn_info = b;
998 #endif
999 t->rn_left->rn_parent = t;
1000 t->rn_right->rn_parent = t;
1001 p = x->rn_parent;
1002 if (p->rn_left == x) {
1003 p->rn_left = t;
1004 } else {
1005 p->rn_right = t;
1006 }
1007 }
1008 out:
1009 tt->rn_flags &= ~RNF_ACTIVE;
1010 tt[1].rn_flags &= ~RNF_ACTIVE;
1011 return tt;
1012 }
1013
1014 /*
1015 * This is the same as rn_walktree() except for the parameters and the
1016 * exit.
1017 */
1018 static int
rn_walktree_from(struct radix_node_head * h,void * a,void * m,walktree_f_t * f,void * w)1019 rn_walktree_from(struct radix_node_head *h, void *a, void *m, walktree_f_t *f,
1020 void *w)
1021 {
1022 int error;
1023 struct radix_node *base, *next;
1024 u_char *xa = (u_char *)a;
1025 u_char *xm = (u_char *)m;
1026 struct radix_node *rn, *last;
1027 int stopping;
1028 int lastb;
1029 int rnh_cnt;
1030
1031 /*
1032 * This gets complicated because we may delete the node while
1033 * applying the function f to it; we cannot simply use the next
1034 * leaf as the successor node in advance, because that leaf may
1035 * be removed as well during deletion when it is a clone of the
1036 * current node. When that happens, we would end up referring
1037 * to an already-freed radix node as the successor node. To get
1038 * around this issue, if we detect that the radix tree has changed
1039 * in dimension (smaller than before), we simply restart the walk
1040 * from the top of tree.
1041 */
1042 restart:
1043 last = NULL;
1044 stopping = 0;
1045 rnh_cnt = h->rnh_cnt;
1046
1047 /*
1048 * rn_search_m is sort-of-open-coded here.
1049 */
1050 for (rn = h->rnh_treetop; rn->rn_bit >= 0;) {
1051 last = rn;
1052 if (!(rn->rn_bmask & xm[rn->rn_offset])) {
1053 break;
1054 }
1055
1056 if (rn->rn_bmask & xa[rn->rn_offset]) {
1057 rn = rn->rn_right;
1058 } else {
1059 rn = rn->rn_left;
1060 }
1061 }
1062
1063 /*
1064 * Two cases: either we stepped off the end of our mask,
1065 * in which case last == rn, or we reached a leaf, in which
1066 * case we want to start from the last node we looked at.
1067 * Either way, last is the node we want to start from.
1068 */
1069 rn = last;
1070 lastb = rn->rn_bit;
1071
1072 /* First time through node, go left */
1073 while (rn->rn_bit >= 0) {
1074 rn = rn->rn_left;
1075 }
1076
1077 while (!stopping) {
1078 base = rn;
1079 /* If at right child go back up, otherwise, go right */
1080 while (rn->rn_parent->rn_right == rn
1081 && !(rn->rn_flags & RNF_ROOT)) {
1082 rn = rn->rn_parent;
1083
1084 /* if went up beyond last, stop */
1085 if (rn->rn_bit <= lastb) {
1086 stopping = 1;
1087 /*
1088 * XXX we should jump to the 'Process leaves'
1089 * part, because the values of 'rn' and 'next'
1090 * we compute will not be used. Not a big deal
1091 * because this loop will terminate, but it is
1092 * inefficient and hard to understand!
1093 */
1094 }
1095 }
1096
1097 /*
1098 * The following code (bug fix) inherited from FreeBSD is
1099 * currently disabled, because our implementation uses the
1100 * RTF_PRCLONING scheme that has been abandoned in current
1101 * FreeBSD release. The scheme involves setting such a flag
1102 * for the default route entry, and therefore all off-link
1103 * destinations would become clones of that entry. Enabling
1104 * the following code would be problematic at this point,
1105 * because the removal of default route would cause only
1106 * the left-half of the tree to be traversed, leaving the
1107 * right-half untouched. If there are clones of the entry
1108 * that reside in that right-half, they would not be deleted
1109 * and would linger around until they expire or explicitly
1110 * deleted, which is a very bad thing.
1111 *
1112 * This code should be uncommented only after we get rid
1113 * of the RTF_PRCLONING scheme.
1114 */
1115 #if 0
1116 /*
1117 * At the top of the tree, no need to traverse the right
1118 * half, prevent the traversal of the entire tree in the
1119 * case of default route.
1120 */
1121 if (rn->rn_parent->rn_flags & RNF_ROOT) {
1122 stopping = 1;
1123 }
1124 #endif
1125
1126 /* Find the next *leaf* to start from */
1127 for (rn = rn->rn_parent->rn_right; rn->rn_bit >= 0;) {
1128 rn = rn->rn_left;
1129 }
1130 next = rn;
1131 /* Process leaves */
1132 while ((rn = base) != 0) {
1133 base = rn->rn_dupedkey;
1134 if (!(rn->rn_flags & RNF_ROOT)
1135 && (error = (*f)(rn, w))) {
1136 return error;
1137 }
1138 }
1139 /* If one or more nodes got deleted, restart from top */
1140 if (h->rnh_cnt < rnh_cnt) {
1141 goto restart;
1142 }
1143 rn = next;
1144 if (rn->rn_flags & RNF_ROOT) {
1145 stopping = 1;
1146 }
1147 }
1148 return 0;
1149 }
1150
1151 static int
rn_walktree(struct radix_node_head * h,walktree_f_t * f,void * w)1152 rn_walktree(struct radix_node_head *h, walktree_f_t *f, void *w)
1153 {
1154 int error;
1155 struct radix_node *base, *next;
1156 struct radix_node *rn;
1157 int rnh_cnt;
1158
1159 /*
1160 * This gets complicated because we may delete the node while
1161 * applying the function f to it; we cannot simply use the next
1162 * leaf as the successor node in advance, because that leaf may
1163 * be removed as well during deletion when it is a clone of the
1164 * current node. When that happens, we would end up referring
1165 * to an already-freed radix node as the successor node. To get
1166 * around this issue, if we detect that the radix tree has changed
1167 * in dimension (smaller than before), we simply restart the walk
1168 * from the top of tree.
1169 */
1170 restart:
1171 rn = h->rnh_treetop;
1172 rnh_cnt = h->rnh_cnt;
1173
1174 /* First time through node, go left */
1175 while (rn->rn_bit >= 0) {
1176 rn = rn->rn_left;
1177 }
1178 for (;;) {
1179 base = rn;
1180 /* If at right child go back up, otherwise, go right */
1181 while (rn->rn_parent->rn_right == rn &&
1182 (rn->rn_flags & RNF_ROOT) == 0) {
1183 rn = rn->rn_parent;
1184 }
1185 /* Find the next *leaf* to start from */
1186 for (rn = rn->rn_parent->rn_right; rn->rn_bit >= 0;) {
1187 rn = rn->rn_left;
1188 }
1189 next = rn;
1190 /* Process leaves */
1191 while ((rn = base) != NULL) {
1192 base = rn->rn_dupedkey;
1193 if (!(rn->rn_flags & RNF_ROOT)
1194 && (error = (*f)(rn, w))) {
1195 return error;
1196 }
1197 }
1198 /* If one or more nodes got deleted, restart from top */
1199 if (h->rnh_cnt < rnh_cnt) {
1200 goto restart;
1201 }
1202 rn = next;
1203 if (rn->rn_flags & RNF_ROOT) {
1204 return 0;
1205 }
1206 }
1207 /* NOTREACHED */
1208 }
1209
1210 int
rn_inithead(void ** head,int off)1211 rn_inithead(void **head, int off)
1212 {
1213 struct radix_node_head *rnh;
1214 struct radix_node *t, *tt, *ttt;
1215 if (off > INT8_MAX) {
1216 return 0;
1217 }
1218 if (*head) {
1219 return 1;
1220 }
1221
1222 rnh = zalloc_flags(radix_node_head_zone, Z_WAITOK_ZERO_NOFAIL);
1223 *head = rnh;
1224 t = rn_newpair(rn_zeros, off, rnh->rnh_nodes);
1225 ttt = rnh->rnh_nodes + 2;
1226 t->rn_right = ttt;
1227 t->rn_parent = t;
1228 tt = t->rn_left;
1229 tt->rn_flags = t->rn_flags = RNF_ROOT | RNF_ACTIVE;
1230 tt->rn_bit = (short)(-1 - off);
1231 *ttt = *tt;
1232 ttt->rn_key = rn_ones;
1233 rnh->rnh_addaddr = rn_addroute;
1234 rnh->rnh_deladdr = rn_delete;
1235 rnh->rnh_matchaddr = rn_match;
1236 rnh->rnh_matchaddr_args = rn_match_args;
1237 rnh->rnh_lookup = rn_lookup;
1238 rnh->rnh_lookup_args = rn_lookup_args;
1239 rnh->rnh_walktree = rn_walktree;
1240 rnh->rnh_walktree_from = rn_walktree_from;
1241 rnh->rnh_treetop = t;
1242 rnh->rnh_cnt = 3;
1243 return 1;
1244 }
1245
1246 void
rn_init(void)1247 rn_init(void)
1248 {
1249 char *cp, *cplim;
1250 struct domain *dom;
1251
1252 /* lock already held when rn_init is called */
1253 TAILQ_FOREACH(dom, &domains, dom_entry) {
1254 if (dom->dom_maxrtkey > max_keylen) {
1255 max_keylen = dom->dom_maxrtkey;
1256 }
1257 }
1258 if (max_keylen == 0) {
1259 log(LOG_ERR,
1260 "rn_init: radix functions require max_keylen be set\n");
1261 return;
1262 }
1263 rn_zeros = zalloc_permanent(3 * max_keylen, ZALIGN_NONE);
1264 rn_ones = cp = rn_zeros + max_keylen;
1265 addmask_key = cplim = rn_ones + max_keylen;
1266 while (cp < cplim) {
1267 *cp++ = -1;
1268 }
1269 if (rn_inithead((void **)&mask_rnhead, 0) == 0) {
1270 panic("rn_init 2");
1271 }
1272
1273 radix_node_zone = zone_create("radix_node",
1274 sizeof(struct radix_node) * 2 + max_keylen,
1275 ZC_PGZ_USE_GUARDS | ZC_ZFREE_CLEARMEM);
1276 }
1277