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