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