17 17 17 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 | /* $NetBSD: keccak.c,v 1.1 2017/11/30 05:47:24 riastradh Exp $ */ /*- * Copyright (c) 2015 Taylor R. Campbell * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include <sys/cdefs.h> #if defined(_KERNEL) || defined(_STANDALONE) __KERNEL_RCSID(0, "$NetBSD: keccak.c,v 1.1 2017/11/30 05:47:24 riastradh Exp $"); #include <sys/types.h> #else __RCSID("$NetBSD: keccak.c,v 1.1 2017/11/30 05:47:24 riastradh Exp $"); #include <stdint.h> #endif #include "keccak.h" #define secret /* can't use in variable-time operations, should zero */ #define FOR5(X, STMT) do \ { \ (X) = 0; STMT; \ (X) = 1; STMT; \ (X) = 2; STMT; \ (X) = 3; STMT; \ (X) = 4; STMT; \ } while (0) static inline secret uint64_t rol64(secret uint64_t v, unsigned c) { return ((v << c) | (v >> (64 - c))); } static inline void keccakf1600_theta(secret uint64_t A[25]) { secret uint64_t C0, C1, C2, C3, C4; unsigned y; C0 = C1 = C2 = C3 = C4 = 0; FOR5(y, { C0 ^= A[0 + 5*y]; C1 ^= A[1 + 5*y]; C2 ^= A[2 + 5*y]; C3 ^= A[3 + 5*y]; C4 ^= A[4 + 5*y]; }); FOR5(y, { A[0 + 5*y] ^= C4 ^ rol64(C1, 1); A[1 + 5*y] ^= C0 ^ rol64(C2, 1); A[2 + 5*y] ^= C1 ^ rol64(C3, 1); A[3 + 5*y] ^= C2 ^ rol64(C4, 1); A[4 + 5*y] ^= C3 ^ rol64(C0, 1); }); } static inline void keccakf1600_rho_pi(secret uint64_t A[25]) { secret uint64_t T, U; /* * Permute by (x,y) |---> (y, 2x + 3y mod 5) starting at (1,0), * rotate the ith element by (i + 1)(i + 2)/2 mod 64. */ U = A[ 1]; T = U; U = A[10]; A[10] = rol64(T, 1); T = U; U = A[ 7]; A[ 7] = rol64(T, 3); T = U; U = A[11]; A[11] = rol64(T, 6); T = U; U = A[17]; A[17] = rol64(T, 10); T = U; U = A[18]; A[18] = rol64(T, 15); T = U; U = A[ 3]; A[ 3] = rol64(T, 21); T = U; U = A[ 5]; A[ 5] = rol64(T, 28); T = U; U = A[16]; A[16] = rol64(T, 36); T = U; U = A[ 8]; A[ 8] = rol64(T, 45); T = U; U = A[21]; A[21] = rol64(T, 55); T = U; U = A[24]; A[24] = rol64(T, 2); T = U; U = A[ 4]; A[ 4] = rol64(T, 14); T = U; U = A[15]; A[15] = rol64(T, 27); T = U; U = A[23]; A[23] = rol64(T, 41); T = U; U = A[19]; A[19] = rol64(T, 56); T = U; U = A[13]; A[13] = rol64(T, 8); T = U; U = A[12]; A[12] = rol64(T, 25); T = U; U = A[ 2]; A[ 2] = rol64(T, 43); T = U; U = A[20]; A[20] = rol64(T, 62); T = U; U = A[14]; A[14] = rol64(T, 18); T = U; U = A[22]; A[22] = rol64(T, 39); T = U; U = A[ 9]; A[ 9] = rol64(T, 61); T = U; U = A[ 6]; A[ 6] = rol64(T, 20); T = U; A[ 1] = rol64(T, 44); } static inline void keccakf1600_chi(secret uint64_t A[25]) { secret uint64_t B0, B1, B2, B3, B4; unsigned y; FOR5(y, { B0 = A[0 + 5*y]; B1 = A[1 + 5*y]; B2 = A[2 + 5*y]; B3 = A[3 + 5*y]; B4 = A[4 + 5*y]; A[0 + 5*y] ^= ~B1 & B2; A[1 + 5*y] ^= ~B2 & B3; A[2 + 5*y] ^= ~B3 & B4; A[3 + 5*y] ^= ~B4 & B0; A[4 + 5*y] ^= ~B0 & B1; }); } static void keccakf1600_round(secret uint64_t A[25]) { keccakf1600_theta(A); keccakf1600_rho_pi(A); keccakf1600_chi(A); } void keccakf1600(secret uint64_t A[25]) { /* * RC[i] = \sum_{j = 0,...,6} rc(j + 7i) 2^(2^j - 1), * rc(t) = (x^t mod x^8 + x^6 + x^5 + x^4 + 1) mod x in GF(2)[x] */ static const uint64_t RC[24] = { 0x0000000000000001ULL, 0x0000000000008082ULL, 0x800000000000808aULL, 0x8000000080008000ULL, 0x000000000000808bULL, 0x0000000080000001ULL, 0x8000000080008081ULL, 0x8000000000008009ULL, 0x000000000000008aULL, 0x0000000000000088ULL, 0x0000000080008009ULL, 0x000000008000000aULL, 0x000000008000808bULL, 0x800000000000008bULL, 0x8000000000008089ULL, 0x8000000000008003ULL, 0x8000000000008002ULL, 0x8000000000000080ULL, 0x000000000000800aULL, 0x800000008000000aULL, 0x8000000080008081ULL, 0x8000000000008080ULL, 0x0000000080000001ULL, 0x8000000080008008ULL, }; unsigned i; for (i = 0; i < 24; i++) { keccakf1600_round(A); A[0] ^= RC[i]; } } |
2 1 2 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 | /* $NetBSD: uftdi.c,v 1.76 2021/08/07 16:19:17 thorpej Exp $ */ /* * Copyright (c) 2000 The NetBSD Foundation, Inc. * All rights reserved. * * This code is derived from software contributed to The NetBSD Foundation * by Lennart Augustsson (lennart@augustsson.net). * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include <sys/cdefs.h> __KERNEL_RCSID(0, "$NetBSD: uftdi.c,v 1.76 2021/08/07 16:19:17 thorpej Exp $"); #ifdef _KERNEL_OPT #include "opt_usb.h" #endif #include <sys/param.h> #include <sys/systm.h> #include <sys/kernel.h> #include <sys/device.h> #include <sys/conf.h> #include <sys/tty.h> #include <dev/usb/usb.h> #include <dev/usb/usbdi.h> #include <dev/usb/usbdi_util.h> #include <dev/usb/usbdevs.h> #include <dev/usb/ucomvar.h> #include <dev/usb/uftdireg.h> #ifdef UFTDI_DEBUG #define DPRINTF(x) if (uftdidebug) printf x #define DPRINTFN(n,x) if (uftdidebug>(n)) printf x int uftdidebug = 0; #else #define DPRINTF(x) #define DPRINTFN(n,x) #endif #define UFTDI_CONFIG_NO 1 /* * These are the default number of bytes transferred per frame if the * endpoint doesn't tell us. The output buffer size is a hard limit * for devices that use a 6-bit size encoding. */ #define UFTDIIBUFSIZE 64 #define UFTDIOBUFSIZE 64 /* * Magic constants! Where do these come from? They're what Linux uses... */ #define UFTDI_MAX_IBUFSIZE 512 #define UFTDI_MAX_OBUFSIZE 256 struct uftdi_softc { device_t sc_dev; /* base device */ struct usbd_device * sc_udev; /* device */ struct usbd_interface * sc_iface; /* interface */ int sc_iface_no; enum uftdi_type sc_type; u_int sc_flags; #define FLAGS_BAUDCLK_12M 0x00000001 #define FLAGS_ROUNDOFF_232A 0x00000002 #define FLAGS_BAUDBITS_HINDEX 0x00000004 u_int sc_hdrlen; u_int sc_chiptype; u_char sc_msr; u_char sc_lsr; device_t sc_subdev; bool sc_dying; u_int last_lcr; }; static void uftdi_get_status(void *, int, u_char *, u_char *); static void uftdi_set(void *, int, int, int); static int uftdi_param(void *, int, struct termios *); static int uftdi_open(void *, int); static void uftdi_read(void *, int, u_char **, uint32_t *); static void uftdi_write(void *, int, u_char *, u_char *, uint32_t *); static void uftdi_break(void *, int, int); static const struct ucom_methods uftdi_methods = { .ucom_get_status = uftdi_get_status, .ucom_set = uftdi_set, .ucom_param = uftdi_param, .ucom_open = uftdi_open, .ucom_read = uftdi_read, .ucom_write = uftdi_write, }; /* * The devices default to UFTDI_TYPE_8U232AM. * Remember to update uftdi_attach() if it should be UFTDI_TYPE_SIO instead */ static const struct usb_devno uftdi_devs[] = { { USB_VENDOR_BBELECTRONICS, USB_PRODUCT_BBELECTRONICS_USOTL4 }, { USB_VENDOR_FALCOM, USB_PRODUCT_FALCOM_TWIST }, { USB_VENDOR_FALCOM, USB_PRODUCT_FALCOM_SAMBA }, { USB_VENDOR_FTDI, USB_PRODUCT_FTDI_SERIAL_230X }, { USB_VENDOR_FTDI, USB_PRODUCT_FTDI_SERIAL_232H }, { USB_VENDOR_FTDI, USB_PRODUCT_FTDI_SERIAL_232RL }, { USB_VENDOR_FTDI, USB_PRODUCT_FTDI_SERIAL_2232C }, { USB_VENDOR_FTDI, USB_PRODUCT_FTDI_SERIAL_4232H }, { USB_VENDOR_FTDI, USB_PRODUCT_FTDI_SERIAL_8U100AX }, { USB_VENDOR_FTDI, USB_PRODUCT_FTDI_SERIAL_8U232AM }, { USB_VENDOR_FTDI, USB_PRODUCT_FTDI_MHAM_KW }, { USB_VENDOR_FTDI, USB_PRODUCT_FTDI_MHAM_YS }, { USB_VENDOR_FTDI, USB_PRODUCT_FTDI_MHAM_Y6 }, { USB_VENDOR_FTDI, USB_PRODUCT_FTDI_MHAM_Y8 }, { USB_VENDOR_FTDI, USB_PRODUCT_FTDI_MHAM_IC }, { USB_VENDOR_FTDI, USB_PRODUCT_FTDI_MHAM_DB9 }, { USB_VENDOR_FTDI, USB_PRODUCT_FTDI_MHAM_RS232 }, { USB_VENDOR_FTDI, USB_PRODUCT_FTDI_MHAM_Y9 }, { USB_VENDOR_FTDI, USB_PRODUCT_FTDI_COASTAL_TNCX }, { USB_VENDOR_FTDI, USB_PRODUCT_FTDI_CTI_485_MINI }, { USB_VENDOR_FTDI, USB_PRODUCT_FTDI_CTI_NANO_485 }, { USB_VENDOR_FTDI, USB_PRODUCT_FTDI_SEMC_DSS20 }, { USB_VENDOR_FTDI, USB_PRODUCT_FTDI_LCD_LK202_24_USB }, { USB_VENDOR_FTDI, USB_PRODUCT_FTDI_LCD_LK204_24_USB }, { USB_VENDOR_FTDI, USB_PRODUCT_FTDI_LCD_MX200_USB }, { USB_VENDOR_FTDI, USB_PRODUCT_FTDI_LCD_MX4_MX5_USB }, { USB_VENDOR_FTDI, USB_PRODUCT_FTDI_LCD_CFA_631 }, { USB_VENDOR_FTDI, USB_PRODUCT_FTDI_LCD_CFA_632 }, { USB_VENDOR_FTDI, USB_PRODUCT_FTDI_LCD_CFA_633 }, { USB_VENDOR_FTDI, USB_PRODUCT_FTDI_LCD_CFA_634 }, { USB_VENDOR_FTDI, USB_PRODUCT_FTDI_LCD_CFA_635 }, { USB_VENDOR_FTDI, USB_PRODUCT_FTDI_OPENRD_JTAGKEY }, { USB_VENDOR_FTDI, USB_PRODUCT_FTDI_BEAGLEBONE }, { USB_VENDOR_FTDI, USB_PRODUCT_FTDI_MAXSTREAM_PKG_U }, { USB_VENDOR_xxFTDI, USB_PRODUCT_xxFTDI_SHEEVAPLUG_JTAG }, { USB_VENDOR_INTREPIDCS, USB_PRODUCT_INTREPIDCS_VALUECAN }, { USB_VENDOR_INTREPIDCS, USB_PRODUCT_INTREPIDCS_NEOVI }, { USB_VENDOR_MELCO, USB_PRODUCT_MELCO_PCOPRS1 }, { USB_VENDOR_RATOC, USB_PRODUCT_RATOC_REXUSB60F }, { USB_VENDOR_RTSYS, USB_PRODUCT_RTSYS_CT57A }, { USB_VENDOR_RTSYS, USB_PRODUCT_RTSYS_RTS03 }, { USB_VENDOR_SEALEVEL, USB_PRODUCT_SEALEVEL_USBSERIAL }, { USB_VENDOR_SEALEVEL, USB_PRODUCT_SEALEVEL_SEAPORT4P1 }, { USB_VENDOR_SEALEVEL, USB_PRODUCT_SEALEVEL_SEAPORT4P2 }, { USB_VENDOR_SEALEVEL, USB_PRODUCT_SEALEVEL_SEAPORT4P3 }, { USB_VENDOR_SEALEVEL, USB_PRODUCT_SEALEVEL_SEAPORT4P4 }, { USB_VENDOR_SIIG2, USB_PRODUCT_SIIG2_US2308 }, { USB_VENDOR_MISC, USB_PRODUCT_MISC_TELLSTICK }, { USB_VENDOR_MISC, USB_PRODUCT_MISC_TELLSTICK_DUO }, }; #define uftdi_lookup(v, p) usb_lookup(uftdi_devs, v, p) static int uftdi_match(device_t, cfdata_t, void *); static void uftdi_attach(device_t, device_t, void *); static void uftdi_childdet(device_t, device_t); static int uftdi_detach(device_t, int); CFATTACH_DECL2_NEW(uftdi, sizeof(struct uftdi_softc), uftdi_match, uftdi_attach, uftdi_detach, NULL, NULL, uftdi_childdet); static int uftdi_match(device_t parent, cfdata_t match, void *aux) { struct usbif_attach_arg *uiaa = aux; DPRINTFN(20,("uftdi: vendor=%#x, product=%#x\n", uiaa->uiaa_vendor, uiaa->uiaa_product)); if (uiaa->uiaa_configno != UFTDI_CONFIG_NO) return UMATCH_NONE; return uftdi_lookup(uiaa->uiaa_vendor, uiaa->uiaa_product) != NULL ? UMATCH_VENDOR_PRODUCT_CONF_IFACE : UMATCH_NONE; } static void uftdi_attach(device_t parent, device_t self, void *aux) { struct uftdi_softc *sc = device_private(self); struct usbif_attach_arg *uiaa = aux; struct usbd_device *dev = uiaa->uiaa_device; struct usbd_interface *iface = uiaa->uiaa_iface; usb_device_descriptor_t *ddesc; usb_interface_descriptor_t *id; usb_endpoint_descriptor_t *ed; char *devinfop; int i; struct ucom_attach_args ucaa; DPRINTFN(10,("\nuftdi_attach: sc=%p\n", sc)); aprint_naive("\n"); aprint_normal("\n"); devinfop = usbd_devinfo_alloc(dev, 0); aprint_normal_dev(self, "%s\n", devinfop); usbd_devinfo_free(devinfop); sc->sc_dev = self; sc->sc_udev = dev; sc->sc_dying = false; sc->sc_iface_no = uiaa->uiaa_ifaceno; sc->sc_type = UFTDI_TYPE_8U232AM; /* most devices are post-8U232AM */ sc->sc_hdrlen = 0; ddesc = usbd_get_device_descriptor(dev); sc->sc_chiptype = UGETW(ddesc->bcdDevice); switch (sc->sc_chiptype) { case 0x0200: if (ddesc->iSerialNumber != 0) sc->sc_flags |= FLAGS_ROUNDOFF_232A; ucaa.ucaa_portno = 0; break; case 0x0400: ucaa.ucaa_portno = 0; break; case 0x0500: sc->sc_flags |= FLAGS_BAUDBITS_HINDEX; ucaa.ucaa_portno = FTDI_PIT_SIOA + sc->sc_iface_no; break; case 0x0600: ucaa.ucaa_portno = 0; break; case 0x0700: case 0x0800: case 0x0900: sc->sc_flags |= FLAGS_BAUDCLK_12M; sc->sc_flags |= FLAGS_BAUDBITS_HINDEX; ucaa.ucaa_portno = FTDI_PIT_SIOA + sc->sc_iface_no; break; case 0x1000: sc->sc_flags |= FLAGS_BAUDBITS_HINDEX; ucaa.ucaa_portno = FTDI_PIT_SIOA + sc->sc_iface_no; break; default: if (sc->sc_chiptype < 0x0200) { sc->sc_type = UFTDI_TYPE_SIO; sc->sc_hdrlen = 1; } ucaa.ucaa_portno = 0; break; } id = usbd_get_interface_descriptor(iface); sc->sc_iface = iface; ucaa.ucaa_bulkin = ucaa.ucaa_bulkout = -1; ucaa.ucaa_ibufsize = ucaa.ucaa_obufsize = 0; for (i = 0; i < id->bNumEndpoints; i++) { int addr, dir, attr; ed = usbd_interface2endpoint_descriptor(iface, i); if (ed == NULL) { aprint_error_dev(self, "could not read endpoint descriptor\n"); goto bad; } addr = ed->bEndpointAddress; dir = UE_GET_DIR(ed->bEndpointAddress); attr = ed->bmAttributes & UE_XFERTYPE; if (dir == UE_DIR_IN && attr == UE_BULK) { ucaa.ucaa_bulkin = addr; ucaa.ucaa_ibufsize = UGETW(ed->wMaxPacketSize); if (ucaa.ucaa_ibufsize >= UFTDI_MAX_IBUFSIZE) ucaa.ucaa_ibufsize = UFTDI_MAX_IBUFSIZE; } else if (dir == UE_DIR_OUT && attr == UE_BULK) { ucaa.ucaa_bulkout = addr; ucaa.ucaa_obufsize = UGETW(ed->wMaxPacketSize) - sc->sc_hdrlen; if (ucaa.ucaa_obufsize >= UFTDI_MAX_OBUFSIZE) ucaa.ucaa_obufsize = UFTDI_MAX_OBUFSIZE; /* Limit length if we have a 6-bit header. */ if ((sc->sc_hdrlen > 0) && (ucaa.ucaa_obufsize > UFTDIOBUFSIZE)) ucaa.ucaa_obufsize = UFTDIOBUFSIZE; } else { aprint_error_dev(self, "unexpected endpoint\n"); goto bad; } } if (ucaa.ucaa_bulkin == -1) { aprint_error_dev(self, "Could not find data bulk in\n"); goto bad; } if (ucaa.ucaa_bulkout == -1) { aprint_error_dev(self, "Could not find data bulk out\n"); goto bad; } /* ucaa_bulkin, ucaa_bulkout set above */ if (ucaa.ucaa_ibufsize == 0) ucaa.ucaa_ibufsize = UFTDIIBUFSIZE; ucaa.ucaa_ibufsizepad = ucaa.ucaa_ibufsize; if (ucaa.ucaa_obufsize == 0) ucaa.ucaa_obufsize = UFTDIOBUFSIZE - sc->sc_hdrlen; ucaa.ucaa_opkthdrlen = sc->sc_hdrlen; ucaa.ucaa_device = dev; ucaa.ucaa_iface = iface; ucaa.ucaa_methods = &uftdi_methods; ucaa.ucaa_arg = sc; ucaa.ucaa_info = NULL; DPRINTF(("uftdi: in=%#x out=%#x isize=%#x osize=%#x\n", ucaa.ucaa_bulkin, ucaa.ucaa_bulkout, ucaa.ucaa_ibufsize, ucaa.ucaa_obufsize)); sc->sc_subdev = config_found(self, &ucaa, ucomprint, CFARGS(.submatch = ucomsubmatch)); usbd_add_drv_event(USB_EVENT_DRIVER_ATTACH, sc->sc_udev, sc->sc_dev); if (!pmf_device_register(self, NULL, NULL)) aprint_error_dev(self, "couldn't establish power handler\n"); return; bad: DPRINTF(("uftdi_attach: ATTACH ERROR\n")); sc->sc_dying = true; return; } static void uftdi_childdet(device_t self, device_t child) { struct uftdi_softc *sc = device_private(self); KASSERT(child == sc->sc_subdev); sc->sc_subdev = NULL; } static int uftdi_detach(device_t self, int flags) { struct uftdi_softc *sc = device_private(self); int rv = 0; DPRINTF(("uftdi_detach: sc=%p flags=%d\n", sc, flags)); sc->sc_dying = true; if (sc->sc_subdev != NULL) { rv = config_detach(sc->sc_subdev, flags); sc->sc_subdev = NULL; } usbd_add_drv_event(USB_EVENT_DRIVER_DETACH, sc->sc_udev, sc->sc_dev); return rv; } static int uftdi_open(void *vsc, int portno) { struct uftdi_softc *sc = vsc; usb_device_request_t req; usbd_status err; struct termios t; DPRINTF(("uftdi_open: sc=%p\n", sc)); if (sc->sc_dying) return EIO; /* Perform a full reset on the device */ req.bmRequestType = UT_WRITE_VENDOR_DEVICE; req.bRequest = FTDI_SIO_RESET; USETW(req.wValue, FTDI_SIO_RESET_SIO); USETW(req.wIndex, portno); USETW(req.wLength, 0); err = usbd_do_request(sc->sc_udev, &req, NULL); if (err) return EIO; /* Set 9600 baud, 2 stop bits, no parity, 8 bits */ t.c_ospeed = 9600; t.c_cflag = CSTOPB | CS8; (void)uftdi_param(sc, portno, &t); /* Turn on RTS/CTS flow control */ req.bmRequestType = UT_WRITE_VENDOR_DEVICE; req.bRequest = FTDI_SIO_SET_FLOW_CTRL; USETW(req.wValue, 0); USETW2(req.wIndex, FTDI_SIO_RTS_CTS_HS, portno); USETW(req.wLength, 0); err = usbd_do_request(sc->sc_udev, &req, NULL); if (err) return EIO; return 0; } static void uftdi_read(void *vsc, int portno, u_char **ptr, uint32_t *count) { struct uftdi_softc *sc = vsc; u_char msr, lsr; DPRINTFN(15,("uftdi_read: sc=%p, port=%d count=%d\n", sc, portno, *count)); msr = FTDI_GET_MSR(*ptr); lsr = FTDI_GET_LSR(*ptr); #ifdef UFTDI_DEBUG if (*count != 2) DPRINTFN(10,("uftdi_read: sc=%p, port=%d count=%d data[0]=" "0x%02x\n", sc, portno, *count, (*ptr)[2])); #endif if (sc->sc_msr != msr || (sc->sc_lsr & FTDI_LSR_MASK) != (lsr & FTDI_LSR_MASK)) { DPRINTF(("uftdi_read: status change msr=0x%02x(0x%02x) " "lsr=0x%02x(0x%02x)\n", msr, sc->sc_msr, lsr, sc->sc_lsr)); sc->sc_msr = msr; sc->sc_lsr = lsr; ucom_status_change(device_private(sc->sc_subdev)); } /* Adjust buffer pointer to skip status prefix */ *ptr += 2; } static void uftdi_write(void *vsc, int portno, u_char *to, u_char *from, uint32_t *count) { struct uftdi_softc *sc = vsc; DPRINTFN(10,("uftdi_write: sc=%p, port=%d count=%u data[0]=0x%02x\n", vsc, portno, *count, from[0])); /* Make length tag and copy data */ if (sc->sc_hdrlen > 0) *to = FTDI_OUT_TAG(*count, portno); memcpy(to + sc->sc_hdrlen, from, *count); *count += sc->sc_hdrlen; } static void uftdi_set(void *vsc, int portno, int reg, int onoff) { struct uftdi_softc *sc = vsc; usb_device_request_t req; int ctl; DPRINTF(("uftdi_set: sc=%p, port=%d reg=%d onoff=%d\n", vsc, portno, reg, onoff)); if (sc->sc_dying) return; switch (reg) { case UCOM_SET_DTR: ctl = onoff ? FTDI_SIO_SET_DTR_HIGH : FTDI_SIO_SET_DTR_LOW; break; case UCOM_SET_RTS: ctl = onoff ? FTDI_SIO_SET_RTS_HIGH : FTDI_SIO_SET_RTS_LOW; break; case UCOM_SET_BREAK: uftdi_break(sc, portno, onoff); return; default: return; } req.bmRequestType = UT_WRITE_VENDOR_DEVICE; req.bRequest = FTDI_SIO_MODEM_CTRL; USETW(req.wValue, ctl); USETW(req.wIndex, portno); USETW(req.wLength, 0); DPRINTFN(2,("uftdi_set: reqtype=0x%02x req=0x%02x value=0x%04x " "index=0x%04x len=%d\n", req.bmRequestType, req.bRequest, UGETW(req.wValue), UGETW(req.wIndex), UGETW(req.wLength))); (void)usbd_do_request(sc->sc_udev, &req, NULL); } /* * Return true if the given speed is within operational tolerance of the target * speed. FTDI recommends that the hardware speed be within 3% of nominal. */ static inline bool uftdi_baud_within_tolerance(uint64_t speed, uint64_t target) { return ((speed >= (target * 100) / 103) && (speed <= (target * 100) / 97)); } static int uftdi_encode_baudrate(struct uftdi_softc *sc, int speed, int *rate, int *ratehi) { static const uint8_t encoded_fraction[8] = { 0, 3, 2, 4, 1, 5, 6, 7 }; static const uint8_t roundoff_232a[16] = { 0, 1, 0, 1, 0, -1, 2, 1, 0, -1, -2, -3, 4, 3, 2, 1, }; uint32_t clk, divisor, fastclk_flag, frac, hwspeed; /* * If this chip has the fast clock capability and the speed is within * range, use the 12MHz clock, otherwise the standard clock is 3MHz. */ if ((sc->sc_flags & FLAGS_BAUDCLK_12M) && speed >= 1200) { clk = 12000000; fastclk_flag = (1 << 17); } else { clk = 3000000; fastclk_flag = 0; } /* * Make sure the requested speed is reachable with the available clock * and a 14-bit divisor. */ if (speed < (clk >> 14) || speed > clk) return -1; /* * Calculate the divisor, initially yielding a fixed point number with a * 4-bit (1/16ths) fraction, then round it to the nearest fraction the * hardware can handle. When the integral part of the divisor is * greater than one, the fractional part is in 1/8ths of the base clock. * The FT8U232AM chips can handle only 0.125, 0.250, and 0.5 fractions. * Later chips can handle all 1/8th fractions. * * If the integral part of the divisor is 1, a special rule applies: the * fractional part can only be .0 or .5 (this is a limitation of the * hardware). We handle this by truncating the fraction rather than * rounding, because this only applies to the two fastest speeds the * chip can achieve and rounding doesn't matter, either you've asked for * that exact speed or you've asked for something the chip can't do. * * For the FT8U232AM chips, use a roundoff table to adjust the result * to the nearest 1/8th fraction that is supported by the hardware, * leaving a fixed-point number with a 3-bit fraction which exactly * represents the math the hardware divider will do. For later-series * chips that support all 8 fractional divisors, just round 16ths to * 8ths by adding 1 and dividing by 2. */ divisor = (clk << 4) / speed; if ((divisor & 0xf) == 1) divisor &= 0xfffffff8; else if (sc->sc_flags & FLAGS_ROUNDOFF_232A) divisor += roundoff_232a[divisor & 0x0f]; else divisor += 1; /* Rounds odd 16ths up to next 8th. */ divisor >>= 1; /* * Ensure the resulting hardware speed will be within operational * tolerance (within 3% of nominal). */ hwspeed = (clk << 3) / divisor; if (!uftdi_baud_within_tolerance(hwspeed, speed)) return -1; /* * Re-pack the divisor into hardware format. The lower 14-bits hold the * integral part, while the upper bits specify the fraction by indexing * a table of fractions within the hardware which is laid out as: * {0.0, 0.5, 0.25, 0.125, 0.325, 0.625, 0.725, 0.875} * The A-series chips only have the first four table entries; the * roundoff table logic above ensures that the fractional part for those * chips will be one of the first four values. * * When the divisor is 1 a special encoding applies: 1.0 is encoded as * 0.0, and 1.5 is encoded as 1.0. The rounding logic above has already * ensured that the fraction is either .0 or .5 if the integral is 1. */ frac = divisor & 0x07; divisor >>= 3; if (divisor == 1) { if (frac == 0) divisor = 0; /* 1.0 becomes 0.0 */ else frac = 0; /* 1.5 becomes 1.0 */ } divisor |= (encoded_fraction[frac] << 14) | fastclk_flag; *rate = (uint16_t)divisor; *ratehi = (uint16_t)(divisor >> 16); /* * If this chip requires the baud bits to be in the high byte of the * index word, move the bits up to that location. */ if (sc->sc_flags & FLAGS_BAUDBITS_HINDEX) *ratehi <<= 8; return 0; } static int uftdi_param(void *vsc, int portno, struct termios *t) { struct uftdi_softc *sc = vsc; usb_device_request_t req; usbd_status err; int rate, ratehi, rerr, data, flow; DPRINTF(("uftdi_param: sc=%p\n", sc)); if (sc->sc_dying) return EIO; req.bmRequestType = UT_WRITE_VENDOR_DEVICE; req.bRequest = FTDI_SIO_SET_BITMODE; USETW(req.wValue, FTDI_BITMODE_RESET << 8 | 0x00); USETW(req.wIndex, portno); USETW(req.wLength, 0); err = usbd_do_request(sc->sc_udev, &req, NULL); if (err) return EIO; switch (sc->sc_type) { case UFTDI_TYPE_SIO: switch (t->c_ospeed) { case 300: rate = ftdi_sio_b300; break; case 600: rate = ftdi_sio_b600; break; case 1200: rate = ftdi_sio_b1200; break; case 2400: rate = ftdi_sio_b2400; break; case 4800: rate = ftdi_sio_b4800; break; case 9600: rate = ftdi_sio_b9600; break; case 19200: rate = ftdi_sio_b19200; break; case 38400: rate = ftdi_sio_b38400; break; case 57600: rate = ftdi_sio_b57600; break; case 115200: rate = ftdi_sio_b115200; break; default: return EINVAL; } ratehi = 0; break; case UFTDI_TYPE_8U232AM: rerr = uftdi_encode_baudrate(sc, t->c_ospeed, &rate, &ratehi); if (rerr != 0) return EINVAL; break; default: return EINVAL; } req.bmRequestType = UT_WRITE_VENDOR_DEVICE; req.bRequest = FTDI_SIO_SET_BAUD_RATE; USETW(req.wValue, rate); USETW(req.wIndex, portno | ratehi); USETW(req.wLength, 0); DPRINTFN(2,("uftdi_param: reqtype=0x%02x req=0x%02x value=0x%04x " "index=0x%04x len=%d\n", req.bmRequestType, req.bRequest, UGETW(req.wValue), UGETW(req.wIndex), UGETW(req.wLength))); err = usbd_do_request(sc->sc_udev, &req, NULL); if (err) return EIO; if (ISSET(t->c_cflag, CSTOPB)) data = FTDI_SIO_SET_DATA_STOP_BITS_2; else data = FTDI_SIO_SET_DATA_STOP_BITS_1; if (ISSET(t->c_cflag, PARENB)) { if (ISSET(t->c_cflag, PARODD)) data |= FTDI_SIO_SET_DATA_PARITY_ODD; else data |= FTDI_SIO_SET_DATA_PARITY_EVEN; } else data |= FTDI_SIO_SET_DATA_PARITY_NONE; switch (ISSET(t->c_cflag, CSIZE)) { case CS5: data |= FTDI_SIO_SET_DATA_BITS(5); break; case CS6: data |= FTDI_SIO_SET_DATA_BITS(6); break; case CS7: data |= FTDI_SIO_SET_DATA_BITS(7); break; case CS8: data |= FTDI_SIO_SET_DATA_BITS(8); break; } sc->last_lcr = data; req.bmRequestType = UT_WRITE_VENDOR_DEVICE; req.bRequest = FTDI_SIO_SET_DATA; USETW(req.wValue, data); USETW(req.wIndex, portno); USETW(req.wLength, 0); DPRINTFN(2,("uftdi_param: reqtype=0x%02x req=0x%02x value=0x%04x " "index=0x%04x len=%d\n", req.bmRequestType, req.bRequest, UGETW(req.wValue), UGETW(req.wIndex), UGETW(req.wLength))); err = usbd_do_request(sc->sc_udev, &req, NULL); if (err) return EIO; if (ISSET(t->c_cflag, CRTSCTS)) { flow = FTDI_SIO_RTS_CTS_HS; USETW(req.wValue, 0); } else if (ISSET(t->c_iflag, IXON) && ISSET(t->c_iflag, IXOFF)) { flow = FTDI_SIO_XON_XOFF_HS; USETW2(req.wValue, t->c_cc[VSTOP], t->c_cc[VSTART]); } else { flow = FTDI_SIO_DISABLE_FLOW_CTRL; USETW(req.wValue, 0); } req.bmRequestType = UT_WRITE_VENDOR_DEVICE; req.bRequest = FTDI_SIO_SET_FLOW_CTRL; USETW2(req.wIndex, flow, portno); USETW(req.wLength, 0); err = usbd_do_request(sc->sc_udev, &req, NULL); if (err) return EIO; return 0; } static void uftdi_get_status(void *vsc, int portno, u_char *lsr, u_char *msr) { struct uftdi_softc *sc = vsc; DPRINTF(("uftdi_status: msr=0x%02x lsr=0x%02x\n", sc->sc_msr, sc->sc_lsr)); if (sc->sc_dying) return; *msr = sc->sc_msr; *lsr = sc->sc_lsr; } static void uftdi_break(void *vsc, int portno, int onoff) { struct uftdi_softc *sc = vsc; usb_device_request_t req; int data; DPRINTF(("uftdi_break: sc=%p, port=%d onoff=%d\n", vsc, portno, onoff)); if (onoff) { data = sc->last_lcr | FTDI_SIO_SET_BREAK; } else { data = sc->last_lcr; } req.bmRequestType = UT_WRITE_VENDOR_DEVICE; req.bRequest = FTDI_SIO_SET_DATA; USETW(req.wValue, data); USETW(req.wIndex, portno); USETW(req.wLength, 0); (void)usbd_do_request(sc->sc_udev, &req, NULL); } |
155 150 157 145 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 | /* $NetBSD: kern_module_hook.c,v 1.4 2019/12/13 08:02:53 skrll Exp $ */ /*- * Copyright (c) 2019 The NetBSD Foundation, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ /* * Kernel module support. */ #include <sys/cdefs.h> __KERNEL_RCSID(0, "$NetBSD: kern_module_hook.c,v 1.4 2019/12/13 08:02:53 skrll Exp $"); #include <sys/param.h> #include <sys/atomic.h> #include <sys/condvar.h> #include <sys/module_hook.h> #include <sys/mutex.h> #include <sys/pserialize.h> #include <uvm/uvm_extern.h> /* Locking/synchronization stuff for module hooks */ static struct { kmutex_t mtx; kcondvar_t cv; pserialize_t psz; } module_hook __cacheline_aligned; /* * We use pserialize_perform() to issue a memory barrier on the current * CPU and on all other CPUs so that all prior memory operations on the * current CPU globally happen before all subsequent memory operations * on the current CPU, as perceived by any other CPU. * * pserialize_perform() might be rather heavy-weight here, but it only * happens during module loading, and it allows MODULE_HOOK_CALL() to * work without any other memory barriers. */ void module_hook_set(bool *hooked, struct localcount *lc) { KASSERT(kernconfig_is_held()); KASSERT(!*hooked); localcount_init(lc); /* Wait until setup has been witnessed by all CPUs. */ pserialize_perform(module_hook.psz); /* Let others use it */ atomic_store_relaxed(hooked, true); } void module_hook_unset(bool *hooked, struct localcount *lc) { KASSERT(kernconfig_is_held()); KASSERT(*hooked); /* Get exclusive with pserialize and localcount. */ mutex_enter(&module_hook.mtx); /* Prevent new calls to module_hook_tryenter(). */ atomic_store_relaxed(hooked, false); /* Wait for existing calls to module_hook_tryenter(). */ pserialize_perform(module_hook.psz); /* Wait for module_hook_exit. */ localcount_drain(lc, &module_hook.cv, &module_hook.mtx); /* All done! */ mutex_exit(&module_hook.mtx); localcount_fini(lc); } bool module_hook_tryenter(bool *hooked, struct localcount *lc) { bool call_hook; int s; s = pserialize_read_enter(); call_hook = atomic_load_relaxed(hooked); if (call_hook) localcount_acquire(lc); pserialize_read_exit(s); return call_hook; } void module_hook_exit(struct localcount *lc) { localcount_release(lc, &module_hook.cv, &module_hook.mtx); } void module_hook_init(void) { mutex_init(&module_hook.mtx, MUTEX_DEFAULT, IPL_NONE); cv_init(&module_hook.cv, "mod_hook"); module_hook.psz = pserialize_create(); } |
8 8 7 6 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 | /* $NetBSD: bt_proto.c,v 1.16 2016/01/21 15:41:30 riastradh Exp $ */ /*- * Copyright (c) 2005 Iain Hibbert. * Copyright (c) 2006 Itronix Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of Itronix Inc. may not be used to endorse * or promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY ITRONIX INC. ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL ITRONIX INC. BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include <sys/cdefs.h> __KERNEL_RCSID(0, "$NetBSD: bt_proto.c,v 1.16 2016/01/21 15:41:30 riastradh Exp $"); #include <sys/param.h> #include <sys/domain.h> #include <sys/kernel.h> #include <sys/protosw.h> #include <sys/socket.h> #include <sys/systm.h> #include <net/route.h> #include <netbt/bluetooth.h> #include <netbt/hci.h> #include <netbt/l2cap.h> #include <netbt/rfcomm.h> #include <netbt/sco.h> DOMAIN_DEFINE(btdomain); /* forward declare and add to link set */ static void bt_init(void); PR_WRAP_CTLOUTPUT(hci_ctloutput) PR_WRAP_CTLOUTPUT(sco_ctloutput) PR_WRAP_CTLOUTPUT(l2cap_ctloutput) PR_WRAP_CTLOUTPUT(rfcomm_ctloutput) #define hci_ctloutput hci_ctloutput_wrapper #define sco_ctloutput sco_ctloutput_wrapper #define l2cap_ctloutput l2cap_ctloutput_wrapper #define rfcomm_ctloutput rfcomm_ctloutput_wrapper static const struct protosw btsw[] = { { /* raw HCI commands */ .pr_type = SOCK_RAW, .pr_domain = &btdomain, .pr_protocol = BTPROTO_HCI, .pr_flags = (PR_ADDR | PR_ATOMIC), .pr_init = hci_init, .pr_ctloutput = hci_ctloutput, .pr_usrreqs = &hci_usrreqs, }, { /* HCI SCO data (audio) */ .pr_type = SOCK_SEQPACKET, .pr_domain = &btdomain, .pr_protocol = BTPROTO_SCO, .pr_flags = (PR_CONNREQUIRED | PR_ATOMIC | PR_LISTEN), .pr_ctloutput = sco_ctloutput, .pr_usrreqs = &sco_usrreqs, }, { /* L2CAP Connection Oriented */ .pr_type = SOCK_SEQPACKET, .pr_domain = &btdomain, .pr_protocol = BTPROTO_L2CAP, .pr_flags = (PR_CONNREQUIRED | PR_ATOMIC | PR_LISTEN), .pr_ctloutput = l2cap_ctloutput, .pr_usrreqs = &l2cap_usrreqs, .pr_init = l2cap_init, }, { /* RFCOMM */ .pr_type = SOCK_STREAM, .pr_domain = &btdomain, .pr_protocol = BTPROTO_RFCOMM, .pr_flags = (PR_CONNREQUIRED | PR_LISTEN | PR_WANTRCVD), .pr_ctloutput = rfcomm_ctloutput, .pr_usrreqs = &rfcomm_usrreqs, .pr_init = rfcomm_init, }, }; struct domain btdomain = { .dom_family = AF_BLUETOOTH, .dom_name = "bluetooth", .dom_init = bt_init, .dom_protosw = btsw, .dom_protoswNPROTOSW = &btsw[__arraycount(btsw)], }; kmutex_t *bt_lock; static void bt_init(void) { bt_lock = mutex_obj_alloc(MUTEX_DEFAULT, IPL_NONE); } |
2 2 2 2 2 2 2 2 2 2 6 6 5 4 3 3 3 1 3 2 2 2 2 3 2 2 2 2 2 2 2 2 2 2 2 2 4 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 | /* $NetBSD: wskbdutil.c,v 1.19 2017/11/03 19:20:27 maya Exp $ */ /*- * Copyright (c) 1997 The NetBSD Foundation, Inc. * All rights reserved. * * This code is derived from software contributed to The NetBSD Foundation * by Juergen Hannken-Illjes. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include <sys/cdefs.h> __KERNEL_RCSID(0, "$NetBSD: wskbdutil.c,v 1.19 2017/11/03 19:20:27 maya Exp $"); #include <sys/param.h> #include <sys/errno.h> #include <sys/systm.h> #include <sys/malloc.h> #include <dev/wscons/wsksymdef.h> #include <dev/wscons/wsksymvar.h> static struct compose_tab_s { keysym_t elem[2]; keysym_t result; } compose_tab[] = { { { KS_plus, KS_plus }, KS_numbersign }, { { KS_a, KS_a }, KS_at }, { { KS_parenleft, KS_parenleft }, KS_bracketleft }, { { KS_slash, KS_slash }, KS_backslash }, { { KS_parenright, KS_parenright }, KS_bracketright }, { { KS_parenleft, KS_minus }, KS_braceleft }, { { KS_slash, KS_minus }, KS_bar }, { { KS_parenright, KS_minus }, KS_braceright }, { { KS_exclam, KS_exclam }, KS_exclamdown }, { { KS_c, KS_slash }, KS_cent }, { { KS_l, KS_minus }, KS_sterling }, { { KS_y, KS_minus }, KS_yen }, { { KS_s, KS_o }, KS_section }, { { KS_x, KS_o }, KS_currency }, { { KS_c, KS_o }, KS_copyright }, { { KS_less, KS_less }, KS_guillemotleft }, { { KS_greater, KS_greater }, KS_guillemotright }, { { KS_question, KS_question }, KS_questiondown }, { { KS_dead_acute, KS_space }, KS_acute }, { { KS_dead_grave, KS_space }, KS_grave }, { { KS_dead_tilde, KS_space }, KS_asciitilde }, { { KS_dead_circumflex, KS_space }, KS_asciicircum }, { { KS_dead_circumflex, KS_A }, KS_Acircumflex }, { { KS_dead_diaeresis, KS_A }, KS_Adiaeresis }, { { KS_dead_grave, KS_A }, KS_Agrave }, { { KS_dead_abovering, KS_A }, KS_Aring }, { { KS_dead_tilde, KS_A }, KS_Atilde }, { { KS_dead_cedilla, KS_C }, KS_Ccedilla }, { { KS_dead_acute, KS_E }, KS_Eacute }, { { KS_dead_circumflex, KS_E }, KS_Ecircumflex }, { { KS_dead_diaeresis, KS_E }, KS_Ediaeresis }, { { KS_dead_grave, KS_E }, KS_Egrave }, { { KS_dead_acute, KS_I }, KS_Iacute }, { { KS_dead_circumflex, KS_I }, KS_Icircumflex }, { { KS_dead_diaeresis, KS_I }, KS_Idiaeresis }, { { KS_dead_grave, KS_I }, KS_Igrave }, { { KS_dead_tilde, KS_N }, KS_Ntilde }, { { KS_dead_acute, KS_O }, KS_Oacute }, { { KS_dead_circumflex, KS_O }, KS_Ocircumflex }, { { KS_dead_diaeresis, KS_O }, KS_Odiaeresis }, { { KS_dead_grave, KS_O }, KS_Ograve }, { { KS_dead_tilde, KS_O }, KS_Otilde }, { { KS_dead_acute, KS_U }, KS_Uacute }, { { KS_dead_circumflex, KS_U }, KS_Ucircumflex }, { { KS_dead_diaeresis, KS_U }, KS_Udiaeresis }, { { KS_dead_grave, KS_U }, KS_Ugrave }, { { KS_dead_acute, KS_Y }, KS_Yacute }, { { KS_dead_acute, KS_a }, KS_aacute }, { { KS_dead_circumflex, KS_a }, KS_acircumflex }, { { KS_dead_diaeresis, KS_a }, KS_adiaeresis }, { { KS_dead_grave, KS_a }, KS_agrave }, { { KS_dead_abovering, KS_a }, KS_aring }, { { KS_dead_tilde, KS_a }, KS_atilde }, { { KS_dead_cedilla, KS_c }, KS_ccedilla }, { { KS_dead_acute, KS_e }, KS_eacute }, { { KS_dead_circumflex, KS_e }, KS_ecircumflex }, { { KS_dead_diaeresis, KS_e }, KS_ediaeresis }, { { KS_dead_grave, KS_e }, KS_egrave }, { { KS_dead_acute, KS_i }, KS_iacute }, { { KS_dead_circumflex, KS_i }, KS_icircumflex }, { { KS_dead_diaeresis, KS_i }, KS_idiaeresis }, { { KS_dead_grave, KS_i }, KS_igrave }, { { KS_dead_tilde, KS_n }, KS_ntilde }, { { KS_dead_acute, KS_o }, KS_oacute }, { { KS_dead_circumflex, KS_o }, KS_ocircumflex }, { { KS_dead_diaeresis, KS_o }, KS_odiaeresis }, { { KS_dead_grave, KS_o }, KS_ograve }, { { KS_dead_tilde, KS_o }, KS_otilde }, { { KS_dead_acute, KS_u }, KS_uacute }, { { KS_dead_circumflex, KS_u }, KS_ucircumflex }, { { KS_dead_diaeresis, KS_u }, KS_udiaeresis }, { { KS_dead_grave, KS_u }, KS_ugrave }, { { KS_dead_acute, KS_y }, KS_yacute }, { { KS_dead_diaeresis, KS_y }, KS_ydiaeresis }, { { KS_quotedbl, KS_A }, KS_Adiaeresis }, { { KS_quotedbl, KS_E }, KS_Ediaeresis }, { { KS_quotedbl, KS_I }, KS_Idiaeresis }, { { KS_quotedbl, KS_O }, KS_Odiaeresis }, { { KS_quotedbl, KS_U }, KS_Udiaeresis }, { { KS_quotedbl, KS_a }, KS_adiaeresis }, { { KS_quotedbl, KS_e }, KS_ediaeresis }, { { KS_quotedbl, KS_i }, KS_idiaeresis }, { { KS_quotedbl, KS_o }, KS_odiaeresis }, { { KS_quotedbl, KS_u }, KS_udiaeresis }, { { KS_quotedbl, KS_y }, KS_ydiaeresis }, { { KS_acute, KS_A }, KS_Aacute }, { { KS_asciicircum, KS_A }, KS_Acircumflex }, { { KS_grave, KS_A }, KS_Agrave }, { { KS_asterisk, KS_A }, KS_Aring }, { { KS_asciitilde, KS_A }, KS_Atilde }, { { KS_cedilla, KS_C }, KS_Ccedilla }, { { KS_acute, KS_E }, KS_Eacute }, { { KS_asciicircum, KS_E }, KS_Ecircumflex }, { { KS_grave, KS_E }, KS_Egrave }, { { KS_acute, KS_I }, KS_Iacute }, { { KS_asciicircum, KS_I }, KS_Icircumflex }, { { KS_grave, KS_I }, KS_Igrave }, { { KS_asciitilde, KS_N }, KS_Ntilde }, { { KS_acute, KS_O }, KS_Oacute }, { { KS_asciicircum, KS_O }, KS_Ocircumflex }, { { KS_grave, KS_O }, KS_Ograve }, { { KS_asciitilde, KS_O }, KS_Otilde }, { { KS_acute, KS_U }, KS_Uacute }, { { KS_asciicircum, KS_U }, KS_Ucircumflex }, { { KS_grave, KS_U }, KS_Ugrave }, { { KS_acute, KS_Y }, KS_Yacute }, { { KS_acute, KS_a }, KS_aacute }, { { KS_asciicircum, KS_a }, KS_acircumflex }, { { KS_grave, KS_a }, KS_agrave }, { { KS_asterisk, KS_a }, KS_aring }, { { KS_asciitilde, KS_a }, KS_atilde }, { { KS_cedilla, KS_c }, KS_ccedilla }, { { KS_acute, KS_e }, KS_eacute }, { { KS_asciicircum, KS_e }, KS_ecircumflex }, { { KS_grave, KS_e }, KS_egrave }, { { KS_acute, KS_i }, KS_iacute }, { { KS_asciicircum, KS_i }, KS_icircumflex }, { { KS_grave, KS_i }, KS_igrave }, { { KS_asciitilde, KS_n }, KS_ntilde }, { { KS_acute, KS_o }, KS_oacute }, { { KS_asciicircum, KS_o }, KS_ocircumflex }, { { KS_grave, KS_o }, KS_ograve }, { { KS_asciitilde, KS_o }, KS_otilde }, { { KS_acute, KS_u }, KS_uacute }, { { KS_asciicircum, KS_u }, KS_ucircumflex }, { { KS_grave, KS_u }, KS_ugrave }, { { KS_acute, KS_y }, KS_yacute }, { { KS_dead_semi, KS_gr_A }, KS_gr_At }, { { KS_dead_semi, KS_gr_E }, KS_gr_Et }, { { KS_dead_semi, KS_gr_H }, KS_gr_Ht }, { { KS_dead_semi, KS_gr_I }, KS_gr_It }, { { KS_dead_semi, KS_gr_O }, KS_gr_Ot }, { { KS_dead_semi, KS_gr_Y }, KS_gr_Yt }, { { KS_dead_semi, KS_gr_V }, KS_gr_Vt }, { { KS_dead_colon, KS_gr_I }, KS_gr_Id }, { { KS_dead_colon, KS_gr_Y }, KS_gr_Yd }, { { KS_dead_semi, KS_gr_a }, KS_gr_at }, { { KS_dead_semi, KS_gr_e }, KS_gr_et }, { { KS_dead_semi, KS_gr_h }, KS_gr_ht }, { { KS_dead_semi, KS_gr_i }, KS_gr_it }, { { KS_dead_semi, KS_gr_o }, KS_gr_ot }, { { KS_dead_semi, KS_gr_y }, KS_gr_yt }, { { KS_dead_semi, KS_gr_v }, KS_gr_vt }, { { KS_dead_colon, KS_gr_i }, KS_gr_id }, { { KS_dead_colon, KS_gr_y }, KS_gr_yd }, /* Latin 2*/ { { KS_dead_acute, KS_S }, KS_Sacute }, { { KS_dead_acute, KS_Z }, KS_Zacute }, { { KS_dead_acute, KS_s }, KS_sacute }, { { KS_dead_acute, KS_z }, KS_zacute }, { { KS_dead_acute, KS_R }, KS_Racute }, { { KS_dead_acute, KS_A }, KS_Aacute }, { { KS_dead_acute, KS_L }, KS_Lacute }, { { KS_dead_acute, KS_C }, KS_Cacute }, { { KS_dead_acute, KS_E }, KS_Eacute }, { { KS_dead_acute, KS_I }, KS_Iacute }, { { KS_dead_acute, KS_N }, KS_Nacute }, { { KS_dead_acute, KS_O }, KS_Oacute }, { { KS_dead_acute, KS_U }, KS_Uacute }, { { KS_dead_acute, KS_Y }, KS_Yacute }, { { KS_dead_acute, KS_r }, KS_racute }, { { KS_dead_acute, KS_a }, KS_aacute }, { { KS_dead_acute, KS_l }, KS_lacute }, { { KS_dead_acute, KS_c }, KS_cacute }, { { KS_dead_acute, KS_e }, KS_eacute }, { { KS_dead_acute, KS_i }, KS_iacute }, { { KS_dead_acute, KS_n }, KS_nacute }, { { KS_dead_acute, KS_o }, KS_oacute }, { { KS_dead_acute, KS_u }, KS_uacute }, { { KS_dead_acute, KS_y }, KS_yacute }, { { KS_dead_breve, KS_A }, KS_Abreve }, { { KS_dead_breve, KS_a }, KS_abreve }, { { KS_dead_caron, KS_L }, KS_Lcaron }, { { KS_dead_caron, KS_S }, KS_Scaron }, { { KS_dead_caron, KS_T }, KS_Tcaron }, { { KS_dead_caron, KS_Z }, KS_Zcaron }, { { KS_dead_caron, KS_l }, KS_lcaron }, { { KS_dead_caron, KS_s }, KS_scaron }, { { KS_dead_caron, KS_t }, KS_tcaron }, { { KS_dead_caron, KS_z }, KS_zcaron }, { { KS_dead_caron, KS_C }, KS_Ccaron }, { { KS_dead_caron, KS_E }, KS_Ecaron }, { { KS_dead_caron, KS_D }, KS_Dcaron }, { { KS_dead_caron, KS_N }, KS_Ncaron }, { { KS_dead_caron, KS_R }, KS_Rcaron }, { { KS_dead_caron, KS_c }, KS_ccaron }, { { KS_dead_caron, KS_e }, KS_ecaron }, { { KS_dead_caron, KS_d }, KS_dcaron }, { { KS_dead_caron, KS_n }, KS_ncaron }, { { KS_dead_caron, KS_r }, KS_rcaron }, { { KS_dead_cedilla, KS_S }, KS_Scedilla }, { { KS_dead_cedilla, KS_s }, KS_scedilla }, { { KS_dead_cedilla, KS_C }, KS_Ccedilla }, { { KS_dead_cedilla, KS_T }, KS_Tcedilla }, { { KS_dead_cedilla, KS_c }, KS_ccedilla }, { { KS_dead_cedilla, KS_t }, KS_tcedilla }, { { KS_dead_circumflex, KS_A }, KS_Acircumflex }, { { KS_dead_circumflex, KS_I }, KS_Icircumflex }, { { KS_dead_circumflex, KS_O }, KS_Ocircumflex }, { { KS_dead_circumflex, KS_a }, KS_acircumflex }, { { KS_dead_circumflex, KS_i }, KS_icircumflex }, { { KS_dead_circumflex, KS_o }, KS_ocircumflex }, { { KS_dead_diaeresis, KS_A }, KS_Adiaeresis }, { { KS_dead_diaeresis, KS_E }, KS_Ediaeresis }, { { KS_dead_diaeresis, KS_O }, KS_Odiaeresis }, { { KS_dead_diaeresis, KS_U }, KS_Udiaeresis }, { { KS_dead_diaeresis, KS_a }, KS_adiaeresis }, { { KS_dead_diaeresis, KS_e }, KS_ediaeresis }, { { KS_dead_diaeresis, KS_o }, KS_odiaeresis }, { { KS_dead_diaeresis, KS_u }, KS_udiaeresis }, { { KS_dead_dotaccent, KS_Z }, KS_Zabovedot }, { { KS_dead_dotaccent, KS_z }, KS_zabovedot }, { { KS_dead_hungarumlaut, KS_O }, KS_Odoubleacute }, { { KS_dead_hungarumlaut, KS_U }, KS_Udoubleacute }, { { KS_dead_hungarumlaut, KS_o }, KS_odoubleacute }, { { KS_dead_hungarumlaut, KS_u }, KS_udoubleacute }, { { KS_dead_ogonek, KS_A }, KS_Aogonek }, { { KS_dead_ogonek, KS_a }, KS_aogonek }, { { KS_dead_ogonek, KS_E }, KS_Eogonek }, { { KS_dead_ogonek, KS_e }, KS_eogonek }, { { KS_dead_abovering, KS_U }, KS_Uabovering }, { { KS_dead_abovering, KS_u }, KS_uabovering }, { { KS_dead_slash, KS_L }, KS_Lstroke }, { { KS_dead_slash, KS_l }, KS_lstroke } }; #define COMPOSE_SIZE __arraycount(compose_tab) static int compose_tab_inorder = 0; static inline int compose_tab_cmp(struct compose_tab_s *, struct compose_tab_s *); static keysym_t ksym_upcase(keysym_t); static void fillmapentry(const keysym_t *, int, struct wscons_keymap *); static inline int compose_tab_cmp(struct compose_tab_s *i, struct compose_tab_s *j) { if (i->elem[0] == j->elem[0]) return(i->elem[1] - j->elem[1]); else return(i->elem[0] - j->elem[0]); } keysym_t wskbd_compose_value(keysym_t *compose_buf) { int i, j, r; struct compose_tab_s v; if (! compose_tab_inorder) { /* Insertion sort. */ for (i = 1; i < COMPOSE_SIZE; i++) { v = compose_tab[i]; /* find correct slot, moving others up */ for (j = i; --j >= 0 && compose_tab_cmp(& v, & compose_tab[j]) < 0; ) compose_tab[j + 1] = compose_tab[j]; compose_tab[j + 1] = v; } compose_tab_inorder = 1; } for (j = 0, i = COMPOSE_SIZE; i != 0; i /= 2) { if (compose_tab[j + i/2].elem[0] == compose_buf[0]) { if (compose_tab[j + i/2].elem[1] == compose_buf[1]) return(compose_tab[j + i/2].result); r = compose_tab[j + i/2].elem[1] < compose_buf[1]; } else r = compose_tab[j + i/2].elem[0] < compose_buf[0]; if (r) { j += i/2 + 1; i--; } } return(KS_voidSymbol); } static const u_char latin1_to_upper[256] = { /* 0 8 1 9 2 a 3 b 4 c 5 d 6 e 7 f */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 1 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 1 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 2 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 2 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 3 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 3 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 4 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 4 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 5 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 5 */ 0x00, 'A', 'B', 'C', 'D', 'E', 'F', 'G', /* 6 */ 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', /* 6 */ 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', /* 7 */ 'X', 'Y', 'Z', 0x00, 0x00, 0x00, 0x00, 0x00, /* 7 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 8 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 8 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 9 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 9 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* a */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* a */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* b */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* b */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* c */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* c */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* d */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* d */ 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, /* e */ 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf, /* e */ 0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0x00, /* f */ 0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0x00, /* f */ }; static keysym_t ksym_upcase(keysym_t ksym) { if (ksym >= KS_f1 && ksym <= KS_f20) return(KS_F1 - KS_f1 + ksym); if (KS_GROUP(ksym) == KS_GROUP_Plain && ksym <= 0xff && latin1_to_upper[ksym] != 0x00) return(latin1_to_upper[ksym]); return(ksym); } static void fillmapentry(const keysym_t *kp, int len, struct wscons_keymap *mapentry) { switch (len) { case 0: mapentry->group1[0] = KS_voidSymbol; mapentry->group1[1] = KS_voidSymbol; mapentry->group2[0] = KS_voidSymbol; mapentry->group2[1] = KS_voidSymbol; break; case 1: mapentry->group1[0] = kp[0]; mapentry->group1[1] = ksym_upcase(kp[0]); mapentry->group2[0] = mapentry->group1[0]; mapentry->group2[1] = mapentry->group1[1]; break; case 2: mapentry->group1[0] = kp[0]; mapentry->group1[1] = kp[1]; mapentry->group2[0] = mapentry->group1[0]; mapentry->group2[1] = mapentry->group1[1]; break; case 3: mapentry->group1[0] = kp[0]; mapentry->group1[1] = kp[1]; mapentry->group2[0] = kp[2]; mapentry->group2[1] = ksym_upcase(kp[2]); break; case 4: mapentry->group1[0] = kp[0]; mapentry->group1[1] = kp[1]; mapentry->group2[0] = kp[2]; mapentry->group2[1] = kp[3]; break; } } void wskbd_get_mapentry(const struct wskbd_mapdata *mapdata, int kc, struct wscons_keymap *mapentry) { kbd_t cur; const keysym_t *kp; const struct wscons_keydesc *mp; int l; mapentry->command = KS_voidSymbol; mapentry->group1[0] = KS_voidSymbol; mapentry->group1[1] = KS_voidSymbol; mapentry->group2[0] = KS_voidSymbol; mapentry->group2[1] = KS_voidSymbol; for (cur = mapdata->layout & ~KB_HANDLEDBYWSKBD; cur != 0; ) { mp = mapdata->keydesc; while (mp->map_size > 0) { if (mp->name == cur) break; mp++; } /* If map not found, return */ if (mp->map_size <= 0) return; for (kp = mp->map; kp < mp->map + mp->map_size; kp++) if (KS_GROUP(*kp) == KS_GROUP_Keycode && KS_VALUE(*kp) == kc) { /* First skip keycode and possible command */ kp++; if (KS_GROUP(*kp) == KS_GROUP_Command || *kp == KS_Cmd || *kp == KS_Cmd1 || *kp == KS_Cmd2) mapentry->command = *kp++; for (l = 0; kp + l < mp->map + mp->map_size; l++) if (KS_GROUP(kp[l]) == KS_GROUP_Keycode) break; if (l > 4) panic("wskbd_get_mapentry: %d(%d): bad entry", mp->name, *kp); fillmapentry(kp, l, mapentry); return; } cur = mp->base; } } void wskbd_init_keymap(int newlen, struct wscons_keymap **map, int *maplen) { int i; if (newlen != *maplen) { if (*maplen > 0) free(*map, M_TEMP); *maplen = newlen; *map = malloc(newlen*sizeof(struct wscons_keymap), M_TEMP, M_WAITOK); } for (i = 0; i < *maplen; i++) { (*map)[i].command = KS_voidSymbol; (*map)[i].group1[0] = KS_voidSymbol; (*map)[i].group1[1] = KS_voidSymbol; (*map)[i].group2[0] = KS_voidSymbol; (*map)[i].group2[1] = KS_voidSymbol; } } int wskbd_load_keymap(const struct wskbd_mapdata *mapdata, struct wscons_keymap **map, int *maplen) { int i, s, kc, stack_ptr; const keysym_t *kp; const struct wscons_keydesc *mp, *stack[10]; kbd_t cur; for (cur = mapdata->layout & ~KB_HANDLEDBYWSKBD, stack_ptr = 0; cur != 0; stack_ptr++) { mp = mapdata->keydesc; while (mp->map_size > 0) { if (cur == 0 || mp->name == cur) { break; } mp++; } if (stack_ptr == __arraycount(stack)) panic("wskbd_load_keymap: %d: recursion too deep", mapdata->layout); if (mp->map_size <= 0) return(EINVAL); stack[stack_ptr] = mp; cur = mp->base; } for (i = 0, s = stack_ptr - 1; s >= 0; s--) { mp = stack[s]; for (kp = mp->map; kp < mp->map + mp->map_size; kp++) if (KS_GROUP(*kp) == KS_GROUP_Keycode && KS_VALUE(*kp) > i) i = KS_VALUE(*kp); } wskbd_init_keymap(i + 1, map, maplen); for (s = stack_ptr - 1; s >= 0; s--) { mp = stack[s]; for (kp = mp->map; kp < mp->map + mp->map_size; ) { if (KS_GROUP(*kp) != KS_GROUP_Keycode) panic("wskbd_load_keymap: %d(%d): bad entry", mp->name, *kp); kc = KS_VALUE(*kp); kp++; if (KS_GROUP(*kp) == KS_GROUP_Command || *kp == KS_Cmd || *kp == KS_Cmd1 || *kp == KS_Cmd2) { (*map)[kc].command = *kp; kp++; } for (i = 0; kp + i < mp->map + mp->map_size; i++) if (KS_GROUP(kp[i]) == KS_GROUP_Keycode) break; if (i > 4) panic("wskbd_load_keymap: %d(%d): bad entry", mp->name, *kp); fillmapentry(kp, i, &(*map)[kc]); kp += i; } } return(0); } |
1 1 1 1 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 | /* $NetBSD: pmap_pvt.c,v 1.15 2022/05/08 22:03:02 rin Exp $ */ /*- * Copyright (c) 2014, 2020 The NetBSD Foundation, Inc. * All rights reserved. * * This code is derived from software contributed to The NetBSD Foundation * by Taylor R. Campbell. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include <sys/cdefs.h> __RCSID("$NetBSD: pmap_pvt.c,v 1.15 2022/05/08 22:03:02 rin Exp $"); #include <sys/param.h> #include <sys/atomic.h> #include <sys/kmem.h> #include <sys/pserialize.h> #include <uvm/uvm.h> #include <uvm/pmap/pmap_pvt.h> #if !defined(PMAP_PV_TRACK_ONLY_STUBS) /* * unmanaged pv-tracked ranges * * This is a linear list for now because the only user are the DRM * graphics drivers, with a single tracked range per device, for the * graphics aperture, so there are expected to be few of them. * * This is used only after the VM system is initialized well enough * that we can use kmem_alloc. */ struct pv_track { paddr_t pvt_start; psize_t pvt_size; struct pv_track *pvt_next; struct pmap_page pvt_pages[]; }; static struct { kmutex_t lock; pserialize_t psz; struct pv_track *list; } pv_unmanaged __cacheline_aligned; void pmap_pv_init(void) { mutex_init(&pv_unmanaged.lock, MUTEX_DEFAULT, IPL_NONE); pv_unmanaged.psz = pserialize_create(); pv_unmanaged.list = NULL; } void pmap_pv_track(paddr_t start, psize_t size) { struct pv_track *pvt; size_t npages; KASSERT(start == trunc_page(start)); KASSERT(size == trunc_page(size)); /* We may sleep for allocation. */ ASSERT_SLEEPABLE(); npages = size >> PAGE_SHIFT; pvt = kmem_zalloc(offsetof(struct pv_track, pvt_pages[npages]), KM_SLEEP); pvt->pvt_start = start; pvt->pvt_size = size; #ifdef PMAP_PAGE_INIT for (size_t i = 0; i < npages; i++) PMAP_PAGE_INIT(&pvt->pvt_pages[i]); #endif mutex_enter(&pv_unmanaged.lock); pvt->pvt_next = pv_unmanaged.list; atomic_store_release(&pv_unmanaged.list, pvt); mutex_exit(&pv_unmanaged.lock); } void pmap_pv_untrack(paddr_t start, psize_t size) { struct pv_track **pvtp, *pvt; size_t npages; KASSERT(start == trunc_page(start)); KASSERT(size == trunc_page(size)); /* We may sleep for pserialize_perform. */ ASSERT_SLEEPABLE(); mutex_enter(&pv_unmanaged.lock); for (pvtp = &pv_unmanaged.list; (pvt = *pvtp) != NULL; pvtp = &pvt->pvt_next) { if (pvt->pvt_start != start) continue; if (pvt->pvt_size != size) panic("pmap_pv_untrack: pv-tracking at 0x%"PRIxPADDR ": 0x%"PRIxPSIZE" bytes, not 0x%"PRIxPSIZE" bytes", pvt->pvt_start, pvt->pvt_size, size); /* * Remove from list. Readers can safely see the old * and new states of the list. */ atomic_store_relaxed(pvtp, pvt->pvt_next); /* Wait for readers who can see the old state to finish. */ pserialize_perform(pv_unmanaged.psz); /* * We now have exclusive access to pvt and can destroy * it. Poison it to catch bugs. */ explicit_memset(&pvt->pvt_next, 0x1a, sizeof pvt->pvt_next); goto out; } panic("pmap_pv_untrack: pages not pv-tracked at 0x%"PRIxPADDR " (0x%"PRIxPSIZE" bytes)", start, size); out: mutex_exit(&pv_unmanaged.lock); npages = size >> PAGE_SHIFT; kmem_free(pvt, offsetof(struct pv_track, pvt_pages[npages])); } struct pmap_page * pmap_pv_tracked(paddr_t pa) { struct pv_track *pvt; size_t pgno; int s; KASSERT(pa == trunc_page(pa)); s = pserialize_read_enter(); for (pvt = atomic_load_consume(&pv_unmanaged.list); pvt != NULL; pvt = pvt->pvt_next) { if ((pvt->pvt_start <= pa) && ((pa - pvt->pvt_start) < pvt->pvt_size)) break; } pserialize_read_exit(s); if (pvt == NULL) return NULL; KASSERT(pvt->pvt_start <= pa); KASSERT((pa - pvt->pvt_start) < pvt->pvt_size); pgno = (pa - pvt->pvt_start) >> PAGE_SHIFT; return &pvt->pvt_pages[pgno]; } #else /* PMAP_PV_TRACK_ONLY_STUBS */ /* * Provide empty stubs just for MODULAR kernels. */ void pmap_pv_init(void) { } struct pmap_page * pmap_pv_tracked(paddr_t pa) { return NULL; } #if notdef /* * pmap_pv_{,un}track() are intentionally commented out. If modules * call these functions, the result should be an inconsistent state. * * Such modules require real PV-tracking support. Let us make the * two symbols undefined, and prevent these modules from loaded. */ void pmap_pv_track(paddr_t start, psize_t size) { panic("PV-tracking not supported"); } void pmap_pv_untrack(paddr_t start, psize_t size) { panic("PV-tracking not supported"); } #endif /* notdef */ #endif /* PMAP_PV_TRACK_ONLY_STUBS */ |
8 8 8 8 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 | /* $NetBSD: chacha_sse2.c,v 1.2 2020/07/27 20:48:18 riastradh Exp $ */ /*- * Copyright (c) 2020 The NetBSD Foundation, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include <sys/types.h> #include <sys/endian.h> #include "immintrin.h" #include "chacha_sse2.h" static inline __m128i rol32(__m128i x, uint8_t n) { return _mm_slli_epi32(x, n) | _mm_srli_epi32(x, 32 - n); } static inline void chacha_permute(__m128i *p0, __m128i *p1, __m128i *p2, __m128i *p3, unsigned nr) { __m128i r0, r1, r2, r3; __m128i c0, c1, c2, c3; r0 = *p0; r1 = *p1; r2 = *p2; r3 = *p3; for (; nr > 0; nr -= 2) { r0 = _mm_add_epi32(r0, r1); r3 ^= r0; r3 = rol32(r3, 16); r2 = _mm_add_epi32(r2, r3); r1 ^= r2; r1 = rol32(r1, 12); r0 = _mm_add_epi32(r0, r1); r3 ^= r0; r3 = rol32(r3, 8); r2 = _mm_add_epi32(r2, r3); r1 ^= r2; r1 = rol32(r1, 7); c0 = r0; c1 = _mm_shuffle_epi32(r1, 0x39); c2 = _mm_shuffle_epi32(r2, 0x4e); c3 = _mm_shuffle_epi32(r3, 0x93); c0 = _mm_add_epi32(c0, c1); c3 ^= c0; c3 = rol32(c3, 16); c2 = _mm_add_epi32(c2, c3); c1 ^= c2; c1 = rol32(c1, 12); c0 = _mm_add_epi32(c0, c1); c3 ^= c0; c3 = rol32(c3, 8); c2 = _mm_add_epi32(c2, c3); c1 ^= c2; c1 = rol32(c1, 7); r0 = c0; r1 = _mm_shuffle_epi32(c1, 0x93); r2 = _mm_shuffle_epi32(c2, 0x4e); r3 = _mm_shuffle_epi32(c3, 0x39); } *p0 = r0; *p1 = r1; *p2 = r2; *p3 = r3; } void chacha_core_sse2(uint8_t out[restrict static 64], const uint8_t in[static 16], const uint8_t k[static 32], const uint8_t c[static 16], unsigned nr) { __m128i in0, in1, in2, in3; __m128i r0, r1, r2, r3; r0 = in0 = _mm_loadu_si128((const __m128i *)c); r1 = in1 = _mm_loadu_si128((const __m128i *)k); r2 = in2 = _mm_loadu_si128((const __m128i *)k + 1); r3 = in3 = _mm_loadu_si128((const __m128i *)in); chacha_permute(&r0, &r1, &r2, &r3, nr); _mm_storeu_si128((__m128i *)out + 0, _mm_add_epi32(r0, in0)); _mm_storeu_si128((__m128i *)out + 1, _mm_add_epi32(r1, in1)); _mm_storeu_si128((__m128i *)out + 2, _mm_add_epi32(r2, in2)); _mm_storeu_si128((__m128i *)out + 3, _mm_add_epi32(r3, in3)); } void hchacha_sse2(uint8_t out[restrict static 32], const uint8_t in[static 16], const uint8_t k[static 32], const uint8_t c[static 16], unsigned nr) { __m128i r0, r1, r2, r3; r0 = _mm_loadu_si128((const __m128i *)c); r1 = _mm_loadu_si128((const __m128i *)k); r2 = _mm_loadu_si128((const __m128i *)k + 1); r3 = _mm_loadu_si128((const __m128i *)in); chacha_permute(&r0, &r1, &r2, &r3, nr); _mm_storeu_si128((__m128i *)out + 0, r0); _mm_storeu_si128((__m128i *)out + 1, r3); } #define CHACHA_QUARTERROUND(a, b, c, d) do \ { \ (a) = _mm_add_epi32((a), (b)); (d) ^= a; (d) = rol32((d), 16); \ (c) = _mm_add_epi32((c), (d)); (b) ^= c; (b) = rol32((b), 12); \ (a) = _mm_add_epi32((a), (b)); (d) ^= a; (d) = rol32((d), 8); \ (c) = _mm_add_epi32((c), (d)); (b) ^= c; (b) = rol32((b), 7); \ } while (/*CONSTCOND*/0) static inline __m128i load1_epi32(const void *p) { return (__m128i)_mm_load1_ps(p); } static inline __m128i loadu_epi32(const void *p) { return _mm_loadu_si128(p); } static inline void storeu_epi32(void *p, __m128i v) { return _mm_storeu_si128(p, v); } static inline __m128i unpack0_epi32(__m128i a, __m128i b, __m128i c, __m128i d) { __m128 lo = (__m128)_mm_unpacklo_epi32(a, b); /* (a[0], b[0], ...) */ __m128 hi = (__m128)_mm_unpacklo_epi32(c, d); /* (c[0], d[0], ...) */ /* (lo[0]=a[0], lo[1]=b[0], hi[0]=c[0], hi[1]=d[0]) */ return (__m128i)_mm_movelh_ps(lo, hi); } static inline __m128i unpack1_epi32(__m128i a, __m128i b, __m128i c, __m128i d) { __m128 lo = (__m128)_mm_unpacklo_epi32(a, b); /* (..., a[1], b[1]) */ __m128 hi = (__m128)_mm_unpacklo_epi32(c, d); /* (..., c[1], d[1]) */ /* (lo[2]=a[1], lo[3]=b[1], hi[2]=c[1], hi[3]=d[1]) */ return (__m128i)_mm_movehl_ps(hi, lo); } static inline __m128i unpack2_epi32(__m128i a, __m128i b, __m128i c, __m128i d) { __m128 lo = (__m128)_mm_unpackhi_epi32(a, b); /* (a[2], b[2], ...) */ __m128 hi = (__m128)_mm_unpackhi_epi32(c, d); /* (c[2], d[2], ...) */ /* (lo[0]=a[2], lo[1]=b[2], hi[0]=c[2], hi[1]=d[2]) */ return (__m128i)_mm_movelh_ps(lo, hi); } static inline __m128i unpack3_epi32(__m128i a, __m128i b, __m128i c, __m128i d) { __m128 lo = (__m128)_mm_unpackhi_epi32(a, b); /* (..., a[3], b[3]) */ __m128 hi = (__m128)_mm_unpackhi_epi32(c, d); /* (..., c[3], d[3]) */ /* (lo[2]=a[3], lo[3]=b[3], hi[2]=c[3], hi[3]=d[3]) */ return (__m128i)_mm_movehl_ps(hi, lo); } void chacha_stream_sse2(uint8_t *restrict s, size_t n, uint32_t blkno, const uint8_t nonce[static 12], const uint8_t k[static 32], unsigned nr) { __m128i x0,x1,x2,x3,x4,x5,x6,x7,x8,x9,x10,x11,x12,x13,x14,x15; __m128i y0,y1,y2,y3,y4,y5,y6,y7,y8,y9,y10,y11,y12,y13,y14,y15; __m128i z0,z1,z2,z3,z4,z5,z6,z7,z8,z9,z10,z11,z12,z13,z14,z15; unsigned r; if (n < 256) goto out; x0 = load1_epi32(chacha_const32 + 0); x1 = load1_epi32(chacha_const32 + 4); x2 = load1_epi32(chacha_const32 + 8); x3 = load1_epi32(chacha_const32 + 12); x4 = load1_epi32(k + 0); x5 = load1_epi32(k + 4); x6 = load1_epi32(k + 8); x7 = load1_epi32(k + 12); x8 = load1_epi32(k + 16); x9 = load1_epi32(k + 20); x10 = load1_epi32(k + 24); x11 = load1_epi32(k + 28); /* x12 set in the loop */ x13 = load1_epi32(nonce + 0); x14 = load1_epi32(nonce + 4); x15 = load1_epi32(nonce + 8); for (; n >= 256; s += 256, n -= 256, blkno += 4) { x12 = _mm_add_epi32(_mm_set1_epi32(blkno), _mm_set_epi32(3,2,1,0)); y0 = x0; y1 = x1; y2 = x2; y3 = x3; y4 = x4; y5 = x5; y6 = x6; y7 = x7; y8 = x8; y9 = x9; y10 = x10; y11 = x11; y12 = x12; y13 = x13; y14 = x14; y15 = x15; for (r = nr; r > 0; r -= 2) { CHACHA_QUARTERROUND( y0, y4, y8,y12); CHACHA_QUARTERROUND( y1, y5, y9,y13); CHACHA_QUARTERROUND( y2, y6,y10,y14); CHACHA_QUARTERROUND( y3, y7,y11,y15); CHACHA_QUARTERROUND( y0, y5,y10,y15); CHACHA_QUARTERROUND( y1, y6,y11,y12); CHACHA_QUARTERROUND( y2, y7, y8,y13); CHACHA_QUARTERROUND( y3, y4, y9,y14); } y0 = _mm_add_epi32(y0, x0); y1 = _mm_add_epi32(y1, x1); y2 = _mm_add_epi32(y2, x2); y3 = _mm_add_epi32(y3, x3); y4 = _mm_add_epi32(y4, x4); y5 = _mm_add_epi32(y5, x5); y6 = _mm_add_epi32(y6, x6); y7 = _mm_add_epi32(y7, x7); y8 = _mm_add_epi32(y8, x8); y9 = _mm_add_epi32(y9, x9); y10 = _mm_add_epi32(y10, x10); y11 = _mm_add_epi32(y11, x11); y12 = _mm_add_epi32(y12, x12); y13 = _mm_add_epi32(y13, x13); y14 = _mm_add_epi32(y14, x14); y15 = _mm_add_epi32(y15, x15); z0 = unpack0_epi32(y0, y1, y2, y3); z1 = unpack0_epi32(y4, y5, y6, y7); z2 = unpack0_epi32(y8, y9, y10, y11); z3 = unpack0_epi32(y12, y13, y14, y15); z4 = unpack1_epi32(y0, y1, y2, y3); z5 = unpack1_epi32(y4, y5, y6, y7); z6 = unpack1_epi32(y8, y9, y10, y11); z7 = unpack1_epi32(y12, y13, y14, y15); z8 = unpack2_epi32(y0, y1, y2, y3); z9 = unpack2_epi32(y4, y5, y6, y7); z10 = unpack2_epi32(y8, y9, y10, y11); z11 = unpack2_epi32(y12, y13, y14, y15); z12 = unpack3_epi32(y0, y1, y2, y3); z13 = unpack3_epi32(y4, y5, y6, y7); z14 = unpack3_epi32(y8, y9, y10, y11); z15 = unpack3_epi32(y12, y13, y14, y15); storeu_epi32(s + 16*0, z0); storeu_epi32(s + 16*1, z1); storeu_epi32(s + 16*2, z2); storeu_epi32(s + 16*3, z3); storeu_epi32(s + 16*4, z4); storeu_epi32(s + 16*5, z5); storeu_epi32(s + 16*6, z6); storeu_epi32(s + 16*7, z7); storeu_epi32(s + 16*8, z8); storeu_epi32(s + 16*9, z9); storeu_epi32(s + 16*10, z10); storeu_epi32(s + 16*11, z11); storeu_epi32(s + 16*12, z12); storeu_epi32(s + 16*13, z13); storeu_epi32(s + 16*14, z14); storeu_epi32(s + 16*15, z15); } out: if (n) { const __m128i blkno_inc = _mm_set_epi32(0,0,0,1); __m128i in0, in1, in2, in3; __m128i r0, r1, r2, r3; in0 = _mm_loadu_si128((const __m128i *)chacha_const32); in1 = _mm_loadu_si128((const __m128i *)k); in2 = _mm_loadu_si128((const __m128i *)k + 1); in3 = _mm_set_epi32(le32dec(nonce + 8), le32dec(nonce + 4), le32dec(nonce), blkno); for (; n; s += 64, n -= 64) { r0 = in0; r1 = in1; r2 = in2; r3 = in3; chacha_permute(&r0, &r1, &r2, &r3, nr); r0 = _mm_add_epi32(r0, in0); r1 = _mm_add_epi32(r1, in1); r2 = _mm_add_epi32(r2, in2); r3 = _mm_add_epi32(r3, in3); if (n < 64) { uint8_t buf[64] __aligned(16); _mm_storeu_si128((__m128i *)buf + 0, r0); _mm_storeu_si128((__m128i *)buf + 1, r1); _mm_storeu_si128((__m128i *)buf + 2, r2); _mm_storeu_si128((__m128i *)buf + 3, r3); memcpy(s, buf, n); break; } _mm_storeu_si128((__m128i *)s + 0, r0); _mm_storeu_si128((__m128i *)s + 1, r1); _mm_storeu_si128((__m128i *)s + 2, r2); _mm_storeu_si128((__m128i *)s + 3, r3); in3 = _mm_add_epi32(in3, blkno_inc); } } } void chacha_stream_xor_sse2(uint8_t *s, const uint8_t *p, size_t n, uint32_t blkno, const uint8_t nonce[static 12], const uint8_t k[static 32], unsigned nr) { __m128i x0,x1,x2,x3,x4,x5,x6,x7,x8,x9,x10,x11,x12,x13,x14,x15; __m128i y0,y1,y2,y3,y4,y5,y6,y7,y8,y9,y10,y11,y12,y13,y14,y15; __m128i z0,z1,z2,z3,z4,z5,z6,z7,z8,z9,z10,z11,z12,z13,z14,z15; unsigned r; if (n < 256) goto out; x0 = load1_epi32(chacha_const32 + 0); x1 = load1_epi32(chacha_const32 + 4); x2 = load1_epi32(chacha_const32 + 8); x3 = load1_epi32(chacha_const32 + 12); x4 = load1_epi32(k + 0); x5 = load1_epi32(k + 4); x6 = load1_epi32(k + 8); x7 = load1_epi32(k + 12); x8 = load1_epi32(k + 16); x9 = load1_epi32(k + 20); x10 = load1_epi32(k + 24); x11 = load1_epi32(k + 28); /* x12 set in the loop */ x13 = load1_epi32(nonce + 0); x14 = load1_epi32(nonce + 4); x15 = load1_epi32(nonce + 8); for (; n >= 256; s += 256, p += 256, n -= 256, blkno += 4) { x12 = _mm_add_epi32(_mm_set1_epi32(blkno), _mm_set_epi32(3,2,1,0)); y0 = x0; y1 = x1; y2 = x2; y3 = x3; y4 = x4; y5 = x5; y6 = x6; y7 = x7; y8 = x8; y9 = x9; y10 = x10; y11 = x11; y12 = x12; y13 = x13; y14 = x14; y15 = x15; for (r = nr; r > 0; r -= 2) { CHACHA_QUARTERROUND( y0, y4, y8,y12); CHACHA_QUARTERROUND( y1, y5, y9,y13); CHACHA_QUARTERROUND( y2, y6,y10,y14); CHACHA_QUARTERROUND( y3, y7,y11,y15); CHACHA_QUARTERROUND( y0, y5,y10,y15); CHACHA_QUARTERROUND( y1, y6,y11,y12); CHACHA_QUARTERROUND( y2, y7, y8,y13); CHACHA_QUARTERROUND( y3, y4, y9,y14); } y0 = _mm_add_epi32(y0, x0); y1 = _mm_add_epi32(y1, x1); y2 = _mm_add_epi32(y2, x2); y3 = _mm_add_epi32(y3, x3); y4 = _mm_add_epi32(y4, x4); y5 = _mm_add_epi32(y5, x5); y6 = _mm_add_epi32(y6, x6); y7 = _mm_add_epi32(y7, x7); y8 = _mm_add_epi32(y8, x8); y9 = _mm_add_epi32(y9, x9); y10 = _mm_add_epi32(y10, x10); y11 = _mm_add_epi32(y11, x11); y12 = _mm_add_epi32(y12, x12); y13 = _mm_add_epi32(y13, x13); y14 = _mm_add_epi32(y14, x14); y15 = _mm_add_epi32(y15, x15); z0 = unpack0_epi32(y0, y1, y2, y3); z1 = unpack0_epi32(y4, y5, y6, y7); z2 = unpack0_epi32(y8, y9, y10, y11); z3 = unpack0_epi32(y12, y13, y14, y15); z4 = unpack1_epi32(y0, y1, y2, y3); z5 = unpack1_epi32(y4, y5, y6, y7); z6 = unpack1_epi32(y8, y9, y10, y11); z7 = unpack1_epi32(y12, y13, y14, y15); z8 = unpack2_epi32(y0, y1, y2, y3); z9 = unpack2_epi32(y4, y5, y6, y7); z10 = unpack2_epi32(y8, y9, y10, y11); z11 = unpack2_epi32(y12, y13, y14, y15); z12 = unpack3_epi32(y0, y1, y2, y3); z13 = unpack3_epi32(y4, y5, y6, y7); z14 = unpack3_epi32(y8, y9, y10, y11); z15 = unpack3_epi32(y12, y13, y14, y15); storeu_epi32(s + 16*0, loadu_epi32(p + 16*0) ^ z0); storeu_epi32(s + 16*1, loadu_epi32(p + 16*1) ^ z1); storeu_epi32(s + 16*2, loadu_epi32(p + 16*2) ^ z2); storeu_epi32(s + 16*3, loadu_epi32(p + 16*3) ^ z3); storeu_epi32(s + 16*4, loadu_epi32(p + 16*4) ^ z4); storeu_epi32(s + 16*5, loadu_epi32(p + 16*5) ^ z5); storeu_epi32(s + 16*6, loadu_epi32(p + 16*6) ^ z6); storeu_epi32(s + 16*7, loadu_epi32(p + 16*7) ^ z7); storeu_epi32(s + 16*8, loadu_epi32(p + 16*8) ^ z8); storeu_epi32(s + 16*9, loadu_epi32(p + 16*9) ^ z9); storeu_epi32(s + 16*10, loadu_epi32(p + 16*10) ^ z10); storeu_epi32(s + 16*11, loadu_epi32(p + 16*11) ^ z11); storeu_epi32(s + 16*12, loadu_epi32(p + 16*12) ^ z12); storeu_epi32(s + 16*13, loadu_epi32(p + 16*13) ^ z13); storeu_epi32(s + 16*14, loadu_epi32(p + 16*14) ^ z14); storeu_epi32(s + 16*15, loadu_epi32(p + 16*15) ^ z15); } out: if (n) { const __m128i blkno_inc = _mm_set_epi32(0,0,0,1); __m128i in0, in1, in2, in3; __m128i r0, r1, r2, r3; in0 = _mm_loadu_si128((const __m128i *)chacha_const32); in1 = _mm_loadu_si128((const __m128i *)k); in2 = _mm_loadu_si128((const __m128i *)k + 1); in3 = _mm_set_epi32(le32dec(nonce + 8), le32dec(nonce + 4), le32dec(nonce), blkno); for (; n; s += 64, p += 64, n -= 64) { r0 = in0; r1 = in1; r2 = in2; r3 = in3; chacha_permute(&r0, &r1, &r2, &r3, nr); r0 = _mm_add_epi32(r0, in0); r1 = _mm_add_epi32(r1, in1); r2 = _mm_add_epi32(r2, in2); r3 = _mm_add_epi32(r3, in3); if (n < 64) { uint8_t buf[64] __aligned(16); unsigned i; _mm_storeu_si128((__m128i *)buf + 0, r0); _mm_storeu_si128((__m128i *)buf + 1, r1); _mm_storeu_si128((__m128i *)buf + 2, r2); _mm_storeu_si128((__m128i *)buf + 3, r3); for (i = 0; i < n - n%4; i += 4) le32enc(s + i, le32dec(p + i) ^ le32dec(buf + i)); for (; i < n; i++) s[i] = p[i] ^ buf[i]; break; } r0 ^= _mm_loadu_si128((const __m128i *)p + 0); r1 ^= _mm_loadu_si128((const __m128i *)p + 1); r2 ^= _mm_loadu_si128((const __m128i *)p + 2); r3 ^= _mm_loadu_si128((const __m128i *)p + 3); _mm_storeu_si128((__m128i *)s + 0, r0); _mm_storeu_si128((__m128i *)s + 1, r1); _mm_storeu_si128((__m128i *)s + 2, r2); _mm_storeu_si128((__m128i *)s + 3, r3); in3 = _mm_add_epi32(in3, blkno_inc); } } } void xchacha_stream_sse2(uint8_t *restrict s, size_t nbytes, uint32_t blkno, const uint8_t nonce[static 24], const uint8_t k[static 32], unsigned nr) { uint8_t subkey[32]; uint8_t subnonce[12]; hchacha_sse2(subkey, nonce/*[0:16)*/, k, chacha_const32, nr); memset(subnonce, 0, 4); memcpy(subnonce + 4, nonce + 16, 8); chacha_stream_sse2(s, nbytes, blkno, subnonce, subkey, nr); } void xchacha_stream_xor_sse2(uint8_t *restrict c, const uint8_t *p, size_t nbytes, uint32_t blkno, const uint8_t nonce[static 24], const uint8_t k[static 32], unsigned nr) { uint8_t subkey[32]; uint8_t subnonce[12]; hchacha_sse2(subkey, nonce/*[0:16)*/, k, chacha_const32, nr); memset(subnonce, 0, 4); memcpy(subnonce + 4, nonce + 16, 8); chacha_stream_xor_sse2(c, p, nbytes, blkno, subnonce, subkey, nr); } |
4 4 1 1 1 1 9 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 | /* $NetBSD: vfs_hooks.c,v 1.6 2009/03/15 17:14:40 cegger Exp $ */ /*- * Copyright (c) 2005 The NetBSD Foundation, Inc. * All rights reserved. * * This code is derived from software contributed to The NetBSD Foundation * by Julio M. Merino Vidal. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ /* * VFS hooks. */ #include <sys/cdefs.h> __KERNEL_RCSID(0, "$NetBSD: vfs_hooks.c,v 1.6 2009/03/15 17:14:40 cegger Exp $"); #include <sys/param.h> #include <sys/queue.h> #include <sys/mount.h> #include <sys/mutex.h> LIST_HEAD(vfs_hooks_head, vfs_hooks) vfs_hooks_head = LIST_HEAD_INITIALIZER(vfs_hooks_head); kmutex_t vfs_hooks_lock; void vfs_hooks_init(void) { mutex_init(&vfs_hooks_lock, MUTEX_DEFAULT, IPL_NONE); } int vfs_hooks_attach(struct vfs_hooks *vfs_hooks) { mutex_enter(&vfs_hooks_lock); LIST_INSERT_HEAD(&vfs_hooks_head, vfs_hooks, vfs_hooks_list); mutex_exit(&vfs_hooks_lock); return (0); } int vfs_hooks_detach(struct vfs_hooks *vfs_hooks) { struct vfs_hooks *hp; int ret = 0; mutex_enter(&vfs_hooks_lock); LIST_FOREACH(hp, &vfs_hooks_head, vfs_hooks_list) { if (hp == vfs_hooks) { LIST_REMOVE(hp, vfs_hooks_list); break; } } if (hp == NULL) ret = ESRCH; mutex_exit(&vfs_hooks_lock); return (ret); } /* * Macro to be used in one of the vfs_hooks_* function for hooks that * return an error code. Calls will stop as soon as one of the hooks * fails. */ #define VFS_HOOKS_W_ERROR(func, fargs, hook, hargs) \ int \ func fargs \ { \ int error; \ struct vfs_hooks *hp; \ \ error = EJUSTRETURN; \ \ mutex_enter(&vfs_hooks_lock); \ LIST_FOREACH(hp, &vfs_hooks_head, vfs_hooks_list) { \ if (hp-> hook != NULL) { \ error = hp-> hook hargs; \ if (error != 0) \ break; \ } \ } \ mutex_exit(&vfs_hooks_lock); \ \ return error; \ } /* * Macro to be used in one of the vfs_hooks_* function for hooks that * do not return any error code. All hooks will be executed * unconditionally. */ #define VFS_HOOKS_WO_ERROR(func, fargs, hook, hargs) \ void \ func fargs \ { \ struct vfs_hooks *hp; \ \ mutex_enter(&vfs_hooks_lock); \ LIST_FOREACH(hp, &vfs_hooks_head, vfs_hooks_list) { \ if (hp-> hook != NULL) \ hp-> hook hargs; \ } \ mutex_exit(&vfs_hooks_lock); \ } /* * Routines to iterate over VFS hooks lists and execute them. */ VFS_HOOKS_WO_ERROR(vfs_hooks_unmount, (struct mount *mp), vh_unmount, (mp)); VFS_HOOKS_W_ERROR(vfs_hooks_reexport, (struct mount *mp, const char *path, void *data), vh_reexport, (mp, path, data)); |
35 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 | /* $NetBSD: proc.h,v 1.370 2022/05/09 13:27:24 wiz Exp $ */ /*- * Copyright (c) 2006, 2007, 2008, 2020 The NetBSD Foundation, Inc. * All rights reserved. * * This code is derived from software contributed to The NetBSD Foundation * by Andrew Doran. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ /*- * Copyright (c) 1986, 1989, 1991, 1993 * The Regents of the University of California. All rights reserved. * (c) UNIX System Laboratories, Inc. * All or some portions of this file are derived from material licensed * to the University of California by American Telephone and Telegraph * Co. or Unix System Laboratories, Inc. and are reproduced herein with * the permission of UNIX System Laboratories, Inc. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * @(#)proc.h 8.15 (Berkeley) 5/19/95 */ #ifndef _SYS_PROC_H_ #define _SYS_PROC_H_ #include <sys/lwp.h> #if defined(_KMEMUSER) || defined(_KERNEL) #if defined(_KERNEL_OPT) #include "opt_multiprocessor.h" #include "opt_kstack.h" #include "opt_lockdebug.h" #endif #include <machine/proc.h> /* Machine-dependent proc substruct */ #include <machine/pcb.h> #include <sys/aio.h> #include <sys/idtype.h> #include <sys/rwlock.h> #include <sys/mqueue.h> #include <sys/mutex.h> #include <sys/condvar.h> #include <sys/queue.h> #include <sys/radixtree.h> #include <sys/signalvar.h> #include <sys/siginfo.h> #include <sys/event.h> #include <sys/specificdata.h> #ifndef _KERNEL #include <sys/time.h> #include <sys/resource.h> #endif /* * One structure allocated per session. */ struct session { int s_count; /* Ref cnt; pgrps in session */ u_int s_flags; #define S_LOGIN_SET 1 /* s_login set in this session */ struct proc *s_leader; /* Session leader */ struct vnode *s_ttyvp; /* Vnode of controlling terminal */ struct tty *s_ttyp; /* Controlling terminal */ char s_login[MAXLOGNAME]; /* Setlogin() name */ pid_t s_sid; /* Session ID (pid of leader) */ }; /* * One structure allocated per process group. */ struct pgrp { LIST_HEAD(, proc) pg_members; /* Pointer to pgrp members */ struct session *pg_session; /* Pointer to session */ pid_t pg_id; /* Pgrp id */ int pg_jobc; /* * Number of processes qualifying * pgrp for job control */ }; /* * Autoloadable syscall definition */ struct sc_autoload { u_int al_code; const char *al_module; }; /* * One structure allocated per emulation. */ struct exec_package; struct ras; struct kauth_cred; struct emul { const char *e_name; /* Symbolic name */ const char *e_path; /* Extra emulation path (NULL if none)*/ #ifndef __HAVE_MINIMAL_EMUL int e_flags; /* Miscellaneous flags, see above */ /* Syscall handling function */ const int *e_errno; /* Errno array */ int e_nosys; /* Offset of the nosys() syscall */ int e_nsysent; /* Number of system call entries */ #endif struct sysent *e_sysent; /* System call array */ const uint32_t *e_nomodbits; /* sys_nosys/sys_nomodule flags * for syscall_disestablish() */ const char * const *e_syscallnames; /* System call name array */ struct sc_autoload *e_sc_autoload; /* List of autoloadable syscalls */ /* Signal sending function */ void (*e_sendsig)(const struct ksiginfo *, const sigset_t *); void (*e_trapsignal)(struct lwp *, struct ksiginfo *); char *e_sigcode; /* Start of sigcode */ char *e_esigcode; /* End of sigcode */ /* Set registers before execution */ struct uvm_object **e_sigobject;/* shared sigcode object */ void (*e_setregs)(struct lwp *, struct exec_package *, vaddr_t); /* Per-process hooks */ void (*e_proc_exec)(struct proc *, struct exec_package *); void (*e_proc_fork)(struct proc *, struct lwp *, int); void (*e_proc_exit)(struct proc *); void (*e_lwp_fork)(struct lwp *, struct lwp *); void (*e_lwp_exit)(struct lwp *); #ifdef __HAVE_SYSCALL_INTERN void (*e_syscall_intern)(struct proc *); #else void (*e_syscall)(void); #endif /* Emulation specific sysctl data */ struct sysctlnode *e_sysctlovly; vaddr_t (*e_vm_default_addr)(struct proc *, vaddr_t, vsize_t, int); /* Emulation-specific hook for userspace page faults */ int (*e_usertrap)(struct lwp *, vaddr_t, void *); size_t e_ucsize; /* size of ucontext_t */ void (*e_startlwp)(void *); /* Dtrace syscall probe */ void (*e_dtrace_syscall)(uint32_t, register_t, const struct sysent *, const void *, const register_t *, int); /* Emulation specific support for ktracing signal posts */ void (*e_ktrpsig)(int, sig_t, const sigset_t *, const struct ksiginfo *); }; /* * Emulation miscellaneous flags */ #define EMUL_HAS_SYS___syscall 0x001 /* Has SYS___syscall */ /* * Description of a process. * * This structure contains the information needed to manage a thread of * control, known in UN*X as a process; it has references to substructures * containing descriptions of things that the process uses, but may share * with related processes. The process structure and the substructures * are always addressible except for those marked "(PROC ONLY)" below, * which might be addressible only on a processor on which the process * is running. * * Field markings and the corresponding locks: * * a: p_auxlock * k: ktrace_mutex * l: proc_lock * t: p_stmutex * p: p_lock * (: updated atomically * :: unlocked, stable */ struct vmspace; struct proc { LIST_ENTRY(proc) p_list; /* l: List of all processes */ kmutex_t *p_lock; /* :: general mutex */ kcondvar_t p_waitcv; /* p: wait, stop CV on children */ kcondvar_t p_lwpcv; /* p: wait, stop CV on LWPs */ /* Substructures: */ struct kauth_cred *p_cred; /* p: Master copy of credentials */ struct filedesc *p_fd; /* :: Ptr to open files structure */ struct cwdinfo *p_cwdi; /* :: cdir/rdir/cmask info */ struct pstats *p_stats; /* :: Accounting/stats (PROC ONLY) */ struct plimit *p_limit; /* :: Process limits */ struct vmspace *p_vmspace; /* :: Address space */ struct sigacts *p_sigacts; /* :: Process sigactions */ struct aioproc *p_aio; /* p: Asynchronous I/O data */ u_int p_mqueue_cnt; /* (: Count of open message queues */ specificdata_reference p_specdataref; /* subsystem proc-specific data */ int p_exitsig; /* l: signal to send to parent on exit */ int p_flag; /* p: PK_* flags */ int p_sflag; /* p: PS_* flags */ int p_slflag; /* p, l: PSL_* flags */ int p_lflag; /* l: PL_* flags */ int p_stflag; /* t: PST_* flags */ char p_stat; /* p: S* process status. */ char p_trace_enabled;/* p: cached by syscall_intern() */ char p_pad1[2]; /* unused */ pid_t p_pid; /* :: Process identifier. */ LIST_ENTRY(proc) p_pglist; /* l: List of processes in pgrp. */ struct proc *p_pptr; /* l: Pointer to parent process. */ LIST_ENTRY(proc) p_sibling; /* l: List of sibling processes. */ LIST_HEAD(, proc) p_children; /* l: List of children. */ LIST_HEAD(, lwp) p_lwps; /* p: List of LWPs. */ struct ras *p_raslist; /* a: List of RAS entries */ /* The following fields are all zeroed upon creation in fork. */ #define p_startzero p_nlwps int p_nlwps; /* p: Number of LWPs */ int p_nzlwps; /* p: Number of zombie LWPs */ int p_nrlwps; /* p: Number running/sleeping LWPs */ int p_nlwpwait; /* p: Number of LWPs in lwp_wait1() */ int p_ndlwps; /* p: Number of detached LWPs */ u_int p_nstopchild; /* l: Count of stopped/dead children */ u_int p_waited; /* l: parent has waited on child */ struct lwp *p_zomblwp; /* p: detached LWP to be reaped */ struct lwp *p_vforklwp; /* p: parent LWP waiting at vfork() */ /* scheduling */ void *p_sched_info; /* p: Scheduler-specific structure */ fixpt_t p_estcpu; /* p: Time avg. value of p_cpticks */ fixpt_t p_estcpu_inherited; /* p: cpu inherited from children */ unsigned int p_forktime; fixpt_t p_pctcpu; /* p: %cpu from dead LWPs */ struct proc *p_opptr; /* l: save parent during ptrace. */ struct ptimers *p_timers; /* Timers: real, virtual, profiling */ struct bintime p_rtime; /* p: real time */ u_quad_t p_uticks; /* t: Statclock hits in user mode */ u_quad_t p_sticks; /* t: Statclock hits in system mode */ u_quad_t p_iticks; /* t: Statclock hits processing intr */ uint64_t p_xutime; /* p: utime exposed to userspace */ uint64_t p_xstime; /* p: stime exposed to userspace */ int p_traceflag; /* k: Kernel trace points */ void *p_tracep; /* k: Trace private data */ struct vnode *p_textvp; /* :: Vnode of executable */ struct emul *p_emul; /* :: emulation information */ void *p_emuldata; /* :: per-proc emul data, or NULL */ const struct execsw *p_execsw; /* :: exec package information */ struct klist p_klist; /* p: knotes attached to proc */ LIST_HEAD(, lwp) p_sigwaiters; /* p: LWPs waiting for signals */ sigpend_t p_sigpend; /* p: pending signals */ struct lcproc *p_lwpctl; /* p, a: _lwp_ctl() information */ pid_t p_ppid; /* :: cached parent pid */ pid_t p_oppid; /* :: cached original parent pid */ char *p_path; /* :: full pathname of executable */ /* * End area that is zeroed on creation */ #define p_endzero p_startcopy /* * The following fields are all copied upon creation in fork. */ #define p_startcopy p_sigctx struct sigctx p_sigctx; /* p: Shared signal state */ u_char p_nice; /* p: Process "nice" value */ char p_comm[MAXCOMLEN+1]; /* p: basename of last exec file */ struct pgrp *p_pgrp; /* l: Pointer to process group */ vaddr_t p_psstrp; /* :: address of process's ps_strings */ u_int p_pax; /* :: PAX flags */ int p_xexit; /* p: exit code */ /* * End area that is copied on creation */ #define p_endcopy p_xsig u_short p_xsig; /* p: stop signal */ u_short p_acflag; /* p: Acc. flags; see struct lwp also */ struct mdproc p_md; /* p: Any machine-dependent fields */ vaddr_t p_stackbase; /* :: ASLR randomized stack base */ struct kdtrace_proc *p_dtrace; /* :: DTrace-specific data. */ /* * Locks in their own cache line towards the end. */ kmutex_t p_auxlock /* :: secondary, longer term lock */ __aligned(COHERENCY_UNIT); kmutex_t p_stmutex; /* :: mutex on profiling state */ krwlock_t p_reflock; /* :: lock for debugger, procfs */ }; #define p_rlimit p_limit->pl_rlimit #define p_session p_pgrp->pg_session #define p_pgid p_pgrp->pg_id #endif /* _KMEMUSER || _KERNEL */ /* * Status values. */ #define SIDL 1 /* Process being created by fork */ #define SACTIVE 2 /* Process is not stopped */ #define SDYING 3 /* About to die */ #define SSTOP 4 /* Process debugging or suspension */ #define SZOMB 5 /* Awaiting collection by parent */ #define SDEAD 6 /* Almost a zombie */ #define P_ZOMBIE(p) \ ((p)->p_stat == SZOMB || (p)->p_stat == SDYING || (p)->p_stat == SDEAD) /* * These flags are kept in p_flag and are protected by p_lock. Access from * process context only. */ #define PK_ADVLOCK 0x00000001 /* Process may hold a POSIX advisory lock */ #define PK_SYSTEM 0x00000002 /* System process (kthread) */ #define PK_SYSVSEM 0x00000004 /* Used SysV semaphores */ #define PK_SUGID 0x00000100 /* Had set id privileges since last exec */ #define PK_KMEM 0x00000200 /* Has kmem access */ #define PK_EXEC 0x00004000 /* Process called exec */ #define PK_NOCLDWAIT 0x00020000 /* No zombies if child dies */ #define PK_32 0x00040000 /* 32-bit process (used on 64-bit kernels) */ #define PK_CLDSIGIGN 0x00080000 /* Process is ignoring SIGCHLD */ #define PK_MARKER 0x80000000 /* Is a dummy marker process */ /* * These flags are kept in p_sflag and are protected by p_lock. Access from * process context only. */ #define PS_NOCLDSTOP 0x00000008 /* No SIGCHLD when children stop */ #define PS_RUMP_LWPEXIT 0x00000400 /* LWPs in RUMP kernel should exit for GC */ #define PS_WCORE 0x00001000 /* Process needs to dump core */ #define PS_WEXIT 0x00002000 /* Working on exiting */ #define PS_STOPFORK 0x00800000 /* Child will be stopped on fork(2) */ #define PS_STOPEXEC 0x01000000 /* Will be stopped on exec(2) */ #define PS_STOPEXIT 0x02000000 /* Will be stopped at process exit */ #define PS_COREDUMP 0x20000000 /* Process core-dumped */ #define PS_CONTINUED 0x40000000 /* Process is continued */ #define PS_STOPPING 0x80000000 /* Transitioning SACTIVE -> SSTOP */ /* * These flags are kept in p_slflag and are protected by the proc_lock * and p_lock. Access from process context only. */ #define PSL_TRACEFORK 0x00000001 /* traced process wants fork events */ #define PSL_TRACEVFORK 0x00000002 /* traced process wants vfork events */ #define PSL_TRACEVFORK_DONE \ 0x00000004 /* traced process wants vfork done events */ #define PSL_TRACELWP_CREATE \ 0x00000008 /* traced process wants LWP create events */ #define PSL_TRACELWP_EXIT \ 0x00000010 /* traced process wants LWP exit events */ #define PSL_TRACEPOSIX_SPAWN \ 0x00000020 /* traced process wants posix_spawn events */ #define PSL_TRACED 0x00000800 /* Debugged process being traced */ #define PSL_TRACEDCHILD 0x00001000 /* Report process birth */ #define PSL_CHTRACED 0x00400000 /* Child has been traced & reparented */ #define PSL_SYSCALL 0x04000000 /* process has PT_SYSCALL enabled */ #define PSL_SYSCALLEMU 0x08000000 /* cancel in-progress syscall */ /* * Kept in p_stflag and protected by p_stmutex. */ #define PST_PROFIL 0x00000020 /* Has started profiling */ /* * Kept in p_lflag and protected by the proc_lock. Access * from process context only. */ #define PL_CONTROLT 0x00000002 /* Has a controlling terminal */ #define PL_PPWAIT 0x00000010 /* Parent is waiting for child exec/exit */ #define PL_SIGCOMPAT 0x00000200 /* Has used compat signal trampoline */ #define PL_ORPHANPG 0x20000000 /* Member of an orphaned pgrp */ #if defined(_KMEMUSER) || defined(_KERNEL) /* * Macro to compute the exit signal to be delivered. */ #define P_EXITSIG(p) \ (((p)->p_slflag & PSL_TRACED) ? SIGCHLD : p->p_exitsig) /* * Compute a wait(2) 16 bit exit status code */ #define P_WAITSTATUS(p) W_EXITCODE((p)->p_xexit, ((p)->p_xsig | \ (((p)->p_sflag & PS_COREDUMP) ? WCOREFLAG : 0))) LIST_HEAD(proclist, proc); /* A list of processes */ /* * This structure associates a proclist with its lock. */ struct proclist_desc { struct proclist *pd_list; /* The list */ /* * XXX Add a pointer to the proclist's lock eventually. */ }; #ifdef _KERNEL /* * We use process IDs <= PID_MAX until there are > 16k processes. * NO_PGID is used to represent "no process group" for a tty. */ #define PID_MAX 30000 #define NO_PGID ((pid_t)-1) #define SESS_LEADER(p) ((p)->p_session->s_leader == (p)) /* * Flags passed to fork1(). */ #define FORK_PPWAIT 0x0001 /* Block parent until child exit */ #define FORK_SHAREVM 0x0002 /* Share vmspace with parent */ #define FORK_SHARECWD 0x0004 /* Share cdir/rdir/cmask */ #define FORK_SHAREFILES 0x0008 /* Share file descriptors */ #define FORK_SHARESIGS 0x0010 /* Share signal actions */ #define FORK_NOWAIT 0x0020 /* Make init the parent of the child */ #define FORK_CLEANFILES 0x0040 /* Start with a clean descriptor set */ #define FORK_SYSTEM 0x0080 /* Fork a kernel thread */ extern struct proc proc0; /* Process slot for swapper */ extern u_int nprocs; /* Current number of procs */ extern int maxproc; /* Max number of procs */ #define vmspace_kernel() (proc0.p_vmspace) extern kmutex_t proc_lock; extern struct proclist allproc; /* List of all processes */ extern struct proclist zombproc; /* List of zombie processes */ extern struct proc *initproc; /* Process slots for init, pager */ extern const struct proclist_desc proclists[]; int proc_find_locked(struct lwp *, struct proc **, pid_t); proc_t * proc_find_raw(pid_t); proc_t * proc_find(pid_t); /* Find process by ID */ proc_t * proc_find_lwpid(pid_t); /* Find process by LWP ID */ struct lwp * proc_find_lwp(proc_t *, pid_t); /* Find LWP in proc by ID */ struct lwp * proc_find_lwp_unlocked(proc_t *, pid_t); /* Find LWP, acquire proc */ struct lwp * proc_find_lwp_acquire_proc(pid_t, proc_t **); struct pgrp * pgrp_find(pid_t); /* Find process group by ID */ void procinit(void); void procinit_sysctl(void); int proc_enterpgrp(struct proc *, pid_t, pid_t, bool); void proc_leavepgrp(struct proc *); void proc_sesshold(struct session *); void proc_sessrele(struct session *); void fixjobc(struct proc *, struct pgrp *, int); int tsleep(wchan_t, pri_t, const char *, int); int mtsleep(wchan_t, pri_t, const char *, int, kmutex_t *); void wakeup(wchan_t); int kpause(const char *, bool, int, kmutex_t *); void exit1(struct lwp *, int, int) __dead; int kill1(struct lwp *l, pid_t pid, ksiginfo_t *ksi, register_t *retval); int do_sys_wait(int *, int *, int, struct rusage *); int do_sys_waitid(idtype_t, id_t, int *, int *, int, struct wrusage *, siginfo_t *); struct proc *proc_alloc(void); void proc0_init(void); pid_t proc_alloc_pid(struct proc *); void proc_free_pid(pid_t); pid_t proc_alloc_lwpid(struct proc *, struct lwp *); void proc_free_lwpid(struct proc *, pid_t); void proc_free_mem(struct proc *); void exit_lwps(struct lwp *l); int fork1(struct lwp *, int, int, void *, size_t, void (*)(void *), void *, register_t *); int pgid_in_session(struct proc *, pid_t); void cpu_lwp_fork(struct lwp *, struct lwp *, void *, size_t, void (*)(void *), void *); void cpu_lwp_free(struct lwp *, int); void cpu_lwp_free2(struct lwp *); void cpu_spawn_return(struct lwp*); #ifdef __HAVE_SYSCALL_INTERN void syscall_intern(struct proc *); #endif void md_child_return(struct lwp *); void child_return(void *); int proc_isunder(struct proc *, struct lwp *); int proc_uidmatch(kauth_cred_t, kauth_cred_t); int proc_vmspace_getref(struct proc *, struct vmspace **); void proc_crmod_leave(kauth_cred_t, kauth_cred_t, bool); void proc_crmod_enter(void); int proc_getauxv(struct proc *, void **, size_t *); int proc_specific_key_create(specificdata_key_t *, specificdata_dtor_t); void proc_specific_key_delete(specificdata_key_t); void proc_initspecific(struct proc *); void proc_finispecific(struct proc *); void * proc_getspecific(struct proc *, specificdata_key_t); void proc_setspecific(struct proc *, specificdata_key_t, void *); int proc_compare(const struct proc *, const struct lwp *, const struct proc *, const struct lwp *); /* * Special handlers for delivering EVFILT_PROC notifications. These * exist to handle some of the special locking considerations around * processes. */ void knote_proc_exec(struct proc *); void knote_proc_fork(struct proc *, struct proc *); void knote_proc_exit(struct proc *); int proclist_foreach_call(struct proclist *, int (*)(struct proc *, void *arg), void *); static __inline struct proc * _proclist_skipmarker(struct proc *p0) { struct proc *p = p0; while (p != NULL && p->p_flag & PK_MARKER) p = LIST_NEXT(p, p_list); return p; } #define PROC_PTRSZ(p) (((p)->p_flag & PK_32) ? sizeof(int) : sizeof(void *)) #define PROC_REGSZ(p) (((p)->p_flag & PK_32) ? \ sizeof(process_reg32) : sizeof(struct reg)) #define PROC_FPREGSZ(p) (((p)->p_flag & PK_32) ? \ sizeof(process_fpreg32) : sizeof(struct fpreg)) #define PROC_DBREGSZ(p) (((p)->p_flag & PK_32) ? \ sizeof(process_dbreg32) : sizeof(struct dbreg)) /* * PROCLIST_FOREACH: iterate on the given proclist, skipping PK_MARKER ones. */ #define PROCLIST_FOREACH(var, head) \ for ((var) = LIST_FIRST(head); \ ((var) = _proclist_skipmarker(var)) != NULL; \ (var) = LIST_NEXT(var, p_list)) #ifdef KSTACK_CHECK_MAGIC void kstack_setup_magic(const struct lwp *); void kstack_check_magic(const struct lwp *); #else #define kstack_setup_magic(x) #define kstack_check_magic(x) #endif extern struct emul emul_netbsd; #endif /* _KERNEL */ /* * Kernel stack parameters. * * KSTACK_LOWEST_ADDR: return the lowest address of the LWP's kernel stack, * excluding red-zone. * * KSTACK_SIZE: the size kernel stack for a LWP, excluding red-zone. * * if <machine/proc.h> provides the MD definition, it will be used. */ #ifndef KSTACK_LOWEST_ADDR #define KSTACK_LOWEST_ADDR(l) ((void *)ALIGN((struct pcb *)((l)->l_addr) + 1)) #endif #ifndef KSTACK_SIZE #define KSTACK_SIZE (USPACE - ALIGN(sizeof(struct pcb))) #endif #endif /* _KMEMUSER || _KERNEL */ #endif /* !_SYS_PROC_H_ */ |
1 1 1 1 1 2 3 2 1 2 2 2 2 2 5 5 5 5 4 4 4 4 2 4 1 1 2 2 2 1 2 2 2 2 2 2 2 21 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 | /* $NetBSD: ddp_usrreq.c,v 1.75 2021/09/21 15:01:59 christos Exp $ */ /* * Copyright (c) 1990,1991 Regents of The University of Michigan. * All Rights Reserved. * * Permission to use, copy, modify, and distribute this software and * its documentation for any purpose and without fee is hereby granted, * provided that the above copyright notice appears in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation, and that the name of The University * of Michigan not be used in advertising or publicity pertaining to * distribution of the software without specific, written prior * permission. This software is supplied as is without expressed or * implied warranties of any kind. * * This product includes software developed by the University of * California, Berkeley and its contributors. * * Research Systems Unix Group * The University of Michigan * c/o Wesley Craig * 535 W. William Street * Ann Arbor, Michigan * +1-313-764-2278 * netatalk@umich.edu */ #include <sys/cdefs.h> __KERNEL_RCSID(0, "$NetBSD: ddp_usrreq.c,v 1.75 2021/09/21 15:01:59 christos Exp $"); #include "opt_mbuftrace.h" #include "opt_atalk.h" #include <sys/param.h> #include <sys/errno.h> #include <sys/systm.h> #include <sys/mbuf.h> #include <sys/ioctl.h> #include <sys/queue.h> #include <sys/socket.h> #include <sys/socketvar.h> #include <sys/protosw.h> #include <sys/kauth.h> #include <sys/kmem.h> #include <sys/sysctl.h> #include <net/if.h> #include <net/route.h> #include <net/if_ether.h> #include <net/net_stats.h> #include <netinet/in.h> #include <netatalk/at.h> #include <netatalk/at_var.h> #include <netatalk/ddp_var.h> #include <netatalk/ddp_private.h> #include <netatalk/aarp.h> #include <netatalk/at_extern.h> static void at_pcbdisconnect(struct ddpcb *); static void at_sockaddr(struct ddpcb *, struct sockaddr_at *); static int at_pcbsetaddr(struct ddpcb *, struct sockaddr_at *); static int at_pcbconnect(struct ddpcb *, struct sockaddr_at *); static void ddp_detach(struct socket *); struct ifqueue atintrq1, atintrq2; struct ddpcb *ddp_ports[ATPORT_LAST]; struct ddpcb *ddpcb = NULL; percpu_t *ddpstat_percpu; struct at_ifaddrhead at_ifaddr; /* Here as inited in this file */ u_long ddp_sendspace = DDP_MAXSZ; /* Max ddp size + 1 (ddp_type) */ u_long ddp_recvspace = 25 * (587 + sizeof(struct sockaddr_at)); #ifdef MBUFTRACE struct mowner atalk_rx_mowner = MOWNER_INIT("atalk", "rx"); struct mowner atalk_tx_mowner = MOWNER_INIT("atalk", "tx"); #endif static void at_sockaddr(struct ddpcb *ddp, struct sockaddr_at *addr) { *addr = ddp->ddp_lsat; } static int at_pcbsetaddr(struct ddpcb *ddp, struct sockaddr_at *sat) { struct sockaddr_at lsat; struct at_ifaddr *aa; struct ddpcb *ddpp; if (ddp->ddp_lsat.sat_port != ATADDR_ANYPORT) { /* shouldn't be bound */ return (EINVAL); } if (NULL != sat) { /* validate passed address */ if (sat->sat_family != AF_APPLETALK) return (EAFNOSUPPORT); if (sat->sat_len != sizeof(*sat)) return EINVAL; if (sat->sat_addr.s_node != ATADDR_ANYNODE || sat->sat_addr.s_net != ATADDR_ANYNET) { TAILQ_FOREACH(aa, &at_ifaddr, aa_list) { if ((sat->sat_addr.s_net == AA_SAT(aa)->sat_addr.s_net) && (sat->sat_addr.s_node == AA_SAT(aa)->sat_addr.s_node)) break; } if (!aa) return (EADDRNOTAVAIL); } if (sat->sat_port != ATADDR_ANYPORT) { int error; if (sat->sat_port < ATPORT_FIRST || sat->sat_port >= ATPORT_LAST) return (EINVAL); if (sat->sat_port < ATPORT_RESERVED && (error = kauth_authorize_network( kauth_cred_get(), KAUTH_NETWORK_BIND, KAUTH_REQ_NETWORK_BIND_PRIVPORT, ddpcb->ddp_socket, sat, NULL)) != 0) return (error); } } else { memset((void *) & lsat, 0, sizeof(struct sockaddr_at)); lsat.sat_len = sizeof(struct sockaddr_at); lsat.sat_addr.s_node = ATADDR_ANYNODE; lsat.sat_addr.s_net = ATADDR_ANYNET; lsat.sat_family = AF_APPLETALK; sat = &lsat; } if (sat->sat_addr.s_node == ATADDR_ANYNODE && sat->sat_addr.s_net == ATADDR_ANYNET) { if (TAILQ_EMPTY(&at_ifaddr)) return EADDRNOTAVAIL; sat->sat_addr = AA_SAT(TAILQ_FIRST(&at_ifaddr))->sat_addr; } ddp->ddp_lsat = *sat; /* * Choose port. */ if (sat->sat_port == ATADDR_ANYPORT) { for (sat->sat_port = ATPORT_RESERVED; sat->sat_port < ATPORT_LAST; sat->sat_port++) { if (ddp_ports[sat->sat_port - 1] == 0) break; } if (sat->sat_port == ATPORT_LAST) { return (EADDRNOTAVAIL); } ddp->ddp_lsat.sat_port = sat->sat_port; ddp_ports[sat->sat_port - 1] = ddp; } else { for (ddpp = ddp_ports[sat->sat_port - 1]; ddpp; ddpp = ddpp->ddp_pnext) { if (ddpp->ddp_lsat.sat_addr.s_net == sat->sat_addr.s_net && ddpp->ddp_lsat.sat_addr.s_node == sat->sat_addr.s_node) break; } if (ddpp != NULL) return (EADDRINUSE); ddp->ddp_pnext = ddp_ports[sat->sat_port - 1]; ddp_ports[sat->sat_port - 1] = ddp; if (ddp->ddp_pnext) ddp->ddp_pnext->ddp_pprev = ddp; } return 0; } static int at_pcbconnect(struct ddpcb *ddp, struct sockaddr_at *sat) { struct rtentry *rt; const struct sockaddr_at *cdst; struct route *ro; struct at_ifaddr *aa; struct ifnet *ifp; u_short hintnet = 0, net; if (sat->sat_family != AF_APPLETALK) return EAFNOSUPPORT; if (sat->sat_len != sizeof(*sat)) return EINVAL; /* * Under phase 2, network 0 means "the network". We take "the * network" to mean the network the control block is bound to. * If the control block is not bound, there is an error. */ if (sat->sat_addr.s_net == ATADDR_ANYNET && sat->sat_addr.s_node != ATADDR_ANYNODE) { if (ddp->ddp_lsat.sat_port == ATADDR_ANYPORT) { return EADDRNOTAVAIL; } hintnet = ddp->ddp_lsat.sat_addr.s_net; } ro = &ddp->ddp_route; /* * If we've got an old route for this pcb, check that it is valid. * If we've changed our address, we may have an old "good looking" * route here. Attempt to detect it. */ if ((rt = rtcache_validate(ro)) != NULL || (rt = rtcache_update(ro, 1)) != NULL) { if (hintnet) { net = hintnet; } else { net = sat->sat_addr.s_net; } if ((ifp = rt->rt_ifp) != NULL) { TAILQ_FOREACH(aa, &at_ifaddr, aa_list) { if (aa->aa_ifp == ifp && ntohs(net) >= ntohs(aa->aa_firstnet) && ntohs(net) <= ntohs(aa->aa_lastnet)) { break; } } } else aa = NULL; cdst = satocsat(rtcache_getdst(ro)); if (aa == NULL || (cdst->sat_addr.s_net != (hintnet ? hintnet : sat->sat_addr.s_net) || cdst->sat_addr.s_node != sat->sat_addr.s_node)) { rtcache_unref(rt, ro); rtcache_free(ro); rt = NULL; } } /* * If we've got no route for this interface, try to find one. */ if (rt == NULL) { union { struct sockaddr dst; struct sockaddr_at dsta; } u; sockaddr_at_init(&u.dsta, &sat->sat_addr, 0); if (hintnet) u.dsta.sat_addr.s_net = hintnet; rt = rtcache_lookup(ro, &u.dst); } /* * Make sure any route that we have has a valid interface. */ if (rt != NULL && (ifp = rt->rt_ifp) != NULL) { TAILQ_FOREACH(aa, &at_ifaddr, aa_list) { if (aa->aa_ifp == ifp) break; } } else aa = NULL; rtcache_unref(rt, ro); if (aa == NULL) return ENETUNREACH; ddp->ddp_fsat = *sat; if (ddp->ddp_lsat.sat_port == ATADDR_ANYPORT) return at_pcbsetaddr(ddp, NULL); return 0; } static void at_pcbdisconnect(struct ddpcb *ddp) { ddp->ddp_fsat.sat_addr.s_net = ATADDR_ANYNET; ddp->ddp_fsat.sat_addr.s_node = ATADDR_ANYNODE; ddp->ddp_fsat.sat_port = ATADDR_ANYPORT; } static int ddp_attach(struct socket *so, int proto) { struct ddpcb *ddp; int error; KASSERT(sotoddpcb(so) == NULL); sosetlock(so); #ifdef MBUFTRACE so->so_rcv.sb_mowner = &atalk_rx_mowner; so->so_snd.sb_mowner = &atalk_tx_mowner; #endif error = soreserve(so, ddp_sendspace, ddp_recvspace); if (error) { return error; } ddp = kmem_zalloc(sizeof(*ddp), KM_SLEEP); ddp->ddp_lsat.sat_port = ATADDR_ANYPORT; ddp->ddp_next = ddpcb; ddp->ddp_prev = NULL; ddp->ddp_pprev = NULL; ddp->ddp_pnext = NULL; if (ddpcb) { ddpcb->ddp_prev = ddp; } ddpcb = ddp; ddp->ddp_socket = so; so->so_pcb = ddp; return 0; } static void ddp_detach(struct socket *so) { struct ddpcb *ddp = sotoddpcb(so); soisdisconnected(so); so->so_pcb = NULL; /* sofree drops the lock */ sofree(so); mutex_enter(softnet_lock); /* remove ddp from ddp_ports list */ if (ddp->ddp_lsat.sat_port != ATADDR_ANYPORT && ddp_ports[ddp->ddp_lsat.sat_port - 1] != NULL) { if (ddp->ddp_pprev != NULL) { ddp->ddp_pprev->ddp_pnext = ddp->ddp_pnext; } else { ddp_ports[ddp->ddp_lsat.sat_port - 1] = ddp->ddp_pnext; } if (ddp->ddp_pnext != NULL) { ddp->ddp_pnext->ddp_pprev = ddp->ddp_pprev; } } rtcache_free(&ddp->ddp_route); if (ddp->ddp_prev) { ddp->ddp_prev->ddp_next = ddp->ddp_next; } else { ddpcb = ddp->ddp_next; } if (ddp->ddp_next) { ddp->ddp_next->ddp_prev = ddp->ddp_prev; } kmem_free(ddp, sizeof(*ddp)); } static int ddp_accept(struct socket *so, struct sockaddr *nam) { KASSERT(solocked(so)); return EOPNOTSUPP; } static int ddp_bind(struct socket *so, struct sockaddr *nam, struct lwp *l) { KASSERT(solocked(so)); KASSERT(sotoddpcb(so) != NULL); return at_pcbsetaddr(sotoddpcb(so), (struct sockaddr_at *)nam); } static int ddp_listen(struct socket *so, struct lwp *l) { KASSERT(solocked(so)); return EOPNOTSUPP; } static int ddp_connect(struct socket *so, struct sockaddr *nam, struct lwp *l) { struct ddpcb *ddp = sotoddpcb(so); int error = 0; KASSERT(solocked(so)); KASSERT(ddp != NULL); KASSERT(nam != NULL); if (ddp->ddp_fsat.sat_port != ATADDR_ANYPORT) return EISCONN; error = at_pcbconnect(ddp, (struct sockaddr_at *)nam); if (error == 0) soisconnected(so); return error; } static int ddp_connect2(struct socket *so, struct socket *so2) { KASSERT(solocked(so)); return EOPNOTSUPP; } static int ddp_disconnect(struct socket *so) { struct ddpcb *ddp = sotoddpcb(so); KASSERT(solocked(so)); KASSERT(ddp != NULL); if (ddp->ddp_fsat.sat_addr.s_node == ATADDR_ANYNODE) return ENOTCONN; at_pcbdisconnect(ddp); soisdisconnected(so); return 0; } static int ddp_shutdown(struct socket *so) { KASSERT(solocked(so)); socantsendmore(so); return 0; } static int ddp_abort(struct socket *so) { KASSERT(solocked(so)); soisdisconnected(so); ddp_detach(so); return 0; } static int ddp_ioctl(struct socket *so, u_long cmd, void *addr, struct ifnet *ifp) { return at_control(cmd, addr, ifp); } static int ddp_stat(struct socket *so, struct stat *ub) { KASSERT(solocked(so)); /* stat: don't bother with a blocksize. */ return 0; } static int ddp_peeraddr(struct socket *so, struct sockaddr *nam) { KASSERT(solocked(so)); return EOPNOTSUPP; } static int ddp_sockaddr(struct socket *so, struct sockaddr *nam) { KASSERT(solocked(so)); KASSERT(sotoddpcb(so) != NULL); KASSERT(nam != NULL); at_sockaddr(sotoddpcb(so), (struct sockaddr_at *)nam); return 0; } static int ddp_rcvd(struct socket *so, int flags, struct lwp *l) { KASSERT(solocked(so)); return EOPNOTSUPP; } static int ddp_recvoob(struct socket *so, struct mbuf *m, int flags) { KASSERT(solocked(so)); return EOPNOTSUPP; } static int ddp_send(struct socket *so, struct mbuf *m, struct sockaddr *nam, struct mbuf *control, struct lwp *l) { struct ddpcb *ddp = sotoddpcb(so); int error = 0; int s = 0; /* XXX gcc 4.8 warns on sgimips */ KASSERT(solocked(so)); KASSERT(ddp != NULL); if (nam) { if (ddp->ddp_fsat.sat_port != ATADDR_ANYPORT) return EISCONN; s = splnet(); error = at_pcbconnect(ddp, (struct sockaddr_at *)nam); if (error) { splx(s); return error; } } else { if (ddp->ddp_fsat.sat_port == ATADDR_ANYPORT) return ENOTCONN; } error = ddp_output(m, ddp); m = NULL; if (nam) { at_pcbdisconnect(ddp); splx(s); } return error; } static int ddp_sendoob(struct socket *so, struct mbuf *m, struct mbuf *control) { KASSERT(solocked(so)); m_freem(m); m_freem(control); return EOPNOTSUPP; } static int ddp_purgeif(struct socket *so, struct ifnet *ifp) { mutex_enter(softnet_lock); at_purgeif(ifp); mutex_exit(softnet_lock); return 0; } /* * For the moment, this just find the pcb with the correct local address. * In the future, this will actually do some real searching, so we can use * the sender's address to do de-multiplexing on a single port to many * sockets (pcbs). */ struct ddpcb * ddp_search( struct sockaddr_at *from, struct sockaddr_at *to, struct at_ifaddr *aa) { struct ddpcb *ddp; /* * Check for bad ports. */ if (to->sat_port < ATPORT_FIRST || to->sat_port >= ATPORT_LAST) return NULL; /* * Make sure the local address matches the sent address. What about * the interface? */ for (ddp = ddp_ports[to->sat_port - 1]; ddp; ddp = ddp->ddp_pnext) { /* XXX should we handle 0.YY? */ /* XXXX.YY to socket on destination interface */ if (to->sat_addr.s_net == ddp->ddp_lsat.sat_addr.s_net && to->sat_addr.s_node == ddp->ddp_lsat.sat_addr.s_node) { break; } /* 0.255 to socket on receiving interface */ if (to->sat_addr.s_node == ATADDR_BCAST && (to->sat_addr.s_net == 0 || to->sat_addr.s_net == ddp->ddp_lsat.sat_addr.s_net) && ddp->ddp_lsat.sat_addr.s_net == AA_SAT(aa)->sat_addr.s_net) { break; } /* XXXX.0 to socket on destination interface */ if (to->sat_addr.s_net == aa->aa_firstnet && to->sat_addr.s_node == 0 && ntohs(ddp->ddp_lsat.sat_addr.s_net) >= ntohs(aa->aa_firstnet) && ntohs(ddp->ddp_lsat.sat_addr.s_net) <= ntohs(aa->aa_lastnet)) { break; } } return (ddp); } /* * Initialize all the ddp & appletalk stuff */ void ddp_init(void) { ddpstat_percpu = percpu_alloc(sizeof(uint64_t) * DDP_NSTATS); TAILQ_INIT(&at_ifaddr); atintrq1.ifq_maxlen = IFQ_MAXLEN; atintrq2.ifq_maxlen = IFQ_MAXLEN; IFQ_LOCK_INIT(&atintrq1); IFQ_LOCK_INIT(&atintrq2); MOWNER_ATTACH(&atalk_tx_mowner); MOWNER_ATTACH(&atalk_rx_mowner); MOWNER_ATTACH(&aarp_mowner); } PR_WRAP_USRREQS(ddp) #define ddp_attach ddp_attach_wrapper #define ddp_detach ddp_detach_wrapper #define ddp_accept ddp_accept_wrapper #define ddp_bind ddp_bind_wrapper #define ddp_listen ddp_listen_wrapper #define ddp_connect ddp_connect_wrapper #define ddp_connect2 ddp_connect2_wrapper #define ddp_disconnect ddp_disconnect_wrapper #define ddp_shutdown ddp_shutdown_wrapper #define ddp_abort ddp_abort_wrapper #define ddp_ioctl ddp_ioctl_wrapper #define ddp_stat ddp_stat_wrapper #define ddp_peeraddr ddp_peeraddr_wrapper #define ddp_sockaddr ddp_sockaddr_wrapper #define ddp_rcvd ddp_rcvd_wrapper #define ddp_recvoob ddp_recvoob_wrapper #define ddp_send ddp_send_wrapper #define ddp_sendoob ddp_sendoob_wrapper #define ddp_purgeif ddp_purgeif_wrapper const struct pr_usrreqs ddp_usrreqs = { .pr_attach = ddp_attach, .pr_detach = ddp_detach, .pr_accept = ddp_accept, .pr_bind = ddp_bind, .pr_listen = ddp_listen, .pr_connect = ddp_connect, .pr_connect2 = ddp_connect2, .pr_disconnect = ddp_disconnect, .pr_shutdown = ddp_shutdown, .pr_abort = ddp_abort, .pr_ioctl = ddp_ioctl, .pr_stat = ddp_stat, .pr_peeraddr = ddp_peeraddr, .pr_sockaddr = ddp_sockaddr, .pr_rcvd = ddp_rcvd, .pr_recvoob = ddp_recvoob, .pr_send = ddp_send, .pr_sendoob = ddp_sendoob, .pr_purgeif = ddp_purgeif, }; static int sysctl_net_atalk_ddp_stats(SYSCTLFN_ARGS) { return (NETSTAT_SYSCTL(ddpstat_percpu, DDP_NSTATS)); } /* * Sysctl for DDP variables. */ SYSCTL_SETUP(sysctl_net_atalk_ddp_setup, "sysctl net.atalk.ddp subtree setup") { sysctl_createv(clog, 0, NULL, NULL, CTLFLAG_PERMANENT, CTLTYPE_NODE, "atalk", NULL, NULL, 0, NULL, 0, CTL_NET, PF_APPLETALK, CTL_EOL); sysctl_createv(clog, 0, NULL, NULL, CTLFLAG_PERMANENT, CTLTYPE_NODE, "ddp", SYSCTL_DESCR("DDP related settings"), NULL, 0, NULL, 0, CTL_NET, PF_APPLETALK, ATPROTO_DDP, CTL_EOL); sysctl_createv(clog, 0, NULL, NULL, CTLFLAG_PERMANENT, CTLTYPE_STRUCT, "stats", SYSCTL_DESCR("DDP statistics"), sysctl_net_atalk_ddp_stats, 0, NULL, 0, CTL_NET, PF_APPLETALK, ATPROTO_DDP, CTL_CREATE, CTL_EOL); } |
4 4 4 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 | /* $NetBSD: strnlen.c,v 1.2 2014/01/09 11:25:11 apb Exp $ */ /*- * Copyright (c) 2009 David Schultz <das@FreeBSD.org> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #if HAVE_NBTOOL_CONFIG_H #include "nbtool_config.h" #endif #include <sys/cdefs.h> #if defined(LIBC_SCCS) && !defined(lint) __RCSID("$NetBSD: strnlen.c,v 1.2 2014/01/09 11:25:11 apb Exp $"); #endif /* LIBC_SCCS and not lint */ /* FreeBSD: src/lib/libc/string/strnlen.c,v 1.1 2009/02/28 06:00:58 das Exp */ #if !defined(_KERNEL) && !defined(_STANDALONE) #include <string.h> #else #include <lib/libkern/libkern.h> #endif #if !HAVE_STRNLEN size_t strnlen(const char *s, size_t maxlen) { size_t len; for (len = 0; len < maxlen; len++, s++) { if (!*s) break; } return (len); } #endif /* !HAVE_STRNLEN */ |
29 38 16 14 10 9 10 10 14 9 8 10 10 7 14 6 5 6 3 4 3 2 10 7 7 4 10 9 9 10 3 18 16 16 4 3 2 17 30 19 7 5 10 8 10 1 8 8 8 1 7 7 7 2 2 7 8 8 1 9 28 10 3 8 7 4 5 5 8 9 3 2 3 3 9 7 1 6 6 5 7 16 16 12 12 10 5 5 11 11 2 9 15 11 11 5 1 1 5 5 5 5 5 1 15 9 9 5 4 2 2 4 3 8 4 2 16 16 16 16 5 15 14 24 12 13 9 23 16 9 16 10 7 9 23 21 22 19 19 12 4 17 16 18 17 16 12 3 2 16 17 8 16 10 2 11 15 15 16 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 | /* $NetBSD: kern_time.c,v 1.217 2022/07/01 21:22:44 riastradh Exp $ */ /*- * Copyright (c) 2000, 2004, 2005, 2007, 2008, 2009, 2020 * The NetBSD Foundation, Inc. * All rights reserved. * * This code is derived from software contributed to The NetBSD Foundation * by Christopher G. Demetriou, by Andrew Doran, and by Jason R. Thorpe. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ /* * Copyright (c) 1982, 1986, 1989, 1993 * The Regents of the University of California. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * @(#)kern_time.c 8.4 (Berkeley) 5/26/95 */ #include <sys/cdefs.h> __KERNEL_RCSID(0, "$NetBSD: kern_time.c,v 1.217 2022/07/01 21:22:44 riastradh Exp $"); #include <sys/param.h> #include <sys/resourcevar.h> #include <sys/kernel.h> #include <sys/systm.h> #include <sys/proc.h> #include <sys/vnode.h> #include <sys/signalvar.h> #include <sys/syslog.h> #include <sys/timetc.h> #include <sys/timex.h> #include <sys/kauth.h> #include <sys/mount.h> #include <sys/syscallargs.h> #include <sys/cpu.h> kmutex_t itimer_mutex __cacheline_aligned; /* XXX static */ static struct itlist itimer_realtime_changed_notify; static void ptimer_intr(void *); static void *ptimer_sih __read_mostly; static TAILQ_HEAD(, ptimer) ptimer_queue; #define CLOCK_VIRTUAL_P(clockid) \ ((clockid) == CLOCK_VIRTUAL || (clockid) == CLOCK_PROF) CTASSERT(ITIMER_REAL == CLOCK_REALTIME); CTASSERT(ITIMER_VIRTUAL == CLOCK_VIRTUAL); CTASSERT(ITIMER_PROF == CLOCK_PROF); CTASSERT(ITIMER_MONOTONIC == CLOCK_MONOTONIC); #define DELAYTIMER_MAX 32 /* * Initialize timekeeping. */ void time_init(void) { mutex_init(&itimer_mutex, MUTEX_DEFAULT, IPL_SCHED); LIST_INIT(&itimer_realtime_changed_notify); TAILQ_INIT(&ptimer_queue); ptimer_sih = softint_establish(SOFTINT_CLOCK | SOFTINT_MPSAFE, ptimer_intr, NULL); } /* * Check if the time will wrap if set to ts. * * ts - timespec describing the new time * delta - the delta between the current time and ts */ bool time_wraps(struct timespec *ts, struct timespec *delta) { /* * Don't allow the time to be set forward so far it * will wrap and become negative, thus allowing an * attacker to bypass the next check below. The * cutoff is 1 year before rollover occurs, so even * if the attacker uses adjtime(2) to move the time * past the cutoff, it will take a very long time * to get to the wrap point. */ if ((ts->tv_sec > LLONG_MAX - 365*24*60*60) || (delta->tv_sec < 0 || delta->tv_nsec < 0)) return true; return false; } /* * itimer_lock: * * Acquire the interval timer data lock. */ void itimer_lock(void) { mutex_spin_enter(&itimer_mutex); } /* * itimer_unlock: * * Release the interval timer data lock. */ void itimer_unlock(void) { mutex_spin_exit(&itimer_mutex); } /* * itimer_lock_held: * * Check that the interval timer lock is held for diagnostic * assertions. */ inline bool __diagused itimer_lock_held(void) { return mutex_owned(&itimer_mutex); } /* * Time of day and interval timer support. * * These routines provide the kernel entry points to get and set * the time-of-day and per-process interval timers. Subroutines * here provide support for adding and subtracting timeval structures * and decrementing interval timers, optionally reloading the interval * timers when they expire. */ /* This function is used by clock_settime and settimeofday */ static int settime1(struct proc *p, const struct timespec *ts, bool check_kauth) { struct timespec delta, now; /* * The time being set to an unreasonable value will cause * unreasonable system behaviour. */ if (ts->tv_sec < 0 || ts->tv_sec > (1LL << 36)) return EINVAL; nanotime(&now); timespecsub(ts, &now, &delta); if (check_kauth && kauth_authorize_system(kauth_cred_get(), KAUTH_SYSTEM_TIME, KAUTH_REQ_SYSTEM_TIME_SYSTEM, __UNCONST(ts), &delta, KAUTH_ARG(check_kauth ? false : true)) != 0) { return EPERM; } #ifdef notyet if ((delta.tv_sec < 86400) && securelevel > 0) { /* XXX elad - notyet */ return EPERM; } #endif tc_setclock(ts); resettodr(); /* * Notify pending CLOCK_REALTIME timers about the real time change. * There may be inactive timers on this list, but this happens * comparatively less often than timers firing, and so it's better * to put the extra checks here than to complicate the other code * path. */ struct itimer *it; itimer_lock(); LIST_FOREACH(it, &itimer_realtime_changed_notify, it_rtchgq) { KASSERT(it->it_ops->ito_realtime_changed != NULL); if (timespecisset(&it->it_time.it_value)) { (*it->it_ops->ito_realtime_changed)(it); } } itimer_unlock(); return 0; } int settime(struct proc *p, struct timespec *ts) { return settime1(p, ts, true); } /* ARGSUSED */ int sys___clock_gettime50(struct lwp *l, const struct sys___clock_gettime50_args *uap, register_t *retval) { /* { syscallarg(clockid_t) clock_id; syscallarg(struct timespec *) tp; } */ int error; struct timespec ats; error = clock_gettime1(SCARG(uap, clock_id), &ats); if (error != 0) return error; return copyout(&ats, SCARG(uap, tp), sizeof(ats)); } /* ARGSUSED */ int sys___clock_settime50(struct lwp *l, const struct sys___clock_settime50_args *uap, register_t *retval) { /* { syscallarg(clockid_t) clock_id; syscallarg(const struct timespec *) tp; } */ int error; struct timespec ats; if ((error = copyin(SCARG(uap, tp), &ats, sizeof(ats))) != 0) return error; return clock_settime1(l->l_proc, SCARG(uap, clock_id), &ats, true); } int clock_settime1(struct proc *p, clockid_t clock_id, const struct timespec *tp, bool check_kauth) { int error; if (tp->tv_nsec < 0 || tp->tv_nsec >= 1000000000L) return EINVAL; switch (clock_id) { case CLOCK_REALTIME: if ((error = settime1(p, tp, check_kauth)) != 0) return error; break; case CLOCK_MONOTONIC: return EINVAL; /* read-only clock */ default: return EINVAL; } return 0; } int sys___clock_getres50(struct lwp *l, const struct sys___clock_getres50_args *uap, register_t *retval) { /* { syscallarg(clockid_t) clock_id; syscallarg(struct timespec *) tp; } */ struct timespec ts; int error; if ((error = clock_getres1(SCARG(uap, clock_id), &ts)) != 0) return error; if (SCARG(uap, tp)) error = copyout(&ts, SCARG(uap, tp), sizeof(ts)); return error; } int clock_getres1(clockid_t clock_id, struct timespec *ts) { switch (clock_id) { case CLOCK_REALTIME: case CLOCK_MONOTONIC: ts->tv_sec = 0; if (tc_getfrequency() > 1000000000) ts->tv_nsec = 1; else ts->tv_nsec = 1000000000 / tc_getfrequency(); break; default: return EINVAL; } return 0; } /* ARGSUSED */ int sys___nanosleep50(struct lwp *l, const struct sys___nanosleep50_args *uap, register_t *retval) { /* { syscallarg(struct timespec *) rqtp; syscallarg(struct timespec *) rmtp; } */ struct timespec rmt, rqt; int error, error1; error = copyin(SCARG(uap, rqtp), &rqt, sizeof(struct timespec)); if (error) return error; error = nanosleep1(l, CLOCK_MONOTONIC, 0, &rqt, SCARG(uap, rmtp) ? &rmt : NULL); if (SCARG(uap, rmtp) == NULL || (error != 0 && error != EINTR)) return error; error1 = copyout(&rmt, SCARG(uap, rmtp), sizeof(rmt)); return error1 ? error1 : error; } /* ARGSUSED */ int sys_clock_nanosleep(struct lwp *l, const struct sys_clock_nanosleep_args *uap, register_t *retval) { /* { syscallarg(clockid_t) clock_id; syscallarg(int) flags; syscallarg(struct timespec *) rqtp; syscallarg(struct timespec *) rmtp; } */ struct timespec rmt, rqt; int error, error1; error = copyin(SCARG(uap, rqtp), &rqt, sizeof(struct timespec)); if (error) goto out; error = nanosleep1(l, SCARG(uap, clock_id), SCARG(uap, flags), &rqt, SCARG(uap, rmtp) ? &rmt : NULL); if (SCARG(uap, rmtp) == NULL || (error != 0 && error != EINTR)) goto out; if ((SCARG(uap, flags) & TIMER_ABSTIME) == 0 && (error1 = copyout(&rmt, SCARG(uap, rmtp), sizeof(rmt))) != 0) error = error1; out: *retval = error; return 0; } int nanosleep1(struct lwp *l, clockid_t clock_id, int flags, struct timespec *rqt, struct timespec *rmt) { struct timespec rmtstart; int error, timo; if ((error = ts2timo(clock_id, flags, rqt, &timo, &rmtstart)) != 0) { if (error == ETIMEDOUT) { error = 0; if (rmt != NULL) rmt->tv_sec = rmt->tv_nsec = 0; } return error; } /* * Avoid inadvertently sleeping forever */ if (timo == 0) timo = 1; again: error = kpause("nanoslp", true, timo, NULL); if (error == EWOULDBLOCK) error = 0; if (rmt != NULL || error == 0) { struct timespec rmtend; struct timespec t0; struct timespec *t; int err; err = clock_gettime1(clock_id, &rmtend); if (err != 0) return err; t = (rmt != NULL) ? rmt : &t0; if (flags & TIMER_ABSTIME) { timespecsub(rqt, &rmtend, t); } else { if (timespeccmp(&rmtend, &rmtstart, <)) timespecclear(t); /* clock wound back */ else timespecsub(&rmtend, &rmtstart, t); if (timespeccmp(rqt, t, <)) timespecclear(t); else timespecsub(rqt, t, t); } if (t->tv_sec < 0) timespecclear(t); if (error == 0) { timo = tstohz(t); if (timo > 0) goto again; } } if (error == ERESTART) error = EINTR; return error; } int sys_clock_getcpuclockid2(struct lwp *l, const struct sys_clock_getcpuclockid2_args *uap, register_t *retval) { /* { syscallarg(idtype_t idtype; syscallarg(id_t id); syscallarg(clockid_t *)clock_id; } */ pid_t pid; lwpid_t lid; clockid_t clock_id; id_t id = SCARG(uap, id); switch (SCARG(uap, idtype)) { case P_PID: pid = id == 0 ? l->l_proc->p_pid : id; clock_id = CLOCK_PROCESS_CPUTIME_ID | pid; break; case P_LWPID: lid = id == 0 ? l->l_lid : id; clock_id = CLOCK_THREAD_CPUTIME_ID | lid; break; default: return EINVAL; } return copyout(&clock_id, SCARG(uap, clock_id), sizeof(clock_id)); } /* ARGSUSED */ int sys___gettimeofday50(struct lwp *l, const struct sys___gettimeofday50_args *uap, register_t *retval) { /* { syscallarg(struct timeval *) tp; syscallarg(void *) tzp; really "struct timezone *"; } */ struct timeval atv; int error = 0; struct timezone tzfake; if (SCARG(uap, tp)) { memset(&atv, 0, sizeof(atv)); microtime(&atv); error = copyout(&atv, SCARG(uap, tp), sizeof(atv)); if (error) return error; } if (SCARG(uap, tzp)) { /* * NetBSD has no kernel notion of time zone, so we just * fake up a timezone struct and return it if demanded. */ tzfake.tz_minuteswest = 0; tzfake.tz_dsttime = 0; error = copyout(&tzfake, SCARG(uap, tzp), sizeof(tzfake)); } return error; } /* ARGSUSED */ int sys___settimeofday50(struct lwp *l, const struct sys___settimeofday50_args *uap, register_t *retval) { /* { syscallarg(const struct timeval *) tv; syscallarg(const void *) tzp; really "const struct timezone *"; } */ return settimeofday1(SCARG(uap, tv), true, SCARG(uap, tzp), l, true); } int settimeofday1(const struct timeval *utv, bool userspace, const void *utzp, struct lwp *l, bool check_kauth) { struct timeval atv; struct timespec ts; int error; /* Verify all parameters before changing time. */ /* * NetBSD has no kernel notion of time zone, and only an * obsolete program would try to set it, so we log a warning. */ if (utzp) log(LOG_WARNING, "pid %d attempted to set the " "(obsolete) kernel time zone\n", l->l_proc->p_pid); if (utv == NULL) return 0; if (userspace) { if ((error = copyin(utv, &atv, sizeof(atv))) != 0) return error; utv = &atv; } if (utv->tv_usec < 0 || utv->tv_usec >= 1000000) return EINVAL; TIMEVAL_TO_TIMESPEC(utv, &ts); return settime1(l->l_proc, &ts, check_kauth); } int time_adjusted; /* set if an adjustment is made */ /* ARGSUSED */ int sys___adjtime50(struct lwp *l, const struct sys___adjtime50_args *uap, register_t *retval) { /* { syscallarg(const struct timeval *) delta; syscallarg(struct timeval *) olddelta; } */ int error; struct timeval atv, oldatv; if ((error = kauth_authorize_system(l->l_cred, KAUTH_SYSTEM_TIME, KAUTH_REQ_SYSTEM_TIME_ADJTIME, NULL, NULL, NULL)) != 0) return error; if (SCARG(uap, delta)) { error = copyin(SCARG(uap, delta), &atv, sizeof(*SCARG(uap, delta))); if (error) return error; } adjtime1(SCARG(uap, delta) ? &atv : NULL, SCARG(uap, olddelta) ? &oldatv : NULL, l->l_proc); if (SCARG(uap, olddelta)) error = copyout(&oldatv, SCARG(uap, olddelta), sizeof(*SCARG(uap, olddelta))); return error; } void adjtime1(const struct timeval *delta, struct timeval *olddelta, struct proc *p) { extern int64_t time_adjtime; /* in kern_ntptime.c */ if (olddelta) { memset(olddelta, 0, sizeof(*olddelta)); mutex_spin_enter(&timecounter_lock); olddelta->tv_sec = time_adjtime / 1000000; olddelta->tv_usec = time_adjtime % 1000000; if (olddelta->tv_usec < 0) { olddelta->tv_usec += 1000000; olddelta->tv_sec--; } mutex_spin_exit(&timecounter_lock); } if (delta) { mutex_spin_enter(&timecounter_lock); /* * XXX This should maybe just report failure to * userland for nonsense deltas. */ if (delta->tv_sec > INT64_MAX/1000000 - 1) { time_adjtime = INT64_MAX; } else if (delta->tv_sec < INT64_MIN/1000000 + 1) { time_adjtime = INT64_MIN; } else { time_adjtime = delta->tv_sec * 1000000 + MAX(-999999, MIN(999999, delta->tv_usec)); } if (time_adjtime) { /* We need to save the system time during shutdown */ time_adjusted |= 1; } mutex_spin_exit(&timecounter_lock); } } /* * Interval timer support. * * The itimer_*() routines provide generic support for interval timers, * both real (CLOCK_REALTIME, CLOCK_MONOTIME), and virtual (CLOCK_VIRTUAL, * CLOCK_PROF). * * Real timers keep their deadline as an absolute time, and are fired * by a callout. Virtual timers are kept as a linked-list of deltas, * and are processed by hardclock(). * * Because the real time timer callout may be delayed in real time due * to interrupt processing on the system, it is possible for the real * time timeout routine (itimer_callout()) run past after its deadline. * It does not suffice, therefore, to reload the real timer .it_value * from the timer's .it_interval. Rather, we compute the next deadline * in absolute time based on the current time and the .it_interval value, * and report any overruns. * * Note that while the virtual timers are supported in a generic fashion * here, they only (currently) make sense as per-process timers, and thus * only really work for that case. */ /* * itimer_init: * * Initialize the common data for an interval timer. */ void itimer_init(struct itimer * const it, const struct itimer_ops * const ops, clockid_t const id, struct itlist * const itl) { KASSERT(itimer_lock_held()); KASSERT(ops != NULL); timespecclear(&it->it_time.it_value); it->it_ops = ops; it->it_clockid = id; it->it_overruns = 0; it->it_dying = false; if (!CLOCK_VIRTUAL_P(id)) { KASSERT(itl == NULL); callout_init(&it->it_ch, CALLOUT_MPSAFE); if (id == CLOCK_REALTIME && ops->ito_realtime_changed != NULL) { LIST_INSERT_HEAD(&itimer_realtime_changed_notify, it, it_rtchgq); } } else { KASSERT(itl != NULL); it->it_vlist = itl; it->it_active = false; } } /* * itimer_poison: * * Poison an interval timer, preventing it from being scheduled * or processed, in preparation for freeing the timer. */ void itimer_poison(struct itimer * const it) { KASSERT(itimer_lock_held()); it->it_dying = true; /* * For non-virtual timers, stop the callout, or wait for it to * run if it has already fired. It cannot restart again after * this point: the callout won't restart itself when dying, no * other users holding the lock can restart it, and any other * users waiting for callout_halt concurrently (itimer_settime) * will restart from the top. */ if (!CLOCK_VIRTUAL_P(it->it_clockid)) { callout_halt(&it->it_ch, &itimer_mutex); if (it->it_clockid == CLOCK_REALTIME && it->it_ops->ito_realtime_changed != NULL) { LIST_REMOVE(it, it_rtchgq); } } } /* * itimer_fini: * * Release resources used by an interval timer. * * N.B. itimer_lock must be held on entry, and is released on exit. */ void itimer_fini(struct itimer * const it) { KASSERT(itimer_lock_held()); /* All done with the global state. */ itimer_unlock(); /* Destroy the callout, if needed. */ if (!CLOCK_VIRTUAL_P(it->it_clockid)) callout_destroy(&it->it_ch); } /* * itimer_decr: * * Decrement an interval timer by a specified number of nanoseconds, * which must be less than a second, i.e. < 1000000000. If the timer * expires, then reload it. In this case, carry over (nsec - old value) * to reduce the value reloaded into the timer so that the timer does * not drift. This routine assumes that it is called in a context where * the timers on which it is operating cannot change in value. * * Returns true if the timer has expired. */ static bool itimer_decr(struct itimer *it, int nsec) { struct itimerspec *itp; int error __diagused; KASSERT(itimer_lock_held()); KASSERT(CLOCK_VIRTUAL_P(it->it_clockid)); itp = &it->it_time; if (itp->it_value.tv_nsec < nsec) { if (itp->it_value.tv_sec == 0) { /* expired, and already in next interval */ nsec -= itp->it_value.tv_nsec; goto expire; } itp->it_value.tv_nsec += 1000000000; itp->it_value.tv_sec--; } itp->it_value.tv_nsec -= nsec; nsec = 0; if (timespecisset(&itp->it_value)) return false; /* expired, exactly at end of interval */ expire: if (timespecisset(&itp->it_interval)) { itp->it_value = itp->it_interval; itp->it_value.tv_nsec -= nsec; if (itp->it_value.tv_nsec < 0) { itp->it_value.tv_nsec += 1000000000; itp->it_value.tv_sec--; } error = itimer_settime(it); KASSERT(error == 0); /* virtual, never fails */ } else itp->it_value.tv_nsec = 0; /* sec is already 0 */ return true; } static void itimer_callout(void *); /* * itimer_arm_real: * * Arm a non-virtual timer. */ static void itimer_arm_real(struct itimer * const it) { /* * Don't need to check tshzto() return value, here. * callout_reset() does it for us. */ callout_reset(&it->it_ch, (it->it_clockid == CLOCK_MONOTONIC ? tshztoup(&it->it_time.it_value) : tshzto(&it->it_time.it_value)), itimer_callout, it); } /* * itimer_callout: * * Callout to expire a non-virtual timer. Queue it up for processing, * and then reload, if it is configured to do so. * * N.B. A delay in processing this callout causes multiple * SIGALRM calls to be compressed into one. */ static void itimer_callout(void *arg) { uint64_t last_val, next_val, interval, now_ns; struct timespec now, next; struct itimer * const it = arg; int backwards; itimer_lock(); (*it->it_ops->ito_fire)(it); if (!timespecisset(&it->it_time.it_interval)) { timespecclear(&it->it_time.it_value); itimer_unlock(); return; } if (it->it_clockid == CLOCK_MONOTONIC) { getnanouptime(&now); } else { getnanotime(&now); } backwards = (timespeccmp(&it->it_time.it_value, &now, >)); /* Nonnegative interval guaranteed by itimerfix. */ KASSERT(it->it_time.it_interval.tv_sec >= 0); KASSERT(it->it_time.it_interval.tv_nsec >= 0); /* Handle the easy case of non-overflown timers first. */ if (!backwards && timespecaddok(&it->it_time.it_value, &it->it_time.it_interval)) { timespecadd(&it->it_time.it_value, &it->it_time.it_interval, &next); it->it_time.it_value = next; } else { now_ns = timespec2ns(&now); last_val = timespec2ns(&it->it_time.it_value); interval = timespec2ns(&it->it_time.it_interval); next_val = now_ns + (now_ns - last_val + interval - 1) % interval; if (backwards) next_val += interval; else it->it_overruns += (now_ns - last_val) / interval; it->it_time.it_value.tv_sec = next_val / 1000000000; it->it_time.it_value.tv_nsec = next_val % 1000000000; } /* * Reset the callout, if it's not going away. */ if (!it->it_dying) itimer_arm_real(it); itimer_unlock(); } /* * itimer_settime: * * Set up the given interval timer. The value in it->it_time.it_value * is taken to be an absolute time for CLOCK_REALTIME/CLOCK_MONOTONIC * timers and a relative time for CLOCK_VIRTUAL/CLOCK_PROF timers. * * If the callout had already fired but not yet run, fails with * ERESTART -- caller must restart from the top to look up a timer. */ int itimer_settime(struct itimer *it) { struct itimer *itn, *pitn; struct itlist *itl; KASSERT(itimer_lock_held()); if (!CLOCK_VIRTUAL_P(it->it_clockid)) { /* * Try to stop the callout. However, if it had already * fired, we have to drop the lock to wait for it, so * the world may have changed and pt may not be there * any more. In that case, tell the caller to start * over from the top. */ if (callout_halt(&it->it_ch, &itimer_mutex)) return ERESTART; /* Now we can touch it and start it up again. */ if (timespecisset(&it->it_time.it_value)) itimer_arm_real(it); } else { if (it->it_active) { itn = LIST_NEXT(it, it_list); LIST_REMOVE(it, it_list); for ( ; itn; itn = LIST_NEXT(itn, it_list)) timespecadd(&it->it_time.it_value, &itn->it_time.it_value, &itn->it_time.it_value); } if (timespecisset(&it->it_time.it_value)) { itl = it->it_vlist; for (itn = LIST_FIRST(itl), pitn = NULL; itn && timespeccmp(&it->it_time.it_value, &itn->it_time.it_value, >); pitn = itn, itn = LIST_NEXT(itn, it_list)) timespecsub(&it->it_time.it_value, &itn->it_time.it_value, &it->it_time.it_value); if (pitn) LIST_INSERT_AFTER(pitn, it, it_list); else LIST_INSERT_HEAD(itl, it, it_list); for ( ; itn ; itn = LIST_NEXT(itn, it_list)) timespecsub(&itn->it_time.it_value, &it->it_time.it_value, &itn->it_time.it_value); it->it_active = true; } else { it->it_active = false; } } /* Success! */ return 0; } /* * itimer_gettime: * * Return the remaining time of an interval timer. */ void itimer_gettime(const struct itimer *it, struct itimerspec *aits) { struct timespec now; struct itimer *itn; KASSERT(itimer_lock_held()); *aits = it->it_time; if (!CLOCK_VIRTUAL_P(it->it_clockid)) { /* * Convert from absolute to relative time in .it_value * part of real time timer. If time for real time * timer has passed return 0, else return difference * between current time and time for the timer to go * off. */ if (timespecisset(&aits->it_value)) { if (it->it_clockid == CLOCK_REALTIME) { getnanotime(&now); } else { /* CLOCK_MONOTONIC */ getnanouptime(&now); } if (timespeccmp(&aits->it_value, &now, <)) timespecclear(&aits->it_value); else timespecsub(&aits->it_value, &now, &aits->it_value); } } else if (it->it_active) { for (itn = LIST_FIRST(it->it_vlist); itn && itn != it; itn = LIST_NEXT(itn, it_list)) timespecadd(&aits->it_value, &itn->it_time.it_value, &aits->it_value); KASSERT(itn != NULL); /* it should be findable on the list */ } else timespecclear(&aits->it_value); } /* * Per-process timer support. * * Both the BSD getitimer() family and the POSIX timer_*() family of * routines are supported. * * All timers are kept in an array pointed to by p_timers, which is * allocated on demand - many processes don't use timers at all. The * first four elements in this array are reserved for the BSD timers: * element 0 is ITIMER_REAL, element 1 is ITIMER_VIRTUAL, element * 2 is ITIMER_PROF, and element 3 is ITIMER_MONOTONIC. The rest may be * allocated by the timer_create() syscall. * * These timers are a "sub-class" of interval timer. */ /* * ptimer_free: * * Free the per-process timer at the specified index. */ static void ptimer_free(struct ptimers *pts, int index) { struct itimer *it; struct ptimer *pt; KASSERT(itimer_lock_held()); it = pts->pts_timers[index]; pt = container_of(it, struct ptimer, pt_itimer); pts->pts_timers[index] = NULL; itimer_poison(it); /* * Remove it from the queue to be signalled. Must be done * after itimer is poisoned, because we may have had to wait * for the callout to complete. */ if (pt->pt_queued) { TAILQ_REMOVE(&ptimer_queue, pt, pt_chain); pt->pt_queued = false; } itimer_fini(it); /* releases itimer_lock */ kmem_free(pt, sizeof(*pt)); } /* * ptimers_alloc: * * Allocate a ptimers for the specified process. */ static struct ptimers * ptimers_alloc(struct proc *p) { struct ptimers *pts; int i; pts = kmem_alloc(sizeof(*pts), KM_SLEEP); LIST_INIT(&pts->pts_virtual); LIST_INIT(&pts->pts_prof); for (i = 0; i < TIMER_MAX; i++) pts->pts_timers[i] = NULL; itimer_lock(); if (p->p_timers == NULL) { p->p_timers = pts; itimer_unlock(); return pts; } itimer_unlock(); kmem_free(pts, sizeof(*pts)); return p->p_timers; } /* * ptimers_free: * * Clean up the per-process timers. If "which" is set to TIMERS_ALL, * then clean up all timers and free all the data structures. If * "which" is set to TIMERS_POSIX, only clean up the timers allocated * by timer_create(), not the BSD setitimer() timers, and only free the * structure if none of those remain. * * This function is exported because it is needed in the exec and * exit code paths. */ void ptimers_free(struct proc *p, int which) { struct ptimers *pts; struct itimer *itn; struct timespec ts; int i; if (p->p_timers == NULL) return; pts = p->p_timers; itimer_lock(); if (which == TIMERS_ALL) { p->p_timers = NULL; i = 0; } else { timespecclear(&ts); for (itn = LIST_FIRST(&pts->pts_virtual); itn && itn != pts->pts_timers[ITIMER_VIRTUAL]; itn = LIST_NEXT(itn, it_list)) { KASSERT(itn->it_clockid == CLOCK_VIRTUAL); timespecadd(&ts, &itn->it_time.it_value, &ts); } LIST_FIRST(&pts->pts_virtual) = NULL; if (itn) { KASSERT(itn->it_clockid == CLOCK_VIRTUAL); timespecadd(&ts, &itn->it_time.it_value, &itn->it_time.it_value); LIST_INSERT_HEAD(&pts->pts_virtual, itn, it_list); } timespecclear(&ts); for (itn = LIST_FIRST(&pts->pts_prof); itn && itn != pts->pts_timers[ITIMER_PROF]; itn = LIST_NEXT(itn, it_list)) { KASSERT(itn->it_clockid == CLOCK_PROF); timespecadd(&ts, &itn->it_time.it_value, &ts); } LIST_FIRST(&pts->pts_prof) = NULL; if (itn) { KASSERT(itn->it_clockid == CLOCK_PROF); timespecadd(&ts, &itn->it_time.it_value, &itn->it_time.it_value); LIST_INSERT_HEAD(&pts->pts_prof, itn, it_list); } i = TIMER_MIN; } for ( ; i < TIMER_MAX; i++) { if (pts->pts_timers[i] != NULL) { /* Free the timer and release the lock. */ ptimer_free(pts, i); /* Reacquire the lock for the next one. */ itimer_lock(); } } if (pts->pts_timers[0] == NULL && pts->pts_timers[1] == NULL && pts->pts_timers[2] == NULL && pts->pts_timers[3] == NULL) { p->p_timers = NULL; itimer_unlock(); kmem_free(pts, sizeof(*pts)); } else itimer_unlock(); } /* * ptimer_fire: * * Fire a per-process timer. */ static void ptimer_fire(struct itimer *it) { struct ptimer *pt = container_of(it, struct ptimer, pt_itimer); KASSERT(itimer_lock_held()); /* * XXX Can overrun, but we don't do signal queueing yet, anyway. * XXX Relying on the clock interrupt is stupid. */ if (pt->pt_ev.sigev_notify != SIGEV_SIGNAL) { return; } if (!pt->pt_queued) { TAILQ_INSERT_TAIL(&ptimer_queue, pt, pt_chain); pt->pt_queued = true; softint_schedule(ptimer_sih); } } /* * Operations vector for per-process timers (BSD and POSIX). */ static const struct itimer_ops ptimer_itimer_ops = { .ito_fire = ptimer_fire, }; /* * sys_timer_create: * * System call to create a POSIX timer. */ int sys_timer_create(struct lwp *l, const struct sys_timer_create_args *uap, register_t *retval) { /* { syscallarg(clockid_t) clock_id; syscallarg(struct sigevent *) evp; syscallarg(timer_t *) timerid; } */ return timer_create1(SCARG(uap, timerid), SCARG(uap, clock_id), SCARG(uap, evp), copyin, l); } int timer_create1(timer_t *tid, clockid_t id, struct sigevent *evp, copyin_t fetch_event, struct lwp *l) { int error; timer_t timerid; struct itlist *itl; struct ptimers *pts; struct ptimer *pt; struct proc *p; p = l->l_proc; if ((u_int)id > CLOCK_MONOTONIC) return EINVAL; if ((pts = p->p_timers) == NULL) pts = ptimers_alloc(p); pt = kmem_zalloc(sizeof(*pt), KM_SLEEP); if (evp != NULL) { if (((error = (*fetch_event)(evp, &pt->pt_ev, sizeof(pt->pt_ev))) != 0) || ((pt->pt_ev.sigev_notify < SIGEV_NONE) || (pt->pt_ev.sigev_notify > SIGEV_SA)) || (pt->pt_ev.sigev_notify == SIGEV_SIGNAL && (pt->pt_ev.sigev_signo <= 0 || pt->pt_ev.sigev_signo >= NSIG))) { kmem_free(pt, sizeof(*pt)); return (error ? error : EINVAL); } } /* Find a free timer slot, skipping those reserved for setitimer(). */ itimer_lock(); for (timerid = TIMER_MIN; timerid < TIMER_MAX; timerid++) if (pts->pts_timers[timerid] == NULL) break; if (timerid == TIMER_MAX) { itimer_unlock(); kmem_free(pt, sizeof(*pt)); return EAGAIN; } if (evp == NULL) { pt->pt_ev.sigev_notify = SIGEV_SIGNAL; switch (id) { case CLOCK_REALTIME: case CLOCK_MONOTONIC: pt->pt_ev.sigev_signo = SIGALRM; break; case CLOCK_VIRTUAL: pt->pt_ev.sigev_signo = SIGVTALRM; break; case CLOCK_PROF: pt->pt_ev.sigev_signo = SIGPROF; break; } pt->pt_ev.sigev_value.sival_int = timerid; } switch (id) { case CLOCK_VIRTUAL: itl = &pts->pts_virtual; break; case CLOCK_PROF: itl = &pts->pts_prof; break; default: itl = NULL; } itimer_init(&pt->pt_itimer, &ptimer_itimer_ops, id, itl); pt->pt_proc = p; pt->pt_poverruns = 0; pt->pt_entry = timerid; pt->pt_queued = false; pts->pts_timers[timerid] = &pt->pt_itimer; itimer_unlock(); return copyout(&timerid, tid, sizeof(timerid)); } /* * sys_timer_delete: * * System call to delete a POSIX timer. */ int sys_timer_delete(struct lwp *l, const struct sys_timer_delete_args *uap, register_t *retval) { /* { syscallarg(timer_t) timerid; } */ struct proc *p = l->l_proc; timer_t timerid; struct ptimers *pts; struct itimer *it, *itn; timerid = SCARG(uap, timerid); pts = p->p_timers; if (pts == NULL || timerid < 2 || timerid >= TIMER_MAX) return EINVAL; itimer_lock(); if ((it = pts->pts_timers[timerid]) == NULL) { itimer_unlock(); return EINVAL; } if (CLOCK_VIRTUAL_P(it->it_clockid)) { if (it->it_active) { itn = LIST_NEXT(it, it_list); LIST_REMOVE(it, it_list); for ( ; itn; itn = LIST_NEXT(itn, it_list)) timespecadd(&it->it_time.it_value, &itn->it_time.it_value, &itn->it_time.it_value); it->it_active = false; } } /* Free the timer and release the lock. */ ptimer_free(pts, timerid); return 0; } /* * sys___timer_settime50: * * System call to set/arm a POSIX timer. */ int sys___timer_settime50(struct lwp *l, const struct sys___timer_settime50_args *uap, register_t *retval) { /* { syscallarg(timer_t) timerid; syscallarg(int) flags; syscallarg(const struct itimerspec *) value; syscallarg(struct itimerspec *) ovalue; } */ int error; struct itimerspec value, ovalue, *ovp = NULL; if ((error = copyin(SCARG(uap, value), &value, sizeof(struct itimerspec))) != 0) return error; if (SCARG(uap, ovalue)) ovp = &ovalue; if ((error = dotimer_settime(SCARG(uap, timerid), &value, ovp, SCARG(uap, flags), l->l_proc)) != 0) return error; if (ovp) return copyout(&ovalue, SCARG(uap, ovalue), sizeof(struct itimerspec)); return 0; } int dotimer_settime(int timerid, struct itimerspec *value, struct itimerspec *ovalue, int flags, struct proc *p) { struct timespec now; struct itimerspec val, oval; struct ptimers *pts; struct itimer *it; int error; pts = p->p_timers; if (pts == NULL || timerid < 2 || timerid >= TIMER_MAX) return EINVAL; val = *value; if ((error = itimespecfix(&val.it_value)) != 0 || (error = itimespecfix(&val.it_interval)) != 0) return error; itimer_lock(); restart: if ((it = pts->pts_timers[timerid]) == NULL) { itimer_unlock(); return EINVAL; } oval = it->it_time; it->it_time = val; /* * If we've been passed a relative time for a realtime timer, * convert it to absolute; if an absolute time for a virtual * timer, convert it to relative and make sure we don't set it * to zero, which would cancel the timer, or let it go * negative, which would confuse the comparison tests. */ if (timespecisset(&it->it_time.it_value)) { if (!CLOCK_VIRTUAL_P(it->it_clockid)) { if ((flags & TIMER_ABSTIME) == 0) { if (it->it_clockid == CLOCK_REALTIME) { getnanotime(&now); } else { /* CLOCK_MONOTONIC */ getnanouptime(&now); } timespecadd(&it->it_time.it_value, &now, &it->it_time.it_value); } } else { if ((flags & TIMER_ABSTIME) != 0) { getnanotime(&now); timespecsub(&it->it_time.it_value, &now, &it->it_time.it_value); if (!timespecisset(&it->it_time.it_value) || it->it_time.it_value.tv_sec < 0) { it->it_time.it_value.tv_sec = 0; it->it_time.it_value.tv_nsec = 1; } } } } error = itimer_settime(it); if (error == ERESTART) { KASSERT(!CLOCK_VIRTUAL_P(it->it_clockid)); goto restart; } KASSERT(error == 0); itimer_unlock(); if (ovalue) *ovalue = oval; return 0; } /* * sys___timer_gettime50: * * System call to return the time remaining until a POSIX timer fires. */ int sys___timer_gettime50(struct lwp *l, const struct sys___timer_gettime50_args *uap, register_t *retval) { /* { syscallarg(timer_t) timerid; syscallarg(struct itimerspec *) value; } */ struct itimerspec its; int error; if ((error = dotimer_gettime(SCARG(uap, timerid), l->l_proc, &its)) != 0) return error; return copyout(&its, SCARG(uap, value), sizeof(its)); } int dotimer_gettime(int timerid, struct proc *p, struct itimerspec *its) { struct itimer *it; struct ptimers *pts; pts = p->p_timers; if (pts == NULL || timerid < 2 || timerid >= TIMER_MAX) return EINVAL; itimer_lock(); if ((it = pts->pts_timers[timerid]) == NULL) { itimer_unlock(); return EINVAL; } itimer_gettime(it, its); itimer_unlock(); return 0; } /* * sys_timer_getoverrun: * * System call to return the number of times a POSIX timer has * expired while a notification was already pending. The counter * is reset when a timer expires and a notification can be posted. */ int sys_timer_getoverrun(struct lwp *l, const struct sys_timer_getoverrun_args *uap, register_t *retval) { /* { syscallarg(timer_t) timerid; } */ struct proc *p = l->l_proc; struct ptimers *pts; int timerid; struct itimer *it; struct ptimer *pt; timerid = SCARG(uap, timerid); pts = p->p_timers; if (pts == NULL || timerid < 2 || timerid >= TIMER_MAX) return EINVAL; itimer_lock(); if ((it = pts->pts_timers[timerid]) == NULL) { itimer_unlock(); return EINVAL; } pt = container_of(it, struct ptimer, pt_itimer); *retval = pt->pt_poverruns; if (*retval >= DELAYTIMER_MAX) *retval = DELAYTIMER_MAX; itimer_unlock(); return 0; } /* * sys___getitimer50: * * System call to get the time remaining before a BSD timer fires. */ int sys___getitimer50(struct lwp *l, const struct sys___getitimer50_args *uap, register_t *retval) { /* { syscallarg(int) which; syscallarg(struct itimerval *) itv; } */ struct proc *p = l->l_proc; struct itimerval aitv; int error; memset(&aitv, 0, sizeof(aitv)); error = dogetitimer(p, SCARG(uap, which), &aitv); if (error) return error; return copyout(&aitv, SCARG(uap, itv), sizeof(struct itimerval)); } int dogetitimer(struct proc *p, int which, struct itimerval *itvp) { struct ptimers *pts; struct itimer *it; struct itimerspec its; if ((u_int)which > ITIMER_MONOTONIC) return EINVAL; itimer_lock(); pts = p->p_timers; if (pts == NULL || (it = pts->pts_timers[which]) == NULL) { timerclear(&itvp->it_value); timerclear(&itvp->it_interval); } else { itimer_gettime(it, &its); TIMESPEC_TO_TIMEVAL(&itvp->it_value, &its.it_value); TIMESPEC_TO_TIMEVAL(&itvp->it_interval, &its.it_interval); } itimer_unlock(); return 0; } /* * sys___setitimer50: * * System call to set/arm a BSD timer. */ int sys___setitimer50(struct lwp *l, const struct sys___setitimer50_args *uap, register_t *retval) { /* { syscallarg(int) which; syscallarg(const struct itimerval *) itv; syscallarg(struct itimerval *) oitv; } */ struct proc *p = l->l_proc; int which = SCARG(uap, which); struct sys___getitimer50_args getargs; const struct itimerval *itvp; struct itimerval aitv; int error; itvp = SCARG(uap, itv); if (itvp && (error = copyin(itvp, &aitv, sizeof(struct itimerval))) != 0) return error; if (SCARG(uap, oitv) != NULL) { SCARG(&getargs, which) = which; SCARG(&getargs, itv) = SCARG(uap, oitv); if ((error = sys___getitimer50(l, &getargs, retval)) != 0) return error; } if (itvp == 0) return 0; return dosetitimer(p, which, &aitv); } int dosetitimer(struct proc *p, int which, struct itimerval *itvp) { struct timespec now; struct ptimers *pts; struct ptimer *spare; struct itimer *it; struct itlist *itl; int error; if ((u_int)which > ITIMER_MONOTONIC) return EINVAL; if (itimerfix(&itvp->it_value) || itimerfix(&itvp->it_interval)) return EINVAL; /* * Don't bother allocating data structures if the process just * wants to clear the timer. */ spare = NULL; pts = p->p_timers; retry: if (!timerisset(&itvp->it_value) && (pts == NULL || pts->pts_timers[which] == NULL)) return 0; if (pts == NULL) pts = ptimers_alloc(p); itimer_lock(); restart: it = pts->pts_timers[which]; if (it == NULL) { struct ptimer *pt; if (spare == NULL) { itimer_unlock(); spare = kmem_zalloc(sizeof(*spare), KM_SLEEP); goto retry; } pt = spare; spare = NULL; it = &pt->pt_itimer; pt->pt_ev.sigev_notify = SIGEV_SIGNAL; pt->pt_ev.sigev_value.sival_int = which; switch (which) { case ITIMER_REAL: case ITIMER_MONOTONIC: itl = NULL; pt->pt_ev.sigev_signo = SIGALRM; break; case ITIMER_VIRTUAL: itl = &pts->pts_virtual; pt->pt_ev.sigev_signo = SIGVTALRM; break; case ITIMER_PROF: itl = &pts->pts_prof; pt->pt_ev.sigev_signo = SIGPROF; break; default: panic("%s: can't happen %d", __func__, which); } itimer_init(it, &ptimer_itimer_ops, which, itl); pt->pt_proc = p; pt->pt_entry = which; pts->pts_timers[which] = it; } TIMEVAL_TO_TIMESPEC(&itvp->it_value, &it->it_time.it_value); TIMEVAL_TO_TIMESPEC(&itvp->it_interval, &it->it_time.it_interval); error = 0; if (timespecisset(&it->it_time.it_value)) { /* Convert to absolute time */ /* XXX need to wrap in splclock for timecounters case? */ switch (which) { case ITIMER_REAL: getnanotime(&now); if (!timespecaddok(&it->it_time.it_value, &now)) { error = EINVAL; goto out; } timespecadd(&it->it_time.it_value, &now, &it->it_time.it_value); break; case ITIMER_MONOTONIC: getnanouptime(&now); if (!timespecaddok(&it->it_time.it_value, &now)) { error = EINVAL; goto out; } timespecadd(&it->it_time.it_value, &now, &it->it_time.it_value); break; default: break; } } error = itimer_settime(it); if (error == ERESTART) { KASSERT(!CLOCK_VIRTUAL_P(it->it_clockid)); goto restart; } KASSERT(error == 0); out: itimer_unlock(); if (spare != NULL) kmem_free(spare, sizeof(*spare)); return error; } /* * ptimer_tick: * * Called from hardclock() to decrement per-process virtual timers. */ void ptimer_tick(lwp_t *l, bool user) { struct ptimers *pts; struct itimer *it; proc_t *p; p = l->l_proc; if (p->p_timers == NULL) return; itimer_lock(); if ((pts = l->l_proc->p_timers) != NULL) { /* * Run current process's virtual and profile time, as needed. */ if (user && (it = LIST_FIRST(&pts->pts_virtual)) != NULL) if (itimer_decr(it, tick * 1000)) (*it->it_ops->ito_fire)(it); if ((it = LIST_FIRST(&pts->pts_prof)) != NULL) if (itimer_decr(it, tick * 1000)) (*it->it_ops->ito_fire)(it); } itimer_unlock(); } /* * ptimer_intr: * * Software interrupt handler for processing per-process * timer expiration. */ static void ptimer_intr(void *cookie) { ksiginfo_t ksi; struct itimer *it; struct ptimer *pt; proc_t *p; mutex_enter(&proc_lock); itimer_lock(); while ((pt = TAILQ_FIRST(&ptimer_queue)) != NULL) { it = &pt->pt_itimer; TAILQ_REMOVE(&ptimer_queue, pt, pt_chain); KASSERT(pt->pt_queued); pt->pt_queued = false; p = pt->pt_proc; if (p->p_timers == NULL) { /* Process is dying. */ continue; } if (pt->pt_ev.sigev_notify != SIGEV_SIGNAL) { continue; } if (sigismember(&p->p_sigpend.sp_set, pt->pt_ev.sigev_signo)) { it->it_overruns++; continue; } KSI_INIT(&ksi); ksi.ksi_signo = pt->pt_ev.sigev_signo; ksi.ksi_code = SI_TIMER; ksi.ksi_value = pt->pt_ev.sigev_value; pt->pt_poverruns = it->it_overruns; it->it_overruns = 0; itimer_unlock(); kpsignal(p, &ksi, NULL); itimer_lock(); } itimer_unlock(); mutex_exit(&proc_lock); } |
2281 5 5 4 2 3 3 1 1 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 | /* $NetBSD: kern_clock.c,v 1.148 2022/03/19 14:34:47 riastradh Exp $ */ /*- * Copyright (c) 2000, 2004, 2006, 2007, 2008 The NetBSD Foundation, Inc. * All rights reserved. * * This code is derived from software contributed to The NetBSD Foundation * by Jason R. Thorpe of the Numerical Aerospace Simulation Facility, * NASA Ames Research Center. * This code is derived from software contributed to The NetBSD Foundation * by Charles M. Hannum. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ /*- * Copyright (c) 1982, 1986, 1991, 1993 * The Regents of the University of California. All rights reserved. * (c) UNIX System Laboratories, Inc. * All or some portions of this file are derived from material licensed * to the University of California by American Telephone and Telegraph * Co. or Unix System Laboratories, Inc. and are reproduced herein with * the permission of UNIX System Laboratories, Inc. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * @(#)kern_clock.c 8.5 (Berkeley) 1/21/94 */ #include <sys/cdefs.h> __KERNEL_RCSID(0, "$NetBSD: kern_clock.c,v 1.148 2022/03/19 14:34:47 riastradh Exp $"); #ifdef _KERNEL_OPT #include "opt_dtrace.h" #include "opt_gprof.h" #include "opt_multiprocessor.h" #endif #include <sys/param.h> #include <sys/systm.h> #include <sys/callout.h> #include <sys/kernel.h> #include <sys/proc.h> #include <sys/resourcevar.h> #include <sys/signalvar.h> #include <sys/sysctl.h> #include <sys/timex.h> #include <sys/sched.h> #include <sys/time.h> #include <sys/timetc.h> #include <sys/cpu.h> #include <sys/atomic.h> #include <sys/rndsource.h> #ifdef GPROF #include <sys/gmon.h> #endif #ifdef KDTRACE_HOOKS #include <sys/dtrace_bsd.h> #include <sys/cpu.h> cyclic_clock_func_t cyclic_clock_func[MAXCPUS]; #endif static int sysctl_kern_clockrate(SYSCTLFN_PROTO); /* * Clock handling routines. * * This code is written to operate with two timers that run independently of * each other. The main clock, running hz times per second, is used to keep * track of real time. The second timer handles kernel and user profiling, * and does resource use estimation. If the second timer is programmable, * it is randomized to avoid aliasing between the two clocks. For example, * the randomization prevents an adversary from always giving up the CPU * just before its quantum expires. Otherwise, it would never accumulate * CPU ticks. The mean frequency of the second timer is stathz. * * If no second timer exists, stathz will be zero; in this case we drive * profiling and statistics off the main clock. This WILL NOT be accurate; * do not do it unless absolutely necessary. * * The statistics clock may (or may not) be run at a higher rate while * profiling. This profile clock runs at profhz. We require that profhz * be an integral multiple of stathz. * * If the statistics clock is running fast, it must be divided by the ratio * profhz/stathz for statistics. (For profiling, every tick counts.) */ int stathz; int profhz; int profsrc; int schedhz; int profprocs; static int hardclock_ticks; static int hardscheddiv; /* hard => sched divider (used if schedhz == 0) */ static int psdiv; /* prof => stat divider */ int psratio; /* ratio: prof / stat */ struct clockrnd { struct krndsource source; unsigned needed; }; static struct clockrnd hardclockrnd __aligned(COHERENCY_UNIT); static struct clockrnd statclockrnd __aligned(COHERENCY_UNIT); static void clockrnd_get(size_t needed, void *cookie) { struct clockrnd *C = cookie; /* Start sampling. */ atomic_store_relaxed(&C->needed, 2*NBBY*needed); } static void clockrnd_sample(struct clockrnd *C) { struct cpu_info *ci = curcpu(); /* If there's nothing needed right now, stop here. */ if (__predict_true(atomic_load_relaxed(&C->needed) == 0)) return; /* * If we're not the primary core of a package, we're probably * driven by the same clock as the primary core, so don't * bother. */ if (ci != ci->ci_package1st) return; /* Take a sample and enter it into the pool. */ rnd_add_uint32(&C->source, 0); /* * On the primary CPU, count down. Using an atomic decrement * here isn't really necessary -- on every platform we care * about, stores to unsigned int are atomic, and the only other * memory operation that could happen here is for another CPU * to store a higher value for needed. But using an atomic * decrement avoids giving the impression of data races, and is * unlikely to hurt because only one CPU will ever be writing * to the location. */ if (CPU_IS_PRIMARY(curcpu())) { unsigned needed __diagused; needed = atomic_dec_uint_nv(&C->needed); KASSERT(needed != UINT_MAX); } } static u_int get_intr_timecount(struct timecounter *); static struct timecounter intr_timecounter = { .tc_get_timecount = get_intr_timecount, .tc_poll_pps = NULL, .tc_counter_mask = ~0u, .tc_frequency = 0, .tc_name = "clockinterrupt", /* quality - minimum implementation level for a clock */ .tc_quality = 0, .tc_priv = NULL, }; static u_int get_intr_timecount(struct timecounter *tc) { return (u_int)getticks(); } int getticks(void) { return atomic_load_relaxed(&hardclock_ticks); } /* * Initialize clock frequencies and start both clocks running. */ void initclocks(void) { static struct sysctllog *clog; int i; /* * Set divisors to 1 (normal case) and let the machine-specific * code do its bit. */ psdiv = 1; /* * Call cpu_initclocks() before registering the default * timecounter, in case it needs to adjust hz. */ const int old_hz = hz; cpu_initclocks(); if (old_hz != hz) { tick = 1000000 / hz; tickadj = (240000 / (60 * hz)) ? (240000 / (60 * hz)) : 1; } /* * provide minimum default time counter * will only run at interrupt resolution */ intr_timecounter.tc_frequency = hz; tc_init(&intr_timecounter); /* * Compute profhz and stathz, fix profhz if needed. */ i = stathz ? stathz : hz; if (profhz == 0) profhz = i; psratio = profhz / i; if (schedhz == 0) { /* 16Hz is best */ hardscheddiv = hz / 16; if (hardscheddiv <= 0) panic("hardscheddiv"); } sysctl_createv(&clog, 0, NULL, NULL, CTLFLAG_PERMANENT, CTLTYPE_STRUCT, "clockrate", SYSCTL_DESCR("Kernel clock rates"), sysctl_kern_clockrate, 0, NULL, sizeof(struct clockinfo), CTL_KERN, KERN_CLOCKRATE, CTL_EOL); sysctl_createv(&clog, 0, NULL, NULL, CTLFLAG_PERMANENT, CTLTYPE_INT, "hardclock_ticks", SYSCTL_DESCR("Number of hardclock ticks"), NULL, 0, &hardclock_ticks, sizeof(hardclock_ticks), CTL_KERN, KERN_HARDCLOCK_TICKS, CTL_EOL); rndsource_setcb(&hardclockrnd.source, clockrnd_get, &hardclockrnd); rnd_attach_source(&hardclockrnd.source, "hardclock", RND_TYPE_SKEW, RND_FLAG_COLLECT_TIME|RND_FLAG_HASCB); if (stathz) { rndsource_setcb(&statclockrnd.source, clockrnd_get, &statclockrnd); rnd_attach_source(&statclockrnd.source, "statclock", RND_TYPE_SKEW, RND_FLAG_COLLECT_TIME|RND_FLAG_HASCB); } } /* * The real-time timer, interrupting hz times per second. */ void hardclock(struct clockframe *frame) { struct lwp *l; struct cpu_info *ci; clockrnd_sample(&hardclockrnd); ci = curcpu(); l = ci->ci_onproc; ptimer_tick(l, CLKF_USERMODE(frame)); /* * If no separate statistics clock is available, run it from here. */ if (stathz == 0) statclock(frame); /* * If no separate schedclock is provided, call it here * at about 16 Hz. */ if (schedhz == 0) { if ((int)(--ci->ci_schedstate.spc_schedticks) <= 0) { schedclock(l); ci->ci_schedstate.spc_schedticks = hardscheddiv; } } if ((--ci->ci_schedstate.spc_ticks) <= 0) sched_tick(ci); if (CPU_IS_PRIMARY(ci)) { atomic_store_relaxed(&hardclock_ticks, atomic_load_relaxed(&hardclock_ticks) + 1); tc_ticktock(); } /* * Update real-time timeout queue. */ callout_hardclock(); } /* * Start profiling on a process. * * Kernel profiling passes proc0 which never exits and hence * keeps the profile clock running constantly. */ void startprofclock(struct proc *p) { KASSERT(mutex_owned(&p->p_stmutex)); if ((p->p_stflag & PST_PROFIL) == 0) { p->p_stflag |= PST_PROFIL; /* * This is only necessary if using the clock as the * profiling source. */ if (++profprocs == 1 && stathz != 0) psdiv = psratio; } } /* * Stop profiling on a process. */ void stopprofclock(struct proc *p) { KASSERT(mutex_owned(&p->p_stmutex)); if (p->p_stflag & PST_PROFIL) { p->p_stflag &= ~PST_PROFIL; /* * This is only necessary if using the clock as the * profiling source. */ if (--profprocs == 0 && stathz != 0) psdiv = 1; } } void schedclock(struct lwp *l) { if ((l->l_flag & LW_IDLE) != 0) return; sched_schedclock(l); } /* * Statistics clock. Grab profile sample, and if divider reaches 0, * do process and kernel statistics. */ void statclock(struct clockframe *frame) { #ifdef GPROF struct gmonparam *g; intptr_t i; #endif struct cpu_info *ci = curcpu(); struct schedstate_percpu *spc = &ci->ci_schedstate; struct proc *p; struct lwp *l; if (stathz) clockrnd_sample(&statclockrnd); /* * Notice changes in divisor frequency, and adjust clock * frequency accordingly. */ if (spc->spc_psdiv != psdiv) { spc->spc_psdiv = psdiv; spc->spc_pscnt = psdiv; if (psdiv == 1) { setstatclockrate(stathz); } else { setstatclockrate(profhz); } } l = ci->ci_onproc; if ((l->l_flag & LW_IDLE) != 0) { /* * don't account idle lwps as swapper. */ p = NULL; } else { p = l->l_proc; mutex_spin_enter(&p->p_stmutex); } if (CLKF_USERMODE(frame)) { KASSERT(p != NULL); if ((p->p_stflag & PST_PROFIL) && profsrc == PROFSRC_CLOCK) addupc_intr(l, CLKF_PC(frame)); if (--spc->spc_pscnt > 0) { mutex_spin_exit(&p->p_stmutex); return; } /* * Came from user mode; CPU was in user state. * If this process is being profiled record the tick. */ p->p_uticks++; if (p->p_nice > NZERO) spc->spc_cp_time[CP_NICE]++; else spc->spc_cp_time[CP_USER]++; } else { #ifdef GPROF /* * Kernel statistics are just like addupc_intr, only easier. */ #if defined(MULTIPROCESSOR) && !defined(_RUMPKERNEL) g = curcpu()->ci_gmon; if (g != NULL && profsrc == PROFSRC_CLOCK && g->state == GMON_PROF_ON) { #else g = &_gmonparam; if (profsrc == PROFSRC_CLOCK && g->state == GMON_PROF_ON) { #endif i = CLKF_PC(frame) - g->lowpc; if (i < g->textsize) { i /= HISTFRACTION * sizeof(*g->kcount); g->kcount[i]++; } } #endif #ifdef LWP_PC if (p != NULL && profsrc == PROFSRC_CLOCK && (p->p_stflag & PST_PROFIL)) { addupc_intr(l, LWP_PC(l)); } #endif if (--spc->spc_pscnt > 0) { if (p != NULL) mutex_spin_exit(&p->p_stmutex); return; } /* * Came from kernel mode, so we were: * - handling an interrupt, * - doing syscall or trap work on behalf of the current * user process, or * - spinning in the idle loop. * Whichever it is, charge the time as appropriate. * Note that we charge interrupts to the current process, * regardless of whether they are ``for'' that process, * so that we know how much of its real time was spent * in ``non-process'' (i.e., interrupt) work. */ if (CLKF_INTR(frame) || (curlwp->l_pflag & LP_INTR) != 0) { if (p != NULL) { p->p_iticks++; } spc->spc_cp_time[CP_INTR]++; } else if (p != NULL) { p->p_sticks++; spc->spc_cp_time[CP_SYS]++; } else { spc->spc_cp_time[CP_IDLE]++; } } spc->spc_pscnt = psdiv; if (p != NULL) { atomic_inc_uint(&l->l_cpticks); mutex_spin_exit(&p->p_stmutex); } #ifdef KDTRACE_HOOKS cyclic_clock_func_t func = cyclic_clock_func[cpu_index(ci)]; if (func) { (*func)((struct clockframe *)frame); } #endif } /* * sysctl helper routine for kern.clockrate. Assembles a struct on * the fly to be returned to the caller. */ static int sysctl_kern_clockrate(SYSCTLFN_ARGS) { struct clockinfo clkinfo; struct sysctlnode node; clkinfo.tick = tick; clkinfo.tickadj = tickadj; clkinfo.hz = hz; clkinfo.profhz = profhz; clkinfo.stathz = stathz ? stathz : hz; node = *rnode; node.sysctl_data = &clkinfo; return (sysctl_lookup(SYSCTLFN_CALL(&node))); } |
4 4 47 47 47 46 47 47 46 47 47 80 81 46 80 81 79 82 82 27 27 27 27 80 82 82 81 81 80 80 80 29 80 81 78 82 27 27 27 27 80 79 81 43 81 26 80 63 81 82 82 82 29 29 29 63 62 63 62 63 63 63 63 63 1 62 63 63 63 81 81 80 79 81 80 81 81 81 81 81 80 81 81 81 563 563 563 564 564 508 564 543 543 80 564 564 79 81 79 78 79 81 81 81 80 81 81 80 80 79 81 81 81 81 81 63 63 63 80 81 81 81 63 63 80 80 81 81 79 64 81 80 79 80 80 80 121 121 120 106 27 27 27 27 27 27 27 26 27 27 25 25 27 26 9 9 27 27 18 19 19 27 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 | /* $NetBSD: subr_vmem.c,v 1.108 2022/05/31 08:43:16 andvar Exp $ */ /*- * Copyright (c)2006,2007,2008,2009 YAMAMOTO Takashi, * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ /* * reference: * - Magazines and Vmem: Extending the Slab Allocator * to Many CPUs and Arbitrary Resources * http://www.usenix.org/event/usenix01/bonwick.html * * locking & the boundary tag pool: * - A pool(9) is used for vmem boundary tags * - During a pool get call the global vmem_btag_refill_lock is taken, * to serialize access to the allocation reserve, but no other * vmem arena locks. * - During pool_put calls no vmem mutexes are locked. * - pool_drain doesn't hold the pool's mutex while releasing memory to * its backing therefore no interference with any vmem mutexes. * - The boundary tag pool is forced to put page headers into pool pages * (PR_PHINPAGE) and not off page to avoid pool recursion. * (due to sizeof(bt_t) it should be the case anyway) */ #include <sys/cdefs.h> __KERNEL_RCSID(0, "$NetBSD: subr_vmem.c,v 1.108 2022/05/31 08:43:16 andvar Exp $"); #if defined(_KERNEL) && defined(_KERNEL_OPT) #include "opt_ddb.h" #endif /* defined(_KERNEL) && defined(_KERNEL_OPT) */ #include <sys/param.h> #include <sys/hash.h> #include <sys/queue.h> #include <sys/bitops.h> #if defined(_KERNEL) #include <sys/systm.h> #include <sys/kernel.h> /* hz */ #include <sys/callout.h> #include <sys/kmem.h> #include <sys/pool.h> #include <sys/vmem.h> #include <sys/vmem_impl.h> #include <sys/workqueue.h> #include <sys/atomic.h> #include <uvm/uvm.h> #include <uvm/uvm_extern.h> #include <uvm/uvm_km.h> #include <uvm/uvm_page.h> #include <uvm/uvm_pdaemon.h> #else /* defined(_KERNEL) */ #include <stdio.h> #include <errno.h> #include <assert.h> #include <stdlib.h> #include <string.h> #include "../sys/vmem.h" #include "../sys/vmem_impl.h" #endif /* defined(_KERNEL) */ #if defined(_KERNEL) #include <sys/evcnt.h> #define VMEM_EVCNT_DEFINE(name) \ struct evcnt vmem_evcnt_##name = EVCNT_INITIALIZER(EVCNT_TYPE_MISC, NULL, \ "vmem", #name); \ EVCNT_ATTACH_STATIC(vmem_evcnt_##name); #define VMEM_EVCNT_INCR(ev) vmem_evcnt_##ev.ev_count++ #define VMEM_EVCNT_DECR(ev) vmem_evcnt_##ev.ev_count-- VMEM_EVCNT_DEFINE(static_bt_count) VMEM_EVCNT_DEFINE(static_bt_inuse) #define VMEM_CONDVAR_INIT(vm, wchan) cv_init(&vm->vm_cv, wchan) #define VMEM_CONDVAR_DESTROY(vm) cv_destroy(&vm->vm_cv) #define VMEM_CONDVAR_WAIT(vm) cv_wait(&vm->vm_cv, &vm->vm_lock) #define VMEM_CONDVAR_BROADCAST(vm) cv_broadcast(&vm->vm_cv) #else /* defined(_KERNEL) */ #define VMEM_EVCNT_INCR(ev) /* nothing */ #define VMEM_EVCNT_DECR(ev) /* nothing */ #define VMEM_CONDVAR_INIT(vm, wchan) /* nothing */ #define VMEM_CONDVAR_DESTROY(vm) /* nothing */ #define VMEM_CONDVAR_WAIT(vm) /* nothing */ #define VMEM_CONDVAR_BROADCAST(vm) /* nothing */ #define UNITTEST #define KASSERT(a) assert(a) #define mutex_init(a, b, c) /* nothing */ #define mutex_destroy(a) /* nothing */ #define mutex_enter(a) /* nothing */ #define mutex_tryenter(a) true #define mutex_exit(a) /* nothing */ #define mutex_owned(a) /* nothing */ #define ASSERT_SLEEPABLE() /* nothing */ #define panic(...) printf(__VA_ARGS__); abort() #endif /* defined(_KERNEL) */ #if defined(VMEM_SANITY) static void vmem_check(vmem_t *); #else /* defined(VMEM_SANITY) */ #define vmem_check(vm) /* nothing */ #endif /* defined(VMEM_SANITY) */ #define VMEM_HASHSIZE_MIN 1 /* XXX */ #define VMEM_HASHSIZE_MAX 65536 /* XXX */ #define VMEM_HASHSIZE_INIT 1 #define VM_FITMASK (VM_BESTFIT | VM_INSTANTFIT) #if defined(_KERNEL) static bool vmem_bootstrapped = false; static kmutex_t vmem_list_lock; static LIST_HEAD(, vmem) vmem_list = LIST_HEAD_INITIALIZER(vmem_list); #endif /* defined(_KERNEL) */ /* ---- misc */ #define VMEM_LOCK(vm) mutex_enter(&vm->vm_lock) #define VMEM_TRYLOCK(vm) mutex_tryenter(&vm->vm_lock) #define VMEM_UNLOCK(vm) mutex_exit(&vm->vm_lock) #define VMEM_LOCK_INIT(vm, ipl) mutex_init(&vm->vm_lock, MUTEX_DEFAULT, ipl) #define VMEM_LOCK_DESTROY(vm) mutex_destroy(&vm->vm_lock) #define VMEM_ASSERT_LOCKED(vm) KASSERT(mutex_owned(&vm->vm_lock)) #define VMEM_ALIGNUP(addr, align) \ (-(-(addr) & -(align))) #define VMEM_CROSS_P(addr1, addr2, boundary) \ ((((addr1) ^ (addr2)) & -(boundary)) != 0) #define ORDER2SIZE(order) ((vmem_size_t)1 << (order)) #define SIZE2ORDER(size) ((int)ilog2(size)) #if !defined(_KERNEL) #define xmalloc(sz, flags) malloc(sz) #define xfree(p, sz) free(p) #define bt_alloc(vm, flags) malloc(sizeof(bt_t)) #define bt_free(vm, bt) free(bt) #else /* defined(_KERNEL) */ #define xmalloc(sz, flags) \ kmem_alloc(sz, ((flags) & VM_SLEEP) ? KM_SLEEP : KM_NOSLEEP); #define xfree(p, sz) kmem_free(p, sz); /* * BT_RESERVE calculation: * we allocate memory for boundary tags with vmem; therefore we have * to keep a reserve of bts used to allocated memory for bts. * This reserve is 4 for each arena involved in allocating vmems memory. * BT_MAXFREE: don't cache excessive counts of bts in arenas */ #define STATIC_BT_COUNT 200 #define BT_MINRESERVE 4 #define BT_MAXFREE 64 static struct vmem_btag static_bts[STATIC_BT_COUNT]; static int static_bt_count = STATIC_BT_COUNT; static struct vmem kmem_va_meta_arena_store; vmem_t *kmem_va_meta_arena; static struct vmem kmem_meta_arena_store; vmem_t *kmem_meta_arena = NULL; static kmutex_t vmem_btag_refill_lock; static kmutex_t vmem_btag_lock; static LIST_HEAD(, vmem_btag) vmem_btag_freelist; static size_t vmem_btag_freelist_count = 0; static struct pool vmem_btag_pool; static void vmem_xfree_bt(vmem_t *, bt_t *); static void vmem_kick_pdaemon(void) { #if defined(_KERNEL) uvm_kick_pdaemon(); #endif } /* ---- boundary tag */ static int bt_refill(vmem_t *vm); static int bt_refill_locked(vmem_t *vm); static void * pool_page_alloc_vmem_meta(struct pool *pp, int flags) { const vm_flag_t vflags = (flags & PR_WAITOK) ? VM_SLEEP: VM_NOSLEEP; vmem_addr_t va; int ret; ret = vmem_alloc(kmem_meta_arena, pp->pr_alloc->pa_pagesz, (vflags & ~VM_FITMASK) | VM_INSTANTFIT | VM_POPULATING, &va); return ret ? NULL : (void *)va; } static void pool_page_free_vmem_meta(struct pool *pp, void *v) { vmem_free(kmem_meta_arena, (vmem_addr_t)v, pp->pr_alloc->pa_pagesz); } /* allocator for vmem-pool metadata */ struct pool_allocator pool_allocator_vmem_meta = { .pa_alloc = pool_page_alloc_vmem_meta, .pa_free = pool_page_free_vmem_meta, .pa_pagesz = 0 }; static int bt_refill_locked(vmem_t *vm) { bt_t *bt; VMEM_ASSERT_LOCKED(vm); if (vm->vm_nfreetags > BT_MINRESERVE) { return 0; } mutex_enter(&vmem_btag_lock); while (!LIST_EMPTY(&vmem_btag_freelist) && vm->vm_nfreetags <= BT_MINRESERVE) { bt = LIST_FIRST(&vmem_btag_freelist); LIST_REMOVE(bt, bt_freelist); LIST_INSERT_HEAD(&vm->vm_freetags, bt, bt_freelist); vm->vm_nfreetags++; vmem_btag_freelist_count--; VMEM_EVCNT_INCR(static_bt_inuse); } mutex_exit(&vmem_btag_lock); while (vm->vm_nfreetags <= BT_MINRESERVE) { VMEM_UNLOCK(vm); mutex_enter(&vmem_btag_refill_lock); bt = pool_get(&vmem_btag_pool, PR_NOWAIT); mutex_exit(&vmem_btag_refill_lock); VMEM_LOCK(vm); if (bt == NULL) break; LIST_INSERT_HEAD(&vm->vm_freetags, bt, bt_freelist); vm->vm_nfreetags++; } if (vm->vm_nfreetags <= BT_MINRESERVE) { return ENOMEM; } if (kmem_meta_arena != NULL) { VMEM_UNLOCK(vm); (void)bt_refill(kmem_arena); (void)bt_refill(kmem_va_meta_arena); (void)bt_refill(kmem_meta_arena); VMEM_LOCK(vm); } return 0; } static int bt_refill(vmem_t *vm) { int rv; VMEM_LOCK(vm); rv = bt_refill_locked(vm); VMEM_UNLOCK(vm); return rv; } static bt_t * bt_alloc(vmem_t *vm, vm_flag_t flags) { bt_t *bt; VMEM_ASSERT_LOCKED(vm); while (vm->vm_nfreetags <= BT_MINRESERVE && (flags & VM_POPULATING) == 0) { if (bt_refill_locked(vm)) { if ((flags & VM_NOSLEEP) != 0) { return NULL; } /* * It would be nice to wait for something specific here * but there are multiple ways that a retry could * succeed and we can't wait for multiple things * simultaneously. So we'll just sleep for an arbitrary * short period of time and retry regardless. * This should be a very rare case. */ vmem_kick_pdaemon(); kpause("btalloc", false, 1, &vm->vm_lock); } } bt = LIST_FIRST(&vm->vm_freetags); LIST_REMOVE(bt, bt_freelist); vm->vm_nfreetags--; return bt; } static void bt_free(vmem_t *vm, bt_t *bt) { VMEM_ASSERT_LOCKED(vm); LIST_INSERT_HEAD(&vm->vm_freetags, bt, bt_freelist); vm->vm_nfreetags++; } static void bt_freetrim(vmem_t *vm, int freelimit) { bt_t *t; LIST_HEAD(, vmem_btag) tofree; VMEM_ASSERT_LOCKED(vm); LIST_INIT(&tofree); while (vm->vm_nfreetags > freelimit) { bt_t *bt = LIST_FIRST(&vm->vm_freetags); LIST_REMOVE(bt, bt_freelist); vm->vm_nfreetags--; if (bt >= static_bts && bt < &static_bts[STATIC_BT_COUNT]) { mutex_enter(&vmem_btag_lock); LIST_INSERT_HEAD(&vmem_btag_freelist, bt, bt_freelist); vmem_btag_freelist_count++; mutex_exit(&vmem_btag_lock); VMEM_EVCNT_DECR(static_bt_inuse); } else { LIST_INSERT_HEAD(&tofree, bt, bt_freelist); } } VMEM_UNLOCK(vm); while (!LIST_EMPTY(&tofree)) { t = LIST_FIRST(&tofree); LIST_REMOVE(t, bt_freelist); pool_put(&vmem_btag_pool, t); } } #endif /* defined(_KERNEL) */ /* * freelist[0] ... [1, 1] * freelist[1] ... [2, 3] * freelist[2] ... [4, 7] * freelist[3] ... [8, 15] * : * freelist[n] ... [(1 << n), (1 << (n + 1)) - 1] * : */ static struct vmem_freelist * bt_freehead_tofree(vmem_t *vm, vmem_size_t size) { const vmem_size_t qsize = size >> vm->vm_quantum_shift; const int idx = SIZE2ORDER(qsize); KASSERT(size != 0 && qsize != 0); KASSERT((size & vm->vm_quantum_mask) == 0); KASSERT(idx >= 0); KASSERT(idx < VMEM_MAXORDER); return &vm->vm_freelist[idx]; } /* * bt_freehead_toalloc: return the freelist for the given size and allocation * strategy. * * for VM_INSTANTFIT, return the list in which any blocks are large enough * for the requested size. otherwise, return the list which can have blocks * large enough for the requested size. */ static struct vmem_freelist * bt_freehead_toalloc(vmem_t *vm, vmem_size_t size, vm_flag_t strat) { const vmem_size_t qsize = size >> vm->vm_quantum_shift; int idx = SIZE2ORDER(qsize); KASSERT(size != 0 && qsize != 0); KASSERT((size & vm->vm_quantum_mask) == 0); if (strat == VM_INSTANTFIT && ORDER2SIZE(idx) != qsize) { idx++; /* check too large request? */ } KASSERT(idx >= 0); KASSERT(idx < VMEM_MAXORDER); return &vm->vm_freelist[idx]; } /* ---- boundary tag hash */ static struct vmem_hashlist * bt_hashhead(vmem_t *vm, vmem_addr_t addr) { struct vmem_hashlist *list; unsigned int hash; hash = hash32_buf(&addr, sizeof(addr), HASH32_BUF_INIT); list = &vm->vm_hashlist[hash & vm->vm_hashmask]; return list; } static bt_t * bt_lookupbusy(vmem_t *vm, vmem_addr_t addr) { struct vmem_hashlist *list; bt_t *bt; list = bt_hashhead(vm, addr); LIST_FOREACH(bt, list, bt_hashlist) { if (bt->bt_start == addr) { break; } } return bt; } static void bt_rembusy(vmem_t *vm, bt_t *bt) { KASSERT(vm->vm_nbusytag > 0); vm->vm_inuse -= bt->bt_size; vm->vm_nbusytag--; LIST_REMOVE(bt, bt_hashlist); } static void bt_insbusy(vmem_t *vm, bt_t *bt) { struct vmem_hashlist *list; KASSERT(bt->bt_type == BT_TYPE_BUSY); list = bt_hashhead(vm, bt->bt_start); LIST_INSERT_HEAD(list, bt, bt_hashlist); if (++vm->vm_nbusytag > vm->vm_maxbusytag) { vm->vm_maxbusytag = vm->vm_nbusytag; } vm->vm_inuse += bt->bt_size; } /* ---- boundary tag list */ static void bt_remseg(vmem_t *vm, bt_t *bt) { TAILQ_REMOVE(&vm->vm_seglist, bt, bt_seglist); } static void bt_insseg(vmem_t *vm, bt_t *bt, bt_t *prev) { TAILQ_INSERT_AFTER(&vm->vm_seglist, prev, bt, bt_seglist); } static void bt_insseg_tail(vmem_t *vm, bt_t *bt) { TAILQ_INSERT_TAIL(&vm->vm_seglist, bt, bt_seglist); } static void bt_remfree(vmem_t *vm, bt_t *bt) { KASSERT(bt->bt_type == BT_TYPE_FREE); LIST_REMOVE(bt, bt_freelist); } static void bt_insfree(vmem_t *vm, bt_t *bt) { struct vmem_freelist *list; list = bt_freehead_tofree(vm, bt->bt_size); LIST_INSERT_HEAD(list, bt, bt_freelist); } /* ---- vmem internal functions */ #if defined(QCACHE) static inline vm_flag_t prf_to_vmf(int prflags) { vm_flag_t vmflags; KASSERT((prflags & ~(PR_LIMITFAIL | PR_WAITOK | PR_NOWAIT)) == 0); if ((prflags & PR_WAITOK) != 0) { vmflags = VM_SLEEP; } else { vmflags = VM_NOSLEEP; } return vmflags; } static inline int vmf_to_prf(vm_flag_t vmflags) { int prflags; if ((vmflags & VM_SLEEP) != 0) { prflags = PR_WAITOK; } else { prflags = PR_NOWAIT; } return prflags; } static size_t qc_poolpage_size(size_t qcache_max) { int i; for (i = 0; ORDER2SIZE(i) <= qcache_max * 3; i++) { /* nothing */ } return ORDER2SIZE(i); } static void * qc_poolpage_alloc(struct pool *pool, int prflags) { qcache_t *qc = QC_POOL_TO_QCACHE(pool); vmem_t *vm = qc->qc_vmem; vmem_addr_t addr; if (vmem_alloc(vm, pool->pr_alloc->pa_pagesz, prf_to_vmf(prflags) | VM_INSTANTFIT, &addr) != 0) return NULL; return (void *)addr; } static void qc_poolpage_free(struct pool *pool, void *addr) { qcache_t *qc = QC_POOL_TO_QCACHE(pool); vmem_t *vm = qc->qc_vmem; vmem_free(vm, (vmem_addr_t)addr, pool->pr_alloc->pa_pagesz); } static void qc_init(vmem_t *vm, size_t qcache_max, int ipl) { qcache_t *prevqc; struct pool_allocator *pa; int qcache_idx_max; int i; KASSERT((qcache_max & vm->vm_quantum_mask) == 0); if (qcache_max > (VMEM_QCACHE_IDX_MAX << vm->vm_quantum_shift)) { qcache_max = VMEM_QCACHE_IDX_MAX << vm->vm_quantum_shift; } vm->vm_qcache_max = qcache_max; pa = &vm->vm_qcache_allocator; memset(pa, 0, sizeof(*pa)); pa->pa_alloc = qc_poolpage_alloc; pa->pa_free = qc_poolpage_free; pa->pa_pagesz = qc_poolpage_size(qcache_max); qcache_idx_max = qcache_max >> vm->vm_quantum_shift; prevqc = NULL; for (i = qcache_idx_max; i > 0; i--) { qcache_t *qc = &vm->vm_qcache_store[i - 1]; size_t size = i << vm->vm_quantum_shift; pool_cache_t pc; qc->qc_vmem = vm; snprintf(qc->qc_name, sizeof(qc->qc_name), "%s-%zu", vm->vm_name, size); pc = pool_cache_init(size, ORDER2SIZE(vm->vm_quantum_shift), 0, PR_NOALIGN | PR_NOTOUCH | PR_RECURSIVE /* XXX */, qc->qc_name, pa, ipl, NULL, NULL, NULL); KASSERT(pc); qc->qc_cache = pc; KASSERT(qc->qc_cache != NULL); /* XXX */ if (prevqc != NULL && qc->qc_cache->pc_pool.pr_itemsperpage == prevqc->qc_cache->pc_pool.pr_itemsperpage) { pool_cache_destroy(qc->qc_cache); vm->vm_qcache[i - 1] = prevqc; continue; } qc->qc_cache->pc_pool.pr_qcache = qc; vm->vm_qcache[i - 1] = qc; prevqc = qc; } } static void qc_destroy(vmem_t *vm) { const qcache_t *prevqc; int i; int qcache_idx_max; qcache_idx_max = vm->vm_qcache_max >> vm->vm_quantum_shift; prevqc = NULL; for (i = 0; i < qcache_idx_max; i++) { qcache_t *qc = vm->vm_qcache[i]; if (prevqc == qc) { continue; } pool_cache_destroy(qc->qc_cache); prevqc = qc; } } #endif #if defined(_KERNEL) static void vmem_bootstrap(void) { mutex_init(&vmem_list_lock, MUTEX_DEFAULT, IPL_NONE); mutex_init(&vmem_btag_lock, MUTEX_DEFAULT, IPL_VM); mutex_init(&vmem_btag_refill_lock, MUTEX_DEFAULT, IPL_VM); while (static_bt_count-- > 0) { bt_t *bt = &static_bts[static_bt_count]; LIST_INSERT_HEAD(&vmem_btag_freelist, bt, bt_freelist); VMEM_EVCNT_INCR(static_bt_count); vmem_btag_freelist_count++; } vmem_bootstrapped = TRUE; } void vmem_subsystem_init(vmem_t *vm) { kmem_va_meta_arena = vmem_init(&kmem_va_meta_arena_store, "vmem-va", 0, 0, PAGE_SIZE, vmem_alloc, vmem_free, vm, 0, VM_NOSLEEP | VM_BOOTSTRAP | VM_LARGEIMPORT, IPL_VM); kmem_meta_arena = vmem_init(&kmem_meta_arena_store, "vmem-meta", 0, 0, PAGE_SIZE, uvm_km_kmem_alloc, uvm_km_kmem_free, kmem_va_meta_arena, 0, VM_NOSLEEP | VM_BOOTSTRAP, IPL_VM); pool_init(&vmem_btag_pool, sizeof(bt_t), coherency_unit, 0, PR_PHINPAGE, "vmembt", &pool_allocator_vmem_meta, IPL_VM); } #endif /* defined(_KERNEL) */ static int vmem_add1(vmem_t *vm, vmem_addr_t addr, vmem_size_t size, vm_flag_t flags, int spanbttype) { bt_t *btspan; bt_t *btfree; VMEM_ASSERT_LOCKED(vm); KASSERT((flags & (VM_SLEEP|VM_NOSLEEP)) != 0); KASSERT((~flags & (VM_SLEEP|VM_NOSLEEP)) != 0); KASSERT(spanbttype == BT_TYPE_SPAN || spanbttype == BT_TYPE_SPAN_STATIC); btspan = bt_alloc(vm, flags); if (btspan == NULL) { return ENOMEM; } btfree = bt_alloc(vm, flags); if (btfree == NULL) { bt_free(vm, btspan); return ENOMEM; } btspan->bt_type = spanbttype; btspan->bt_start = addr; btspan->bt_size = size; btfree->bt_type = BT_TYPE_FREE; btfree->bt_start = addr; btfree->bt_size = size; bt_insseg_tail(vm, btspan); bt_insseg(vm, btfree, btspan); bt_insfree(vm, btfree); vm->vm_size += size; return 0; } static void vmem_destroy1(vmem_t *vm) { #if defined(QCACHE) qc_destroy(vm); #endif /* defined(QCACHE) */ VMEM_LOCK(vm); for (int i = 0; i < vm->vm_hashsize; i++) { bt_t *bt; while ((bt = LIST_FIRST(&vm->vm_hashlist[i])) != NULL) { KASSERT(bt->bt_type == BT_TYPE_SPAN_STATIC); LIST_REMOVE(bt, bt_hashlist); bt_free(vm, bt); } } /* bt_freetrim() drops the lock. */ bt_freetrim(vm, 0); if (vm->vm_hashlist != &vm->vm_hash0) { xfree(vm->vm_hashlist, sizeof(struct vmem_hashlist) * vm->vm_hashsize); } VMEM_CONDVAR_DESTROY(vm); VMEM_LOCK_DESTROY(vm); xfree(vm, sizeof(*vm)); } static int vmem_import(vmem_t *vm, vmem_size_t size, vm_flag_t flags) { vmem_addr_t addr; int rc; VMEM_ASSERT_LOCKED(vm); if (vm->vm_importfn == NULL) { return EINVAL; } if (vm->vm_flags & VM_LARGEIMPORT) { size *= 16; } VMEM_UNLOCK(vm); if (vm->vm_flags & VM_XIMPORT) { rc = __FPTRCAST(vmem_ximport_t *, vm->vm_importfn)(vm->vm_arg, size, &size, flags, &addr); } else { rc = (vm->vm_importfn)(vm->vm_arg, size, flags, &addr); } VMEM_LOCK(vm); if (rc) { return ENOMEM; } if (vmem_add1(vm, addr, size, flags, BT_TYPE_SPAN) != 0) { VMEM_UNLOCK(vm); (*vm->vm_releasefn)(vm->vm_arg, addr, size); VMEM_LOCK(vm); return ENOMEM; } return 0; } static int vmem_rehash(vmem_t *vm, size_t newhashsize, vm_flag_t flags) { bt_t *bt; int i; struct vmem_hashlist *newhashlist; struct vmem_hashlist *oldhashlist; size_t oldhashsize; KASSERT(newhashsize > 0); /* Round hash size up to a power of 2. */ newhashsize = 1 << (ilog2(newhashsize) + 1); newhashlist = xmalloc(sizeof(struct vmem_hashlist) * newhashsize, flags); if (newhashlist == NULL) { return ENOMEM; } for (i = 0; i < newhashsize; i++) { LIST_INIT(&newhashlist[i]); } VMEM_LOCK(vm); /* Decay back to a small hash slowly. */ if (vm->vm_maxbusytag >= 2) { vm->vm_maxbusytag = vm->vm_maxbusytag / 2 - 1; if (vm->vm_nbusytag > vm->vm_maxbusytag) { vm->vm_maxbusytag = vm->vm_nbusytag; } } else { vm->vm_maxbusytag = vm->vm_nbusytag; } oldhashlist = vm->vm_hashlist; oldhashsize = vm->vm_hashsize; vm->vm_hashlist = newhashlist; vm->vm_hashsize = newhashsize; vm->vm_hashmask = newhashsize - 1; if (oldhashlist == NULL) { VMEM_UNLOCK(vm); return 0; } for (i = 0; i < oldhashsize; i++) { while ((bt = LIST_FIRST(&oldhashlist[i])) != NULL) { bt_rembusy(vm, bt); /* XXX */ bt_insbusy(vm, bt); } } VMEM_UNLOCK(vm); if (oldhashlist != &vm->vm_hash0) { xfree(oldhashlist, sizeof(struct vmem_hashlist) * oldhashsize); } return 0; } /* * vmem_fit: check if a bt can satisfy the given restrictions. * * it's a caller's responsibility to ensure the region is big enough * before calling us. */ static int vmem_fit(const bt_t *bt, vmem_size_t size, vmem_size_t align, vmem_size_t phase, vmem_size_t nocross, vmem_addr_t minaddr, vmem_addr_t maxaddr, vmem_addr_t *addrp) { vmem_addr_t start; vmem_addr_t end; KASSERT(size > 0); KASSERT(bt->bt_size >= size); /* caller's responsibility */ /* * XXX assumption: vmem_addr_t and vmem_size_t are * unsigned integer of the same size. */ start = bt->bt_start; if (start < minaddr) { start = minaddr; } end = BT_END(bt); if (end > maxaddr) { end = maxaddr; } if (start > end) { return ENOMEM; } start = VMEM_ALIGNUP(start - phase, align) + phase; if (start < bt->bt_start) { start += align; } if (VMEM_CROSS_P(start, start + size - 1, nocross)) { KASSERT(align < nocross); start = VMEM_ALIGNUP(start - phase, nocross) + phase; } if (start <= end && end - start >= size - 1) { KASSERT((start & (align - 1)) == phase); KASSERT(!VMEM_CROSS_P(start, start + size - 1, nocross)); KASSERT(minaddr <= start); KASSERT(maxaddr == 0 || start + size - 1 <= maxaddr); KASSERT(bt->bt_start <= start); KASSERT(BT_END(bt) - start >= size - 1); *addrp = start; return 0; } return ENOMEM; } /* ---- vmem API */ /* * vmem_init: creates a vmem arena. */ vmem_t * vmem_init(vmem_t *vm, const char *name, vmem_addr_t base, vmem_size_t size, vmem_size_t quantum, vmem_import_t *importfn, vmem_release_t *releasefn, vmem_t *arg, vmem_size_t qcache_max, vm_flag_t flags, int ipl) { int i; KASSERT((flags & (VM_SLEEP|VM_NOSLEEP)) != 0); KASSERT((~flags & (VM_SLEEP|VM_NOSLEEP)) != 0); KASSERT(quantum > 0); #if defined(_KERNEL) /* XXX: SMP, we get called early... */ if (!vmem_bootstrapped) { vmem_bootstrap(); } #endif /* defined(_KERNEL) */ if (vm == NULL) { vm = xmalloc(sizeof(*vm), flags); } if (vm == NULL) { return NULL; } VMEM_CONDVAR_INIT(vm, "vmem"); VMEM_LOCK_INIT(vm, ipl); vm->vm_flags = flags; vm->vm_nfreetags = 0; LIST_INIT(&vm->vm_freetags); strlcpy(vm->vm_name, name, sizeof(vm->vm_name)); vm->vm_quantum_mask = quantum - 1; vm->vm_quantum_shift = SIZE2ORDER(quantum); KASSERT(ORDER2SIZE(vm->vm_quantum_shift) == quantum); vm->vm_importfn = importfn; vm->vm_releasefn = releasefn; vm->vm_arg = arg; vm->vm_nbusytag = 0; vm->vm_maxbusytag = 0; vm->vm_size = 0; vm->vm_inuse = 0; #if defined(QCACHE) qc_init(vm, qcache_max, ipl); #endif /* defined(QCACHE) */ TAILQ_INIT(&vm->vm_seglist); for (i = 0; i < VMEM_MAXORDER; i++) { LIST_INIT(&vm->vm_freelist[i]); } memset(&vm->vm_hash0, 0, sizeof(vm->vm_hash0)); vm->vm_hashsize = 1; vm->vm_hashmask = vm->vm_hashsize - 1; vm->vm_hashlist = &vm->vm_hash0; if (size != 0) { if (vmem_add(vm, base, size, flags) != 0) { vmem_destroy1(vm); return NULL; } } #if defined(_KERNEL) if (flags & VM_BOOTSTRAP) { bt_refill(vm); } mutex_enter(&vmem_list_lock); LIST_INSERT_HEAD(&vmem_list, vm, vm_alllist); mutex_exit(&vmem_list_lock); #endif /* defined(_KERNEL) */ return vm; } /* * vmem_create: create an arena. * * => must not be called from interrupt context. */ vmem_t * vmem_create(const char *name, vmem_addr_t base, vmem_size_t size, vmem_size_t quantum, vmem_import_t *importfn, vmem_release_t *releasefn, vmem_t *source, vmem_size_t qcache_max, vm_flag_t flags, int ipl) { KASSERT((flags & (VM_XIMPORT)) == 0); return vmem_init(NULL, name, base, size, quantum, importfn, releasefn, source, qcache_max, flags, ipl); } /* * vmem_xcreate: create an arena takes alternative import func. * * => must not be called from interrupt context. */ vmem_t * vmem_xcreate(const char *name, vmem_addr_t base, vmem_size_t size, vmem_size_t quantum, vmem_ximport_t *importfn, vmem_release_t *releasefn, vmem_t *source, vmem_size_t qcache_max, vm_flag_t flags, int ipl) { KASSERT((flags & (VM_XIMPORT)) == 0); return vmem_init(NULL, name, base, size, quantum, __FPTRCAST(vmem_import_t *, importfn), releasefn, source, qcache_max, flags | VM_XIMPORT, ipl); } void vmem_destroy(vmem_t *vm) { #if defined(_KERNEL) mutex_enter(&vmem_list_lock); LIST_REMOVE(vm, vm_alllist); mutex_exit(&vmem_list_lock); #endif /* defined(_KERNEL) */ vmem_destroy1(vm); } vmem_size_t vmem_roundup_size(vmem_t *vm, vmem_size_t size) { return (size + vm->vm_quantum_mask) & ~vm->vm_quantum_mask; } /* * vmem_alloc: allocate resource from the arena. */ int vmem_alloc(vmem_t *vm, vmem_size_t size, vm_flag_t flags, vmem_addr_t *addrp) { const vm_flag_t strat __diagused = flags & VM_FITMASK; int error; KASSERT((flags & (VM_SLEEP|VM_NOSLEEP)) != 0); KASSERT((~flags & (VM_SLEEP|VM_NOSLEEP)) != 0); KASSERT(size > 0); KASSERT(strat == VM_BESTFIT || strat == VM_INSTANTFIT); if ((flags & VM_SLEEP) != 0) { ASSERT_SLEEPABLE(); } #if defined(QCACHE) if (size <= vm->vm_qcache_max) { void *p; int qidx = (size + vm->vm_quantum_mask) >> vm->vm_quantum_shift; qcache_t *qc = vm->vm_qcache[qidx - 1]; p = pool_cache_get(qc->qc_cache, vmf_to_prf(flags)); if (addrp != NULL) *addrp = (vmem_addr_t)p; error = (p == NULL) ? ENOMEM : 0; goto out; } #endif /* defined(QCACHE) */ error = vmem_xalloc(vm, size, 0, 0, 0, VMEM_ADDR_MIN, VMEM_ADDR_MAX, flags, addrp); out: KASSERTMSG(error || addrp == NULL || (*addrp & vm->vm_quantum_mask) == 0, "vmem %s mask=0x%jx addr=0x%jx", vm->vm_name, (uintmax_t)vm->vm_quantum_mask, (uintmax_t)*addrp); KASSERT(error == 0 || (flags & VM_SLEEP) == 0); return error; } int vmem_xalloc(vmem_t *vm, const vmem_size_t size0, vmem_size_t align, const vmem_size_t phase, const vmem_size_t nocross, const vmem_addr_t minaddr, const vmem_addr_t maxaddr, const vm_flag_t flags, vmem_addr_t *addrp) { struct vmem_freelist *list; struct vmem_freelist *first; struct vmem_freelist *end; bt_t *bt; bt_t *btnew; bt_t *btnew2; const vmem_size_t size = vmem_roundup_size(vm, size0); vm_flag_t strat = flags & VM_FITMASK; vmem_addr_t start; int rc; KASSERT(size0 > 0); KASSERT(size > 0); KASSERT(strat == VM_BESTFIT || strat == VM_INSTANTFIT); if ((flags & VM_SLEEP) != 0) { ASSERT_SLEEPABLE(); } KASSERT((align & vm->vm_quantum_mask) == 0); KASSERT((align & (align - 1)) == 0); KASSERT((phase & vm->vm_quantum_mask) == 0); KASSERT((nocross & vm->vm_quantum_mask) == 0); KASSERT((nocross & (nocross - 1)) == 0); KASSERT((align == 0 && phase == 0) || phase < align); KASSERT(nocross == 0 || nocross >= size); KASSERT(minaddr <= maxaddr); KASSERT(!VMEM_CROSS_P(phase, phase + size - 1, nocross)); if (align == 0) { align = vm->vm_quantum_mask + 1; } /* * allocate boundary tags before acquiring the vmem lock. */ VMEM_LOCK(vm); btnew = bt_alloc(vm, flags); if (btnew == NULL) { VMEM_UNLOCK(vm); return ENOMEM; } btnew2 = bt_alloc(vm, flags); /* XXX not necessary if no restrictions */ if (btnew2 == NULL) { bt_free(vm, btnew); VMEM_UNLOCK(vm); return ENOMEM; } /* * choose a free block from which we allocate. */ retry_strat: first = bt_freehead_toalloc(vm, size, strat); end = &vm->vm_freelist[VMEM_MAXORDER]; retry: bt = NULL; vmem_check(vm); if (strat == VM_INSTANTFIT) { /* * just choose the first block which satisfies our restrictions. * * note that we don't need to check the size of the blocks * because any blocks found on these list should be larger than * the given size. */ for (list = first; list < end; list++) { bt = LIST_FIRST(list); if (bt != NULL) { rc = vmem_fit(bt, size, align, phase, nocross, minaddr, maxaddr, &start); if (rc == 0) { goto gotit; } /* * don't bother to follow the bt_freelist link * here. the list can be very long and we are * told to run fast. blocks from the later free * lists are larger and have better chances to * satisfy our restrictions. */ } } } else { /* VM_BESTFIT */ /* * we assume that, for space efficiency, it's better to * allocate from a smaller block. thus we will start searching * from the lower-order list than VM_INSTANTFIT. * however, don't bother to find the smallest block in a free * list because the list can be very long. we can revisit it * if/when it turns out to be a problem. * * note that the 'first' list can contain blocks smaller than * the requested size. thus we need to check bt_size. */ for (list = first; list < end; list++) { LIST_FOREACH(bt, list, bt_freelist) { if (bt->bt_size >= size) { rc = vmem_fit(bt, size, align, phase, nocross, minaddr, maxaddr, &start); if (rc == 0) { goto gotit; } } } } } #if 1 if (strat == VM_INSTANTFIT) { strat = VM_BESTFIT; goto retry_strat; } #endif if (align != vm->vm_quantum_mask + 1 || phase != 0 || nocross != 0) { /* * XXX should try to import a region large enough to * satisfy restrictions? */ goto fail; } /* XXX eeek, minaddr & maxaddr not respected */ if (vmem_import(vm, size, flags) == 0) { goto retry; } /* XXX */ if ((flags & VM_SLEEP) != 0) { vmem_kick_pdaemon(); VMEM_CONDVAR_WAIT(vm); goto retry; } fail: bt_free(vm, btnew); bt_free(vm, btnew2); VMEM_UNLOCK(vm); return ENOMEM; gotit: KASSERT(bt->bt_type == BT_TYPE_FREE); KASSERT(bt->bt_size >= size); bt_remfree(vm, bt); vmem_check(vm); if (bt->bt_start != start) { btnew2->bt_type = BT_TYPE_FREE; btnew2->bt_start = bt->bt_start; btnew2->bt_size = start - bt->bt_start; bt->bt_start = start; bt->bt_size -= btnew2->bt_size; bt_insfree(vm, btnew2); bt_insseg(vm, btnew2, TAILQ_PREV(bt, vmem_seglist, bt_seglist)); btnew2 = NULL; vmem_check(vm); } KASSERT(bt->bt_start == start); if (bt->bt_size != size && bt->bt_size - size > vm->vm_quantum_mask) { /* split */ btnew->bt_type = BT_TYPE_BUSY; btnew->bt_start = bt->bt_start; btnew->bt_size = size; bt->bt_start = bt->bt_start + size; bt->bt_size -= size; bt_insfree(vm, bt); bt_insseg(vm, btnew, TAILQ_PREV(bt, vmem_seglist, bt_seglist)); bt_insbusy(vm, btnew); vmem_check(vm); } else { bt->bt_type = BT_TYPE_BUSY; bt_insbusy(vm, bt); vmem_check(vm); bt_free(vm, btnew); btnew = bt; } if (btnew2 != NULL) { bt_free(vm, btnew2); } KASSERT(btnew->bt_size >= size); btnew->bt_type = BT_TYPE_BUSY; if (addrp != NULL) *addrp = btnew->bt_start; VMEM_UNLOCK(vm); KASSERTMSG(addrp == NULL || (*addrp & vm->vm_quantum_mask) == 0, "vmem %s mask=0x%jx addr=0x%jx", vm->vm_name, (uintmax_t)vm->vm_quantum_mask, (uintmax_t)*addrp); return 0; } /* * vmem_free: free the resource to the arena. */ void vmem_free(vmem_t *vm, vmem_addr_t addr, vmem_size_t size) { KASSERT(size > 0); KASSERTMSG((addr & vm->vm_quantum_mask) == 0, "vmem %s mask=0x%jx addr=0x%jx", vm->vm_name, (uintmax_t)vm->vm_quantum_mask, (uintmax_t)addr); #if defined(QCACHE) if (size <= vm->vm_qcache_max) { int qidx = (size + vm->vm_quantum_mask) >> vm->vm_quantum_shift; qcache_t *qc = vm->vm_qcache[qidx - 1]; pool_cache_put(qc->qc_cache, (void *)addr); return; } #endif /* defined(QCACHE) */ vmem_xfree(vm, addr, size); } void vmem_xfree(vmem_t *vm, vmem_addr_t addr, vmem_size_t size) { bt_t *bt; KASSERT(size > 0); KASSERTMSG((addr & vm->vm_quantum_mask) == 0, "vmem %s mask=0x%jx addr=0x%jx", vm->vm_name, (uintmax_t)vm->vm_quantum_mask, (uintmax_t)addr); VMEM_LOCK(vm); bt = bt_lookupbusy(vm, addr); KASSERTMSG(bt != NULL, "vmem %s addr 0x%jx size 0x%jx", vm->vm_name, (uintmax_t)addr, (uintmax_t)size); KASSERT(bt->bt_start == addr); KASSERT(bt->bt_size == vmem_roundup_size(vm, size) || bt->bt_size - vmem_roundup_size(vm, size) <= vm->vm_quantum_mask); /* vmem_xfree_bt() drops the lock. */ vmem_xfree_bt(vm, bt); } void vmem_xfreeall(vmem_t *vm) { bt_t *bt; /* This can't be used if the arena has a quantum cache. */ KASSERT(vm->vm_qcache_max == 0); for (;;) { VMEM_LOCK(vm); TAILQ_FOREACH(bt, &vm->vm_seglist, bt_seglist) { if (bt->bt_type == BT_TYPE_BUSY) break; } if (bt != NULL) { /* vmem_xfree_bt() drops the lock. */ vmem_xfree_bt(vm, bt); } else { VMEM_UNLOCK(vm); return; } } } static void vmem_xfree_bt(vmem_t *vm, bt_t *bt) { bt_t *t; VMEM_ASSERT_LOCKED(vm); KASSERT(bt->bt_type == BT_TYPE_BUSY); bt_rembusy(vm, bt); bt->bt_type = BT_TYPE_FREE; /* coalesce */ t = TAILQ_NEXT(bt, bt_seglist); if (t != NULL && t->bt_type == BT_TYPE_FREE) { KASSERT(BT_END(bt) < t->bt_start); /* YYY */ bt_remfree(vm, t); bt_remseg(vm, t); bt->bt_size += t->bt_size; bt_free(vm, t); } t = TAILQ_PREV(bt, vmem_seglist, bt_seglist); if (t != NULL && t->bt_type == BT_TYPE_FREE) { KASSERT(BT_END(t) < bt->bt_start); /* YYY */ bt_remfree(vm, t); bt_remseg(vm, t); bt->bt_size += t->bt_size; bt->bt_start = t->bt_start; bt_free(vm, t); } t = TAILQ_PREV(bt, vmem_seglist, bt_seglist); KASSERT(t != NULL); KASSERT(BT_ISSPAN_P(t) || t->bt_type == BT_TYPE_BUSY); if (vm->vm_releasefn != NULL && t->bt_type == BT_TYPE_SPAN && t->bt_size == bt->bt_size) { vmem_addr_t spanaddr; vmem_size_t spansize; KASSERT(t->bt_start == bt->bt_start); spanaddr = bt->bt_start; spansize = bt->bt_size; bt_remseg(vm, bt); bt_free(vm, bt); bt_remseg(vm, t); bt_free(vm, t); vm->vm_size -= spansize; VMEM_CONDVAR_BROADCAST(vm); /* bt_freetrim() drops the lock. */ bt_freetrim(vm, BT_MAXFREE); (*vm->vm_releasefn)(vm->vm_arg, spanaddr, spansize); } else { bt_insfree(vm, bt); VMEM_CONDVAR_BROADCAST(vm); /* bt_freetrim() drops the lock. */ bt_freetrim(vm, BT_MAXFREE); } } /* * vmem_add: * * => caller must ensure appropriate spl, * if the arena can be accessed from interrupt context. */ int vmem_add(vmem_t *vm, vmem_addr_t addr, vmem_size_t size, vm_flag_t flags) { int rv; VMEM_LOCK(vm); rv = vmem_add1(vm, addr, size, flags, BT_TYPE_SPAN_STATIC); VMEM_UNLOCK(vm); return rv; } /* * vmem_size: information about arenas size * * => return free/allocated size in arena */ vmem_size_t vmem_size(vmem_t *vm, int typemask) { switch (typemask) { case VMEM_ALLOC: return vm->vm_inuse; case VMEM_FREE: return vm->vm_size - vm->vm_inuse; case VMEM_FREE|VMEM_ALLOC: return vm->vm_size; default: panic("vmem_size"); } } /* ---- rehash */ #if defined(_KERNEL) static struct callout vmem_rehash_ch; static int vmem_rehash_interval; static struct workqueue *vmem_rehash_wq; static struct work vmem_rehash_wk; static void vmem_rehash_all(struct work *wk, void *dummy) { vmem_t *vm; KASSERT(wk == &vmem_rehash_wk); mutex_enter(&vmem_list_lock); LIST_FOREACH(vm, &vmem_list, vm_alllist) { size_t desired; size_t current; desired = atomic_load_relaxed(&vm->vm_maxbusytag); current = atomic_load_relaxed(&vm->vm_hashsize); if (desired > VMEM_HASHSIZE_MAX) { desired = VMEM_HASHSIZE_MAX; } else if (desired < VMEM_HASHSIZE_MIN) { desired = VMEM_HASHSIZE_MIN; } if (desired > current * 2 || desired * 2 < current) { vmem_rehash(vm, desired, VM_NOSLEEP); } } mutex_exit(&vmem_list_lock); callout_schedule(&vmem_rehash_ch, vmem_rehash_interval); } static void vmem_rehash_all_kick(void *dummy) { workqueue_enqueue(vmem_rehash_wq, &vmem_rehash_wk, NULL); } void vmem_rehash_start(void) { int error; error = workqueue_create(&vmem_rehash_wq, "vmem_rehash", vmem_rehash_all, NULL, PRI_VM, IPL_SOFTCLOCK, WQ_MPSAFE); if (error) { panic("%s: workqueue_create %d\n", __func__, error); } callout_init(&vmem_rehash_ch, CALLOUT_MPSAFE); callout_setfunc(&vmem_rehash_ch, vmem_rehash_all_kick, NULL); vmem_rehash_interval = hz * 10; callout_schedule(&vmem_rehash_ch, vmem_rehash_interval); } #endif /* defined(_KERNEL) */ /* ---- debug */ #if defined(DDB) || defined(UNITTEST) || defined(VMEM_SANITY) static void bt_dump(const bt_t *, void (*)(const char *, ...) __printflike(1, 2)); static const char * bt_type_string(int type) { static const char * const table[] = { [BT_TYPE_BUSY] = "busy", [BT_TYPE_FREE] = "free", [BT_TYPE_SPAN] = "span", [BT_TYPE_SPAN_STATIC] = "static span", }; if (type >= __arraycount(table)) { return "BOGUS"; } return table[type]; } static void bt_dump(const bt_t *bt, void (*pr)(const char *, ...)) { (*pr)("\t%p: %" PRIu64 ", %" PRIu64 ", %d(%s)\n", bt, (uint64_t)bt->bt_start, (uint64_t)bt->bt_size, bt->bt_type, bt_type_string(bt->bt_type)); } static void vmem_dump(const vmem_t *vm , void (*pr)(const char *, ...) __printflike(1, 2)) { const bt_t *bt; int i; (*pr)("vmem %p '%s'\n", vm, vm->vm_name); TAILQ_FOREACH(bt, &vm->vm_seglist, bt_seglist) { bt_dump(bt, pr); } for (i = 0; i < VMEM_MAXORDER; i++) { const struct vmem_freelist *fl = &vm->vm_freelist[i]; if (LIST_EMPTY(fl)) { continue; } (*pr)("freelist[%d]\n", i); LIST_FOREACH(bt, fl, bt_freelist) { bt_dump(bt, pr); } } } #endif /* defined(DDB) || defined(UNITTEST) || defined(VMEM_SANITY) */ #if defined(DDB) static bt_t * vmem_whatis_lookup(vmem_t *vm, uintptr_t addr) { bt_t *bt; TAILQ_FOREACH(bt, &vm->vm_seglist, bt_seglist) { if (BT_ISSPAN_P(bt)) { continue; } if (bt->bt_start <= addr && addr <= BT_END(bt)) { return bt; } } return NULL; } void vmem_whatis(uintptr_t addr, void (*pr)(const char *, ...)) { vmem_t *vm; LIST_FOREACH(vm, &vmem_list, vm_alllist) { bt_t *bt; bt = vmem_whatis_lookup(vm, addr); if (bt == NULL) { continue; } (*pr)("%p is %p+%zu in VMEM '%s' (%s)\n", (void *)addr, (void *)bt->bt_start, (size_t)(addr - bt->bt_start), vm->vm_name, (bt->bt_type == BT_TYPE_BUSY) ? "allocated" : "free"); } } void vmem_printall(const char *modif, void (*pr)(const char *, ...)) { const vmem_t *vm; LIST_FOREACH(vm, &vmem_list, vm_alllist) { vmem_dump(vm, pr); } } void vmem_print(uintptr_t addr, const char *modif, void (*pr)(const char *, ...)) { const vmem_t *vm = (const void *)addr; vmem_dump(vm, pr); } #endif /* defined(DDB) */ #if defined(_KERNEL) #define vmem_printf printf #else #include <stdio.h> #include <stdarg.h> static void vmem_printf(const char *fmt, ...) { va_list ap; va_start(ap, fmt); vprintf(fmt, ap); va_end(ap); } #endif #if defined(VMEM_SANITY) static bool vmem_check_sanity(vmem_t *vm) { const bt_t *bt, *bt2; KASSERT(vm != NULL); TAILQ_FOREACH(bt, &vm->vm_seglist, bt_seglist) { if (bt->bt_start > BT_END(bt)) { printf("corrupted tag\n"); bt_dump(bt, vmem_printf); return false; } } TAILQ_FOREACH(bt, &vm->vm_seglist, bt_seglist) { TAILQ_FOREACH(bt2, &vm->vm_seglist, bt_seglist) { if (bt == bt2) { continue; } if (BT_ISSPAN_P(bt) != BT_ISSPAN_P(bt2)) { continue; } if (bt->bt_start <= BT_END(bt2) && bt2->bt_start <= BT_END(bt)) { printf("overwrapped tags\n"); bt_dump(bt, vmem_printf); bt_dump(bt2, vmem_printf); return false; } } } return true; } static void vmem_check(vmem_t *vm) { if (!vmem_check_sanity(vm)) { panic("insanity vmem %p", vm); } } #endif /* defined(VMEM_SANITY) */ #if defined(UNITTEST) int main(void) { int rc; vmem_t *vm; vmem_addr_t p; struct reg { vmem_addr_t p; vmem_size_t sz; bool x; } *reg = NULL; int nreg = 0; int nalloc = 0; int nfree = 0; vmem_size_t total = 0; #if 1 vm_flag_t strat = VM_INSTANTFIT; #else vm_flag_t strat = VM_BESTFIT; #endif vm = vmem_create("test", 0, 0, 1, NULL, NULL, NULL, 0, VM_SLEEP, #ifdef _KERNEL IPL_NONE #else 0 #endif ); if (vm == NULL) { printf("vmem_create\n"); exit(EXIT_FAILURE); } vmem_dump(vm, vmem_printf); rc = vmem_add(vm, 0, 50, VM_SLEEP); assert(rc == 0); rc = vmem_add(vm, 100, 200, VM_SLEEP); assert(rc == 0); rc = vmem_add(vm, 2000, 1, VM_SLEEP); assert(rc == 0); rc = vmem_add(vm, 40000, 65536, VM_SLEEP); assert(rc == 0); rc = vmem_add(vm, 10000, 10000, VM_SLEEP); assert(rc == 0); rc = vmem_add(vm, 500, 1000, VM_SLEEP); assert(rc == 0); rc = vmem_add(vm, 0xffffff00, 0x100, VM_SLEEP); assert(rc == 0); rc = vmem_xalloc(vm, 0x101, 0, 0, 0, 0xffffff00, 0xffffffff, strat|VM_SLEEP, &p); assert(rc != 0); rc = vmem_xalloc(vm, 50, 0, 0, 0, 0, 49, strat|VM_SLEEP, &p); assert(rc == 0 && p == 0); vmem_xfree(vm, p, 50); rc = vmem_xalloc(vm, 25, 0, 0, 0, 0, 24, strat|VM_SLEEP, &p); assert(rc == 0 && p == 0); rc = vmem_xalloc(vm, 0x100, 0, 0, 0, 0xffffff01, 0xffffffff, strat|VM_SLEEP, &p); assert(rc != 0); rc = vmem_xalloc(vm, 0x100, 0, 0, 0, 0xffffff00, 0xfffffffe, strat|VM_SLEEP, &p); assert(rc != 0); rc = vmem_xalloc(vm, 0x100, 0, 0, 0, 0xffffff00, 0xffffffff, strat|VM_SLEEP, &p); assert(rc == 0); vmem_dump(vm, vmem_printf); for (;;) { struct reg *r; int t = rand() % 100; if (t > 45) { /* alloc */ vmem_size_t sz = rand() % 500 + 1; bool x; vmem_size_t align, phase, nocross; vmem_addr_t minaddr, maxaddr; if (t > 70) { x = true; /* XXX */ align = 1 << (rand() % 15); phase = rand() % 65536; nocross = 1 << (rand() % 15); if (align <= phase) { phase = 0; } if (VMEM_CROSS_P(phase, phase + sz - 1, nocross)) { nocross = 0; } do { minaddr = rand() % 50000; maxaddr = rand() % 70000; } while (minaddr > maxaddr); printf("=== xalloc %" PRIu64 " align=%" PRIu64 ", phase=%" PRIu64 ", nocross=%" PRIu64 ", min=%" PRIu64 ", max=%" PRIu64 "\n", (uint64_t)sz, (uint64_t)align, (uint64_t)phase, (uint64_t)nocross, (uint64_t)minaddr, (uint64_t)maxaddr); rc = vmem_xalloc(vm, sz, align, phase, nocross, minaddr, maxaddr, strat|VM_SLEEP, &p); } else { x = false; printf("=== alloc %" PRIu64 "\n", (uint64_t)sz); rc = vmem_alloc(vm, sz, strat|VM_SLEEP, &p); } printf("-> %" PRIu64 "\n", (uint64_t)p); vmem_dump(vm, vmem_printf); if (rc != 0) { if (x) { continue; } break; } nreg++; reg = realloc(reg, sizeof(*reg) * nreg); r = ®[nreg - 1]; r->p = p; r->sz = sz; r->x = x; total += sz; nalloc++; } else if (nreg != 0) { /* free */ r = ®[rand() % nreg]; printf("=== free %" PRIu64 ", %" PRIu64 "\n", (uint64_t)r->p, (uint64_t)r->sz); if (r->x) { vmem_xfree(vm, r->p, r->sz); } else { vmem_free(vm, r->p, r->sz); } total -= r->sz; vmem_dump(vm, vmem_printf); *r = reg[nreg - 1]; nreg--; nfree++; } printf("total=%" PRIu64 "\n", (uint64_t)total); } fprintf(stderr, "total=%" PRIu64 ", nalloc=%d, nfree=%d\n", (uint64_t)total, nalloc, nfree); exit(EXIT_SUCCESS); } #endif /* defined(UNITTEST) */ |
1 1 8 2 2 2 1 1 7 2 2 1 3 3 3 2 1 1 1 1 1 1 1 1 1 1 1 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 | /* $NetBSD: pci_usrreq.c,v 1.31 2021/09/05 03:47:24 mrg Exp $ */ /* * Copyright 2001 Wasabi Systems, Inc. * All rights reserved. * * Written by Jason R. Thorpe for Wasabi Systems, Inc. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * This product includes software developed for the NetBSD Project by * Wasabi Systems, Inc. * 4. The name of Wasabi Systems, Inc. may not be used to endorse * or promote products derived from this software without specific prior * written permission. * * THIS SOFTWARE IS PROVIDED BY WASABI SYSTEMS, INC. ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL WASABI SYSTEMS, INC * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ /* * User -> kernel interface for PCI bus access. */ #include <sys/cdefs.h> __KERNEL_RCSID(0, "$NetBSD: pci_usrreq.c,v 1.31 2021/09/05 03:47:24 mrg Exp $"); #ifdef _KERNEL_OPT #include "opt_pci.h" #endif #include <sys/param.h> #include <sys/conf.h> #include <sys/device.h> #include <sys/ioctl.h> #include <sys/proc.h> #include <sys/systm.h> #include <sys/errno.h> #include <sys/fcntl.h> #include <sys/kauth.h> #include <dev/pci/pcireg.h> #include <dev/pci/pcivar.h> #include <dev/pci/pciio.h> static int pciopen(dev_t dev, int flags, int mode, struct lwp *l) { device_t dv; dv = device_lookup(&pci_cd, minor(dev)); if (dv == NULL) return ENXIO; return 0; } static int pciioctl(dev_t dev, u_long cmd, void *data, int flag, struct lwp *l) { struct pci_softc *sc = device_lookup_private(&pci_cd, minor(dev)); struct pci_child *child; struct pciio_bdf_cfgreg *bdfr; struct pciio_businfo *binfo; struct pciio_drvname *dname; struct pciio_drvnameonbus *dnameonbus; pcitag_t tag; switch (cmd) { case PCI_IOC_BDF_CFGREAD: case PCI_IOC_BDF_CFGWRITE: bdfr = data; if (bdfr->bus > 255 || bdfr->device >= sc->sc_maxndevs || bdfr->function > 7 || ISSET(bdfr->cfgreg.reg, 3)) return EINVAL; tag = pci_make_tag(sc->sc_pc, bdfr->bus, bdfr->device, bdfr->function); if (cmd == PCI_IOC_BDF_CFGREAD) { bdfr->cfgreg.val = pci_conf_read(sc->sc_pc, tag, bdfr->cfgreg.reg); } else { if ((flag & FWRITE) == 0) return EBADF; pci_conf_write(sc->sc_pc, tag, bdfr->cfgreg.reg, bdfr->cfgreg.val); } return 0; case PCI_IOC_BUSINFO: binfo = data; binfo->busno = sc->sc_bus; binfo->maxdevs = sc->sc_maxndevs; return 0; case PCI_IOC_DRVNAME: dname = data; if (dname->device >= sc->sc_maxndevs || dname->function > 7) return EINVAL; child = &sc->PCI_SC_DEVICESC(dname->device, dname->function); if (!child->c_dev) return ENXIO; strlcpy(dname->name, device_xname(child->c_dev), sizeof dname->name); return 0; case PCI_IOC_DRVNAMEONBUS: dnameonbus = data; int i; for (i = 0; i < pci_cd.cd_ndevs; i++) { sc = device_lookup_private(&pci_cd, i); if (sc == NULL) continue; if (sc->sc_bus == dnameonbus->bus) break; /* found the right bus */ } if (i == pci_cd.cd_ndevs || sc == NULL) return ENXIO; if (dnameonbus->device >= sc->sc_maxndevs || dnameonbus->function > 7) return EINVAL; child = &sc->PCI_SC_DEVICESC(dnameonbus->device, dnameonbus->function); if (!child->c_dev) return ENXIO; strlcpy(dnameonbus->name, device_xname(child->c_dev), sizeof dnameonbus->name); return 0; default: return ENOTTY; } } static paddr_t pcimmap(dev_t dev, off_t offset, int prot) { struct pci_softc *sc = device_lookup_private(&pci_cd, minor(dev)); struct pci_child *c; struct pci_range *r; int flags = 0; int device, range; if (kauth_authorize_machdep(kauth_cred_get(), KAUTH_MACHDEP_UNMANAGEDMEM, NULL, NULL, NULL, NULL) != 0) { return -1; } /* * Since we allow mapping of the entire bus, we * take the offset to be the address on the bus, * and pass 0 as the offset into that range. * * XXX Need a way to deal with linear/etc. * * XXX we rely on MD mmap() methods to enforce limits since these * are hidden in *_tag_t structs if they exist at all */ #ifdef PCI_MAGIC_IO_RANGE /* * first, check if someone's trying to map the IO range * XXX this assumes 64kB IO space even though some machines can have * significantly more than that - macppc's bandit host bridge allows * 8MB IO space and sparc64 may have the entire 4GB available. The * firmware on both tries to use the lower 64kB first though and * exausting it is pretty difficult so we should be safe */ if ((offset >= PCI_MAGIC_IO_RANGE) && (offset < (PCI_MAGIC_IO_RANGE + 0x10000))) { return bus_space_mmap(sc->sc_iot, offset - PCI_MAGIC_IO_RANGE, 0, prot, 0); } #endif /* PCI_MAGIC_IO_RANGE */ for (device = 0; device < __arraycount(sc->sc_devices); device++) { c = &sc->sc_devices[device]; if (c->c_dev == NULL) continue; for (range = 0; range < __arraycount(c->c_range); range++) { r = &c->c_range[range]; if (r->r_size == 0) break; if (offset >= r->r_offset && offset < r->r_offset + r->r_size) { flags = r->r_flags; break; } } } return bus_space_mmap(sc->sc_memt, offset, 0, prot, flags); } const struct cdevsw pci_cdevsw = { .d_open = pciopen, .d_close = nullclose, .d_read = noread, .d_write = nowrite, .d_ioctl = pciioctl, .d_stop = nostop, .d_tty = notty, .d_poll = nopoll, .d_mmap = pcimmap, .d_kqfilter = nokqfilter, .d_discard = nodiscard, .d_flag = D_OTHER }; /* * pci_devioctl: * * PCI ioctls that can be performed on devices directly. */ int pci_devioctl(pci_chipset_tag_t pc, pcitag_t tag, u_long cmd, void *data, int flag, struct lwp *l) { struct pciio_cfgreg *r = (void *) data; switch (cmd) { case PCI_IOC_CFGREAD: r->val = pci_conf_read(pc, tag, r->reg); break; case PCI_IOC_CFGWRITE: if ((flag & FWRITE) == 0) return EBADF; pci_conf_write(pc, tag, r->reg, r->val); break; default: return EPASSTHROUGH; } return 0; } |
1 1 37 37 34 2 1 1 36 16 13 1 12 1 11 11 14 2 2 12 13 11 11 11 4 3 10 11 7 11 5 3 6 4 4 4 2 2 6 6 6 6 10 16 3 1 3 16 7 7 5 2 10 10 7 2 2 2 2 2 16 16 2 47 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 | /* $NetBSD: udp6_usrreq.c,v 1.150 2021/02/19 14:52:00 christos Exp $ */ /* $KAME: udp6_usrreq.c,v 1.86 2001/05/27 17:33:00 itojun Exp $ */ /* $KAME: udp6_output.c,v 1.43 2001/10/15 09:19:52 itojun Exp $ */ /* * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the project nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ /* * Copyright (c) 1982, 1986, 1989, 1993 * The Regents of the University of California. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * @(#)udp_var.h 8.1 (Berkeley) 6/10/93 */ #include <sys/cdefs.h> __KERNEL_RCSID(0, "$NetBSD: udp6_usrreq.c,v 1.150 2021/02/19 14:52:00 christos Exp $"); #ifdef _KERNEL_OPT #include "opt_inet.h" #include "opt_inet_csum.h" #include "opt_ipsec.h" #include "opt_net_mpsafe.h" #endif #include <sys/param.h> #include <sys/mbuf.h> #include <sys/protosw.h> #include <sys/socket.h> #include <sys/socketvar.h> #include <sys/systm.h> #include <sys/proc.h> #include <sys/syslog.h> #include <sys/domain.h> #include <sys/sysctl.h> #include <net/if.h> #include <net/if_types.h> #include <netinet/in.h> #include <netinet/in_var.h> #include <netinet/in_systm.h> #include <netinet/in_offload.h> #include <netinet/ip.h> #include <netinet/ip_var.h> #include <netinet/in_pcb.h> #include <netinet/udp.h> #include <netinet/udp_var.h> #include <netinet/udp_private.h> #include <netinet/ip6.h> #include <netinet/icmp6.h> #include <netinet6/ip6_var.h> #include <netinet6/ip6_private.h> #include <netinet6/in6_pcb.h> #include <netinet6/udp6_var.h> #include <netinet6/udp6_private.h> #include <netinet6/ip6protosw.h> #include <netinet6/scope6_var.h> #ifdef IPSEC #include <netipsec/ipsec.h> #include <netipsec/esp.h> #ifdef INET6 #include <netipsec/ipsec6.h> #endif #endif #include "faith.h" #if defined(NFAITH) && NFAITH > 0 #include <net/if_faith.h> #endif /* * UDP protocol implementation. * Per RFC 768, August, 1980. */ extern struct inpcbtable udbtable; percpu_t *udp6stat_percpu; /* UDP on IP6 parameters */ static int udp6_sendspace = 9216; /* really max datagram size */ static int udp6_recvspace = 40 * (1024 + sizeof(struct sockaddr_in6)); /* 40 1K datagrams */ static void udp6_notify(struct in6pcb *, int); static void sysctl_net_inet6_udp6_setup(struct sysctllog **); #ifdef IPSEC static int udp6_espinudp(struct mbuf **, int); #endif #ifdef UDP_CSUM_COUNTERS #include <sys/device.h> struct evcnt udp6_hwcsum_bad = EVCNT_INITIALIZER(EVCNT_TYPE_MISC, NULL, "udp6", "hwcsum bad"); struct evcnt udp6_hwcsum_ok = EVCNT_INITIALIZER(EVCNT_TYPE_MISC, NULL, "udp6", "hwcsum ok"); struct evcnt udp6_hwcsum_data = EVCNT_INITIALIZER(EVCNT_TYPE_MISC, NULL, "udp6", "hwcsum data"); struct evcnt udp6_swcsum = EVCNT_INITIALIZER(EVCNT_TYPE_MISC, NULL, "udp6", "swcsum"); EVCNT_ATTACH_STATIC(udp6_hwcsum_bad); EVCNT_ATTACH_STATIC(udp6_hwcsum_ok); EVCNT_ATTACH_STATIC(udp6_hwcsum_data); EVCNT_ATTACH_STATIC(udp6_swcsum); #define UDP_CSUM_COUNTER_INCR(ev) (ev)->ev_count++ #else #define UDP_CSUM_COUNTER_INCR(ev) /* nothing */ #endif void udp6_init(void) { sysctl_net_inet6_udp6_setup(NULL); udp6stat_percpu = percpu_alloc(sizeof(uint64_t) * UDP6_NSTATS); udp_init_common(); } /* * Notify a udp user of an asynchronous error; * just wake up so that he can collect error status. */ static void udp6_notify(struct in6pcb *in6p, int errno) { in6p->in6p_socket->so_error = errno; sorwakeup(in6p->in6p_socket); sowwakeup(in6p->in6p_socket); } void * udp6_ctlinput(int cmd, const struct sockaddr *sa, void *d) { struct udphdr uh; struct ip6_hdr *ip6; const struct sockaddr_in6 *sa6 = (const struct sockaddr_in6 *)sa; struct mbuf *m; int off; void *cmdarg; struct ip6ctlparam *ip6cp = NULL; const struct sockaddr_in6 *sa6_src = NULL; void (*notify)(struct in6pcb *, int) = udp6_notify; struct udp_portonly { u_int16_t uh_sport; u_int16_t uh_dport; } *uhp; if (sa->sa_family != AF_INET6 || sa->sa_len != sizeof(struct sockaddr_in6)) return NULL; if ((unsigned)cmd >= PRC_NCMDS) return NULL; if (PRC_IS_REDIRECT(cmd)) notify = in6_rtchange, d = NULL; else if (cmd == PRC_HOSTDEAD) d = NULL; else if (cmd == PRC_MSGSIZE) { /* special code is present, see below */ notify = in6_rtchange; } else if (inet6ctlerrmap[cmd] == 0) return NULL; /* if the parameter is from icmp6, decode it. */ if (d != NULL) { ip6cp = (struct ip6ctlparam *)d; m = ip6cp->ip6c_m; ip6 = ip6cp->ip6c_ip6; off = ip6cp->ip6c_off; cmdarg = ip6cp->ip6c_cmdarg; sa6_src = ip6cp->ip6c_src; } else { m = NULL; ip6 = NULL; cmdarg = NULL; sa6_src = &sa6_any; off = 0; } if (ip6) { /* check if we can safely examine src and dst ports */ if (m->m_pkthdr.len < off + sizeof(*uhp)) { if (cmd == PRC_MSGSIZE) icmp6_mtudisc_update((struct ip6ctlparam *)d, 0); return NULL; } memset(&uh, 0, sizeof(uh)); m_copydata(m, off, sizeof(*uhp), (void *)&uh); if (cmd == PRC_MSGSIZE) { int valid = 0; /* * Check to see if we have a valid UDP socket * corresponding to the address in the ICMPv6 message * payload. */ if (in6_pcblookup_connect(&udbtable, &sa6->sin6_addr, uh.uh_dport, (const struct in6_addr *)&sa6_src->sin6_addr, uh.uh_sport, 0, 0)) valid++; #if 0 /* * As the use of sendto(2) is fairly popular, * we may want to allow non-connected pcb too. * But it could be too weak against attacks... * We should at least check if the local address (= s) * is really ours. */ else if (in6_pcblookup_bind(&udbtable, &sa6->sin6_addr, uh.uh_dport, 0)) valid++; #endif /* * Depending on the value of "valid" and routing table * size (mtudisc_{hi,lo}wat), we will: * - recalculate the new MTU and create the * corresponding routing entry, or * - ignore the MTU change notification. */ icmp6_mtudisc_update((struct ip6ctlparam *)d, valid); /* * regardless of if we called * icmp6_mtudisc_update(), we need to call * in6_pcbnotify(), to notify path MTU change * to the userland (RFC3542), because some * unconnected sockets may share the same * destination and want to know the path MTU. */ } (void)in6_pcbnotify(&udbtable, sa, uh.uh_dport, sin6tocsa(sa6_src), uh.uh_sport, cmd, cmdarg, notify); } else { (void)in6_pcbnotify(&udbtable, sa, 0, sin6tocsa(sa6_src), 0, cmd, cmdarg, notify); } return NULL; } int udp6_ctloutput(int op, struct socket *so, struct sockopt *sopt) { int s; int error = 0; struct in6pcb *in6p; int family; int optval; family = so->so_proto->pr_domain->dom_family; s = splsoftnet(); switch (family) { #ifdef INET case PF_INET: if (sopt->sopt_level != IPPROTO_UDP) { error = ip_ctloutput(op, so, sopt); goto end; } break; #endif #ifdef INET6 case PF_INET6: if (sopt->sopt_level != IPPROTO_UDP) { error = ip6_ctloutput(op, so, sopt); goto end; } break; #endif default: error = EAFNOSUPPORT; goto end; } switch (op) { case PRCO_SETOPT: in6p = sotoin6pcb(so); switch (sopt->sopt_name) { case UDP_ENCAP: error = sockopt_getint(sopt, &optval); if (error) break; switch(optval) { case 0: in6p->in6p_flags &= ~IN6P_ESPINUDP; break; case UDP_ENCAP_ESPINUDP: in6p->in6p_flags |= IN6P_ESPINUDP; break; default: error = EINVAL; break; } break; default: error = ENOPROTOOPT; break; } break; default: error = EINVAL; break; } end: splx(s); return error; } static void udp6_sendup(struct mbuf *m, int off /* offset of data portion */, struct sockaddr *src, struct socket *so) { struct mbuf *opts = NULL; struct mbuf *n; struct in6pcb *in6p; KASSERT(so != NULL); KASSERT(so->so_proto->pr_domain->dom_family == AF_INET6); in6p = sotoin6pcb(so); KASSERT(in6p != NULL); #if defined(IPSEC) if (ipsec_used && ipsec_in_reject(m, in6p)) { if ((n = m_copypacket(m, M_DONTWAIT)) != NULL) icmp6_error(n, ICMP6_DST_UNREACH, ICMP6_DST_UNREACH_ADMIN, 0); return; } #endif if ((n = m_copypacket(m, M_DONTWAIT)) != NULL) { if (in6p->in6p_flags & IN6P_CONTROLOPTS || SOOPT_TIMESTAMP(in6p->in6p_socket->so_options)) { struct ip6_hdr *ip6 = mtod(n, struct ip6_hdr *); ip6_savecontrol(in6p, &opts, ip6, n); } m_adj(n, off); if (sbappendaddr(&so->so_rcv, src, n, opts) == 0) { m_freem(n); if (opts) m_freem(opts); UDP6_STATINC(UDP6_STAT_FULLSOCK); soroverflow(so); } else sorwakeup(so); } } int udp6_realinput(int af, struct sockaddr_in6 *src, struct sockaddr_in6 *dst, struct mbuf **mp, int off) { u_int16_t sport, dport; int rcvcnt; struct in6_addr src6, *dst6; const struct in_addr *dst4; struct inpcb_hdr *inph; struct in6pcb *in6p; struct mbuf *m = *mp; rcvcnt = 0; off += sizeof(struct udphdr); /* now, offset of payload */ if (af != AF_INET && af != AF_INET6) goto bad; if (src->sin6_family != AF_INET6 || dst->sin6_family != AF_INET6) goto bad; src6 = src->sin6_addr; if (sa6_recoverscope(src) != 0) { /* XXX: should be impossible. */ goto bad; } sport = src->sin6_port; dport = dst->sin6_port; dst4 = (struct in_addr *)&dst->sin6_addr.s6_addr[12]; dst6 = &dst->sin6_addr; if (IN6_IS_ADDR_MULTICAST(dst6) || (af == AF_INET && IN_MULTICAST(dst4->s_addr))) { /* * Deliver a multicast or broadcast datagram to *all* sockets * for which the local and remote addresses and ports match * those of the incoming datagram. This allows more than * one process to receive multi/broadcasts on the same port. * (This really ought to be done for unicast datagrams as * well, but that would cause problems with existing * applications that open both address-specific sockets and * a wildcard socket listening to the same port -- they would * end up receiving duplicates of every unicast datagram. * Those applications open the multiple sockets to overcome an * inadequacy of the UDP socket interface, but for backwards * compatibility we avoid the problem here rather than * fixing the interface. Maybe 4.5BSD will remedy this?) */ /* * KAME note: traditionally we dropped udpiphdr from mbuf here. * we need udpiphdr for IPsec processing so we do that later. */ /* * Locate pcb(s) for datagram. */ TAILQ_FOREACH(inph, &udbtable.inpt_queue, inph_queue) { in6p = (struct in6pcb *)inph; if (in6p->in6p_af != AF_INET6) continue; if (in6p->in6p_lport != dport) continue; if (!IN6_IS_ADDR_UNSPECIFIED(&in6p->in6p_laddr)) { if (!IN6_ARE_ADDR_EQUAL(&in6p->in6p_laddr, dst6)) continue; } else { if (IN6_IS_ADDR_V4MAPPED(dst6) && (in6p->in6p_flags & IN6P_IPV6_V6ONLY)) continue; } if (!IN6_IS_ADDR_UNSPECIFIED(&in6p->in6p_faddr)) { if (!IN6_ARE_ADDR_EQUAL(&in6p->in6p_faddr, &src6) || in6p->in6p_fport != sport) continue; } else { if (IN6_IS_ADDR_V4MAPPED(&src6) && (in6p->in6p_flags & IN6P_IPV6_V6ONLY)) continue; } udp6_sendup(m, off, sin6tosa(src), in6p->in6p_socket); rcvcnt++; /* * Don't look for additional matches if this one does * not have either the SO_REUSEPORT or SO_REUSEADDR * socket options set. This heuristic avoids searching * through all pcbs in the common case of a non-shared * port. It assumes that an application will never * clear these options after setting them. */ if ((in6p->in6p_socket->so_options & (SO_REUSEPORT|SO_REUSEADDR)) == 0) break; } } else { /* * Locate pcb for datagram. */ in6p = in6_pcblookup_connect(&udbtable, &src6, sport, dst6, dport, 0, 0); if (in6p == 0) { UDP_STATINC(UDP_STAT_PCBHASHMISS); in6p = in6_pcblookup_bind(&udbtable, dst6, dport, 0); if (in6p == 0) return rcvcnt; } #ifdef IPSEC /* Handle ESP over UDP */ if (in6p->in6p_flags & IN6P_ESPINUDP) { switch (udp6_espinudp(mp, off)) { case -1: /* Error, m was freed */ rcvcnt = -1; goto bad; case 1: /* ESP over UDP */ rcvcnt++; goto bad; case 0: /* plain UDP */ default: /* Unexpected */ /* * Normal UDP processing will take place, * m may have changed. */ m = *mp; break; } } #endif if (in6p->in6p_overudp_cb != NULL) { int ret; ret = in6p->in6p_overudp_cb(mp, off, in6p->in6p_socket, sin6tosa(src), in6p->in6p_overudp_arg); switch (ret) { case -1: /* Error, m was freed */ rcvcnt = -1; goto bad; case 1: /* Foo over UDP */ KASSERT(*mp == NULL); rcvcnt++; goto bad; case 0: /* plain UDP */ default: /* Unexpected */ /* * Normal UDP processing will take place, * m may have changed. */ break; } } udp6_sendup(m, off, sin6tosa(src), in6p->in6p_socket); rcvcnt++; } bad: return rcvcnt; } int udp6_input_checksum(struct mbuf *m, const struct udphdr *uh, int off, int len) { /* * XXX it's better to record and check if this mbuf is * already checked. */ if (__predict_false((m->m_flags & M_LOOP) && !udp_do_loopback_cksum)) { goto good; } if (uh->uh_sum == 0) { UDP6_STATINC(UDP6_STAT_NOSUM); goto bad; } switch (m->m_pkthdr.csum_flags & ((m_get_rcvif_NOMPSAFE(m)->if_csum_flags_rx & M_CSUM_UDPv6) | M_CSUM_TCP_UDP_BAD | M_CSUM_DATA)) { case M_CSUM_UDPv6|M_CSUM_TCP_UDP_BAD: UDP_CSUM_COUNTER_INCR(&udp6_hwcsum_bad); UDP6_STATINC(UDP6_STAT_BADSUM); goto bad; #if 0 /* notyet */ case M_CSUM_UDPv6|M_CSUM_DATA: #endif case M_CSUM_UDPv6: /* Checksum was okay. */ UDP_CSUM_COUNTER_INCR(&udp6_hwcsum_ok); break; default: /* * Need to compute it ourselves. Maybe skip checksum * on loopback interfaces. */ UDP_CSUM_COUNTER_INCR(&udp6_swcsum); if (in6_cksum(m, IPPROTO_UDP, off, len) != 0) { UDP6_STATINC(UDP6_STAT_BADSUM); goto bad; } } good: return 0; bad: return -1; } int udp6_input(struct mbuf **mp, int *offp, int proto) { struct mbuf *m = *mp; int off = *offp; struct sockaddr_in6 src, dst; struct ip6_hdr *ip6; struct udphdr *uh; u_int32_t plen, ulen; ip6 = mtod(m, struct ip6_hdr *); #if defined(NFAITH) && 0 < NFAITH if (faithprefix(&ip6->ip6_dst)) { /* send icmp6 host unreach? */ m_freem(m); return IPPROTO_DONE; } #endif UDP6_STATINC(UDP6_STAT_IPACKETS); /* Check for jumbogram is done in ip6_input. We can trust pkthdr.len. */ plen = m->m_pkthdr.len - off; IP6_EXTHDR_GET(uh, struct udphdr *, m, off, sizeof(struct udphdr)); if (uh == NULL) { IP6_STATINC(IP6_STAT_TOOSHORT); return IPPROTO_DONE; } /* * Enforce alignment requirements that are violated in * some cases, see kern/50766 for details. */ if (ACCESSIBLE_POINTER(uh, struct udphdr) == 0) { m = m_copyup(m, off + sizeof(struct udphdr), 0); if (m == NULL) { IP6_STATINC(IP6_STAT_TOOSHORT); return IPPROTO_DONE; } ip6 = mtod(m, struct ip6_hdr *); uh = (struct udphdr *)(mtod(m, char *) + off); } KASSERT(ACCESSIBLE_POINTER(uh, struct udphdr)); ulen = ntohs((u_short)uh->uh_ulen); /* * RFC2675 section 4: jumbograms will have 0 in the UDP header field, * iff payload length > 0xffff. */ if (ulen == 0 && plen > 0xffff) ulen = plen; if (plen != ulen) { UDP6_STATINC(UDP6_STAT_BADLEN); goto bad; } /* destination port of 0 is illegal, based on RFC768. */ if (uh->uh_dport == 0) goto bad; /* * Checksum extended UDP header and data. Maybe skip checksum * on loopback interfaces. */ if (udp6_input_checksum(m, uh, off, ulen)) goto bad; /* * Construct source and dst sockaddrs. */ memset(&src, 0, sizeof(src)); src.sin6_family = AF_INET6; src.sin6_len = sizeof(struct sockaddr_in6); src.sin6_addr = ip6->ip6_src; src.sin6_port = uh->uh_sport; memset(&dst, 0, sizeof(dst)); dst.sin6_family = AF_INET6; dst.sin6_len = sizeof(struct sockaddr_in6); dst.sin6_addr = ip6->ip6_dst; dst.sin6_port = uh->uh_dport; if (udp6_realinput(AF_INET6, &src, &dst, &m, off) == 0) { if (m->m_flags & M_MCAST) { UDP6_STATINC(UDP6_STAT_NOPORTMCAST); goto bad; } UDP6_STATINC(UDP6_STAT_NOPORT); icmp6_error(m, ICMP6_DST_UNREACH, ICMP6_DST_UNREACH_NOPORT, 0); m = NULL; } bad: if (m) m_freem(m); return IPPROTO_DONE; } int udp6_output(struct in6pcb * const in6p, struct mbuf *m, struct sockaddr_in6 * const addr6, struct mbuf * const control, struct lwp * const l) { u_int32_t ulen = m->m_pkthdr.len; u_int32_t plen = sizeof(struct udphdr) + ulen; struct ip6_hdr *ip6; struct udphdr *udp6; struct in6_addr _laddr, *laddr, *faddr; struct in6_addr laddr_mapped; /* XXX ugly */ struct sockaddr_in6 *sin6 = NULL; struct ifnet *oifp = NULL; int scope_ambiguous = 0; u_int16_t fport; int error = 0; struct ip6_pktopts *optp = NULL; struct ip6_pktopts opt; int af = AF_INET6, hlen = sizeof(struct ip6_hdr); #ifdef INET struct ip *ip; struct udpiphdr *ui; int flags = 0; #endif struct sockaddr_in6 tmp; if (addr6) { sin6 = addr6; if (sin6->sin6_len != sizeof(*sin6)) { error = EINVAL; goto release; } if (sin6->sin6_family != AF_INET6) { error = EAFNOSUPPORT; goto release; } /* protect *sin6 from overwrites */ tmp = *sin6; sin6 = &tmp; /* * Application should provide a proper zone ID or the use of * default zone IDs should be enabled. Unfortunately, some * applications do not behave as it should, so we need a * workaround. Even if an appropriate ID is not determined, * we'll see if we can determine the outgoing interface. If we * can, determine the zone ID based on the interface below. */ if (sin6->sin6_scope_id == 0 && !ip6_use_defzone) scope_ambiguous = 1; if ((error = sa6_embedscope(sin6, ip6_use_defzone)) != 0) goto release; } if (control) { if (__predict_false(l == NULL)) { panic("%s: control but no lwp", __func__); } if ((error = ip6_setpktopts(control, &opt, in6p->in6p_outputopts, l->l_cred, IPPROTO_UDP)) != 0) goto release; optp = &opt; } else optp = in6p->in6p_outputopts; if (sin6) { /* * Slightly different than v4 version in that we call * in6_selectsrc and in6_pcbsetport to fill in the local * address and port rather than in_pcbconnect. in_pcbconnect * sets in6p_faddr which causes EISCONN below to be hit on * subsequent sendto. */ if (sin6->sin6_port == 0) { error = EADDRNOTAVAIL; goto release; } if (!IN6_IS_ADDR_UNSPECIFIED(&in6p->in6p_faddr)) { /* how about ::ffff:0.0.0.0 case? */ error = EISCONN; goto release; } faddr = &sin6->sin6_addr; fport = sin6->sin6_port; /* allow 0 port */ if (IN6_IS_ADDR_V4MAPPED(faddr)) { if ((in6p->in6p_flags & IN6P_IPV6_V6ONLY)) { /* * I believe we should explicitly discard the * packet when mapped addresses are disabled, * rather than send the packet as an IPv6 one. * If we chose the latter approach, the packet * might be sent out on the wire based on the * default route, the situation which we'd * probably want to avoid. * (20010421 jinmei@kame.net) */ error = EINVAL; goto release; } if (!IN6_IS_ADDR_UNSPECIFIED(&in6p->in6p_laddr) && !IN6_IS_ADDR_V4MAPPED(&in6p->in6p_laddr)) { /* * when remote addr is an IPv4-mapped address, * local addr should not be an IPv6 address, * since you cannot determine how to map IPv6 * source address to IPv4. */ error = EINVAL; goto release; } af = AF_INET; } if (!IN6_IS_ADDR_V4MAPPED(faddr)) { struct psref psref; int bound = curlwp_bind(); error = in6_selectsrc(sin6, optp, in6p->in6p_moptions, &in6p->in6p_route, &in6p->in6p_laddr, &oifp, &psref, &_laddr); if (error) laddr = NULL; else laddr = &_laddr; if (oifp && scope_ambiguous && (error = in6_setscope(&sin6->sin6_addr, oifp, NULL))) { if_put(oifp, &psref); curlwp_bindx(bound); goto release; } if_put(oifp, &psref); curlwp_bindx(bound); } else { /* * XXX: freebsd[34] does not have in_selectsrc, but * we can omit the whole part because freebsd4 calls * udp_output() directly in this case, and thus we'll * never see this path. */ if (IN6_IS_ADDR_UNSPECIFIED(&in6p->in6p_laddr)) { struct sockaddr_in sin_dst; struct in_addr ina; struct in_ifaddr *ia4; struct psref _psref; int bound; memcpy(&ina, &faddr->s6_addr[12], sizeof(ina)); sockaddr_in_init(&sin_dst, &ina, 0); bound = curlwp_bind(); ia4 = in_selectsrc(&sin_dst, &in6p->in6p_route, in6p->in6p_socket->so_options, NULL, &error, &_psref); if (ia4 == NULL) { curlwp_bindx(bound); if (error == 0) error = EADDRNOTAVAIL; goto release; } memset(&laddr_mapped, 0, sizeof(laddr_mapped)); laddr_mapped.s6_addr16[5] = 0xffff; /* ugly */ memcpy(&laddr_mapped.s6_addr[12], &IA_SIN(ia4)->sin_addr, sizeof(IA_SIN(ia4)->sin_addr)); ia4_release(ia4, &_psref); curlwp_bindx(bound); laddr = &laddr_mapped; } else { laddr = &in6p->in6p_laddr; /* XXX */ } } if (laddr == NULL) { if (error == 0) error = EADDRNOTAVAIL; goto release; } if (in6p->in6p_lport == 0) { /* * Craft a sockaddr_in6 for the local endpoint. Use the * "any" as a base, set the address, and recover the * scope. */ struct sockaddr_in6 lsin6 = *((const struct sockaddr_in6 *)in6p->in6p_socket->so_proto->pr_domain->dom_sa_any); lsin6.sin6_addr = *laddr; error = sa6_recoverscope(&lsin6); if (error) goto release; error = in6_pcbsetport(&lsin6, in6p, l); if (error) { in6p->in6p_laddr = in6addr_any; goto release; } } } else { if (IN6_IS_ADDR_UNSPECIFIED(&in6p->in6p_faddr)) { error = ENOTCONN; goto release; } if (IN6_IS_ADDR_V4MAPPED(&in6p->in6p_faddr)) { if ((in6p->in6p_flags & IN6P_IPV6_V6ONLY)) { /* * XXX: this case would happen when the * application sets the V6ONLY flag after * connecting the foreign address. * Such applications should be fixed, * so we bark here. */ log(LOG_INFO, "udp6_output: IPV6_V6ONLY " "option was set for a connected socket\n"); error = EINVAL; goto release; } else af = AF_INET; } laddr = &in6p->in6p_laddr; faddr = &in6p->in6p_faddr; fport = in6p->in6p_fport; } if (af == AF_INET) hlen = sizeof(struct ip); /* * Calculate data length and get a mbuf * for UDP and IP6 headers. */ M_PREPEND(m, hlen + sizeof(struct udphdr), M_DONTWAIT); if (m == NULL) { error = ENOBUFS; goto release; } /* * Stuff checksum and output datagram. */ udp6 = (struct udphdr *)(mtod(m, char *) + hlen); udp6->uh_sport = in6p->in6p_lport; /* lport is always set in the PCB */ udp6->uh_dport = fport; if (plen <= 0xffff) udp6->uh_ulen = htons((u_int16_t)plen); else udp6->uh_ulen = 0; udp6->uh_sum = 0; switch (af) { case AF_INET6: ip6 = mtod(m, struct ip6_hdr *); ip6->ip6_flow = in6p->in6p_flowinfo & IPV6_FLOWINFO_MASK; ip6->ip6_vfc &= ~IPV6_VERSION_MASK; ip6->ip6_vfc |= IPV6_VERSION; #if 0 /* ip6_plen will be filled in ip6_output. */ ip6->ip6_plen = htons((u_int16_t)plen); #endif ip6->ip6_nxt = IPPROTO_UDP; ip6->ip6_hlim = in6_selecthlim_rt(in6p); ip6->ip6_src = *laddr; ip6->ip6_dst = *faddr; udp6->uh_sum = in6_cksum_phdr(laddr, faddr, htonl(plen), htonl(IPPROTO_UDP)); m->m_pkthdr.csum_flags = M_CSUM_UDPv6; m->m_pkthdr.csum_data = offsetof(struct udphdr, uh_sum); UDP6_STATINC(UDP6_STAT_OPACKETS); error = ip6_output(m, optp, &in6p->in6p_route, 0, in6p->in6p_moptions, in6p, NULL); break; case AF_INET: #ifdef INET /* can't transmit jumbogram over IPv4 */ if (plen > 0xffff) { error = EMSGSIZE; goto release; } ip = mtod(m, struct ip *); ui = (struct udpiphdr *)ip; memset(ui->ui_x1, 0, sizeof(ui->ui_x1)); ui->ui_pr = IPPROTO_UDP; ui->ui_len = htons(plen); memcpy(&ui->ui_src, &laddr->s6_addr[12], sizeof(ui->ui_src)); ui->ui_ulen = ui->ui_len; flags = (in6p->in6p_socket->so_options & (SO_DONTROUTE | SO_BROADCAST)); memcpy(&ui->ui_dst, &faddr->s6_addr[12], sizeof(ui->ui_dst)); udp6->uh_sum = in_cksum(m, hlen + plen); if (udp6->uh_sum == 0) udp6->uh_sum = 0xffff; ip->ip_len = htons(hlen + plen); ip->ip_ttl = in6_selecthlim(in6p, NULL); /* XXX */ ip->ip_tos = 0; /* XXX */ UDP_STATINC(UDP_STAT_OPACKETS); error = ip_output(m, NULL, &in6p->in6p_route, flags /* XXX */, in6p->in6p_v4moptions, NULL); break; #else error = EAFNOSUPPORT; goto release; #endif } goto releaseopt; release: m_freem(m); releaseopt: if (control) { if (optp == &opt) ip6_clearpktopts(&opt, -1); m_freem(control); } return (error); } static int udp6_attach(struct socket *so, int proto) { struct in6pcb *in6p; int s, error; KASSERT(sotoin6pcb(so) == NULL); sosetlock(so); error = soreserve(so, udp6_sendspace, udp6_recvspace); if (error) { return error; } /* * MAPPED_ADDR implementation spec: * Always attach for IPv6, and only when necessary for IPv4. */ s = splsoftnet(); error = in6_pcballoc(so, &udbtable); splx(s); if (error) { return error; } in6p = sotoin6pcb(so); in6p->in6p_cksum = -1; /* just to be sure */ KASSERT(solocked(so)); return 0; } static void udp6_detach(struct socket *so) { struct in6pcb *in6p = sotoin6pcb(so); int s; KASSERT(solocked(so)); KASSERT(in6p != NULL); s = splsoftnet(); in6_pcbdetach(in6p); splx(s); } static int udp6_accept(struct socket *so, struct sockaddr *nam) { KASSERT(solocked(so)); return EOPNOTSUPP; } static int udp6_bind(struct socket *so, struct sockaddr *nam, struct lwp *l) { struct in6pcb *in6p = sotoin6pcb(so); struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)nam; int error = 0; int s; KASSERT(solocked(so)); KASSERT(in6p != NULL); s = splsoftnet(); error = in6_pcbbind(in6p, sin6, l); splx(s); return error; } static int udp6_listen(struct socket *so, struct lwp *l) { KASSERT(solocked(so)); return EOPNOTSUPP; } static int udp6_connect(struct socket *so, struct sockaddr *nam, struct lwp *l) { struct in6pcb *in6p = sotoin6pcb(so); int error = 0; int s; KASSERT(solocked(so)); KASSERT(in6p != NULL); if (!IN6_IS_ADDR_UNSPECIFIED(&in6p->in6p_faddr)) return EISCONN; s = splsoftnet(); error = in6_pcbconnect(in6p, (struct sockaddr_in6 *)nam, l); splx(s); if (error == 0) soisconnected(so); return error; } static int udp6_connect2(struct socket *so, struct socket *so2) { KASSERT(solocked(so)); return EOPNOTSUPP; } static int udp6_disconnect(struct socket *so) { struct in6pcb *in6p = sotoin6pcb(so); int s; KASSERT(solocked(so)); KASSERT(in6p != NULL); if (IN6_IS_ADDR_UNSPECIFIED(&in6p->in6p_faddr)) return ENOTCONN; s = splsoftnet(); in6_pcbdisconnect(in6p); memset((void *)&in6p->in6p_laddr, 0, sizeof(in6p->in6p_laddr)); splx(s); so->so_state &= ~SS_ISCONNECTED; /* XXX */ in6_pcbstate(in6p, IN6P_BOUND); /* XXX */ return 0; } static int udp6_shutdown(struct socket *so) { int s; s = splsoftnet(); socantsendmore(so); splx(s); return 0; } static int udp6_abort(struct socket *so) { int s; KASSERT(solocked(so)); KASSERT(sotoin6pcb(so) != NULL); s = splsoftnet(); soisdisconnected(so); in6_pcbdetach(sotoin6pcb(so)); splx(s); return 0; } static int udp6_ioctl(struct socket *so, u_long cmd, void *addr6, struct ifnet *ifp) { /* * MAPPED_ADDR implementation info: * Mapped addr support for PRU_CONTROL is not necessary. * Because typical user of PRU_CONTROL is such as ifconfig, * and they don't associate any addr to their socket. Then * socket family is only hint about the PRU_CONTROL'ed address * family, especially when getting addrs from kernel. * So AF_INET socket need to be used to control AF_INET addrs, * and AF_INET6 socket for AF_INET6 addrs. */ return in6_control(so, cmd, addr6, ifp); } static int udp6_stat(struct socket *so, struct stat *ub) { KASSERT(solocked(so)); /* stat: don't bother with a blocksize */ return 0; } static int udp6_peeraddr(struct socket *so, struct sockaddr *nam) { KASSERT(solocked(so)); KASSERT(sotoin6pcb(so) != NULL); KASSERT(nam != NULL); in6_setpeeraddr(sotoin6pcb(so), (struct sockaddr_in6 *)nam); return 0; } static int udp6_sockaddr(struct socket *so, struct sockaddr *nam) { KASSERT(solocked(so)); KASSERT(sotoin6pcb(so) != NULL); KASSERT(nam != NULL); in6_setsockaddr(sotoin6pcb(so), (struct sockaddr_in6 *)nam); return 0; } static int udp6_rcvd(struct socket *so, int flags, struct lwp *l) { KASSERT(solocked(so)); return EOPNOTSUPP; } static int udp6_recvoob(struct socket *so, struct mbuf *m, int flags) { KASSERT(solocked(so)); return EOPNOTSUPP; } static int udp6_send(struct socket *so, struct mbuf *m, struct sockaddr *nam, struct mbuf *control, struct lwp *l) { struct in6pcb *in6p = sotoin6pcb(so); int error = 0; int s; KASSERT(solocked(so)); KASSERT(in6p != NULL); KASSERT(m != NULL); s = splsoftnet(); error = udp6_output(in6p, m, (struct sockaddr_in6 *)nam, control, l); splx(s); return error; } static int udp6_sendoob(struct socket *so, struct mbuf *m, struct mbuf *control) { KASSERT(solocked(so)); m_freem(m); m_freem(control); return EOPNOTSUPP; } static int udp6_purgeif(struct socket *so, struct ifnet *ifp) { mutex_enter(softnet_lock); in6_pcbpurgeif0(&udbtable, ifp); #ifdef NET_MPSAFE mutex_exit(softnet_lock); #endif in6_purgeif(ifp); #ifdef NET_MPSAFE mutex_enter(softnet_lock); #endif in6_pcbpurgeif(&udbtable, ifp); mutex_exit(softnet_lock); return 0; } static int sysctl_net_inet6_udp6_stats(SYSCTLFN_ARGS) { return (NETSTAT_SYSCTL(udp6stat_percpu, UDP6_NSTATS)); } static void sysctl_net_inet6_udp6_setup(struct sysctllog **clog) { sysctl_createv(clog, 0, NULL, NULL, CTLFLAG_PERMANENT, CTLTYPE_NODE, "inet6", NULL, NULL, 0, NULL, 0, CTL_NET, PF_INET6, CTL_EOL); sysctl_createv(clog, 0, NULL, NULL, CTLFLAG_PERMANENT, CTLTYPE_NODE, "udp6", SYSCTL_DESCR("UDPv6 related settings"), NULL, 0, NULL, 0, CTL_NET, PF_INET6, IPPROTO_UDP, CTL_EOL); sysctl_createv(clog, 0, NULL, NULL, CTLFLAG_PERMANENT|CTLFLAG_READWRITE, CTLTYPE_INT, "sendspace", SYSCTL_DESCR("Default UDP send buffer size"), NULL, 0, &udp6_sendspace, 0, CTL_NET, PF_INET6, IPPROTO_UDP, UDP6CTL_SENDSPACE, CTL_EOL); sysctl_createv(clog, 0, NULL, NULL, CTLFLAG_PERMANENT|CTLFLAG_READWRITE, CTLTYPE_INT, "recvspace", SYSCTL_DESCR("Default UDP receive buffer size"), NULL, 0, &udp6_recvspace, 0, CTL_NET, PF_INET6, IPPROTO_UDP, UDP6CTL_RECVSPACE, CTL_EOL); sysctl_createv(clog, 0, NULL, NULL, CTLFLAG_PERMANENT|CTLFLAG_READWRITE, CTLTYPE_INT, "do_loopback_cksum", SYSCTL_DESCR("Perform UDP checksum on loopback"), NULL, 0, &udp_do_loopback_cksum, 0, CTL_NET, PF_INET6, IPPROTO_UDP, UDP6CTL_LOOPBACKCKSUM, CTL_EOL); sysctl_createv(clog, 0, NULL, NULL, CTLFLAG_PERMANENT, CTLTYPE_STRUCT, "pcblist", SYSCTL_DESCR("UDP protocol control block list"), sysctl_inpcblist, 0, &udbtable, 0, CTL_NET, PF_INET6, IPPROTO_UDP, CTL_CREATE, CTL_EOL); sysctl_createv(clog, 0, NULL, NULL, CTLFLAG_PERMANENT, CTLTYPE_STRUCT, "stats", SYSCTL_DESCR("UDPv6 statistics"), sysctl_net_inet6_udp6_stats, 0, NULL, 0, CTL_NET, PF_INET6, IPPROTO_UDP, UDP6CTL_STATS, CTL_EOL); } void udp6_statinc(u_int stat) { KASSERT(stat < UDP6_NSTATS); UDP6_STATINC(stat); } #ifdef IPSEC /* * Returns: * 1 if the packet was processed * 0 if normal UDP processing should take place * -1 if an error occurred and m was freed */ static int udp6_espinudp(struct mbuf **mp, int off) { const size_t skip = sizeof(struct udphdr); size_t len; void *data; size_t minlen; int ip6hdrlen; struct ip6_hdr *ip6; struct m_tag *tag; struct udphdr *udphdr; u_int16_t sport, dport; struct mbuf *m = *mp; uint32_t *marker; /* * Collapse the mbuf chain if the first mbuf is too short * The longest case is: UDP + non ESP marker + ESP */ minlen = off + sizeof(u_int64_t) + sizeof(struct esp); if (minlen > m->m_pkthdr.len) minlen = m->m_pkthdr.len; if (m->m_len < minlen) { if ((*mp = m_pullup(m, minlen)) == NULL) { return -1; } m = *mp; } len = m->m_len - off; data = mtod(m, char *) + off; /* Ignore keepalive packets */ if ((len == 1) && (*(unsigned char *)data == 0xff)) { m_freem(m); *mp = NULL; /* avoid any further processing by caller ... */ return 1; } /* Handle Non-ESP marker (32bit). If zero, then IKE. */ marker = (uint32_t *)data; if (len <= sizeof(uint32_t)) return 0; if (marker[0] == 0) return 0; /* * Get the UDP ports. They are handled in network * order everywhere in IPSEC_NAT_T code. */ udphdr = (struct udphdr *)((char *)data - skip); sport = udphdr->uh_sport; dport = udphdr->uh_dport; /* * Remove the UDP header (and possibly the non ESP marker) * IPv6 header length is ip6hdrlen * Before: * <---- off ---> * +-----+------+-----+ * | IP6 | UDP | ESP | * +-----+------+-----+ * <-skip-> * After: * +-----+-----+ * | IP6 | ESP | * +-----+-----+ * <-skip-> */ ip6hdrlen = off - sizeof(struct udphdr); memmove(mtod(m, char *) + skip, mtod(m, void *), ip6hdrlen); m_adj(m, skip); ip6 = mtod(m, struct ip6_hdr *); ip6->ip6_plen = htons(ntohs(ip6->ip6_plen) - skip); ip6->ip6_nxt = IPPROTO_ESP; /* * We have modified the packet - it is now ESP, so we should not * return to UDP processing ... * * Add a PACKET_TAG_IPSEC_NAT_T_PORT tag to remember * the source UDP port. This is required if we want * to select the right SPD for multiple hosts behind * same NAT */ if ((tag = m_tag_get(PACKET_TAG_IPSEC_NAT_T_PORTS, sizeof(sport) + sizeof(dport), M_DONTWAIT)) == NULL) { m_freem(m); return -1; } ((u_int16_t *)(tag + 1))[0] = sport; ((u_int16_t *)(tag + 1))[1] = dport; m_tag_prepend(m, tag); if (ipsec_used) ipsec6_common_input(&m, &ip6hdrlen, IPPROTO_ESP); else m_freem(m); /* We handled it, it shouldn't be handled by UDP */ *mp = NULL; /* avoid free by caller ... */ return 1; } #endif /* IPSEC */ PR_WRAP_USRREQS(udp6) #define udp6_attach udp6_attach_wrapper #define udp6_detach udp6_detach_wrapper #define udp6_accept udp6_accept_wrapper #define udp6_bind udp6_bind_wrapper #define udp6_listen udp6_listen_wrapper #define udp6_connect udp6_connect_wrapper #define udp6_connect2 udp6_connect2_wrapper #define udp6_disconnect udp6_disconnect_wrapper #define udp6_shutdown udp6_shutdown_wrapper #define udp6_abort udp6_abort_wrapper #define udp6_ioctl udp6_ioctl_wrapper #define udp6_stat udp6_stat_wrapper #define udp6_peeraddr udp6_peeraddr_wrapper #define udp6_sockaddr udp6_sockaddr_wrapper #define udp6_rcvd udp6_rcvd_wrapper #define udp6_recvoob udp6_recvoob_wrapper #define udp6_send udp6_send_wrapper #define udp6_sendoob udp6_sendoob_wrapper #define udp6_purgeif udp6_purgeif_wrapper const struct pr_usrreqs udp6_usrreqs = { .pr_attach = udp6_attach, .pr_detach = udp6_detach, .pr_accept = udp6_accept, .pr_bind = udp6_bind, .pr_listen = udp6_listen, .pr_connect = udp6_connect, .pr_connect2 = udp6_connect2, .pr_disconnect = udp6_disconnect, .pr_shutdown = udp6_shutdown, .pr_abort = udp6_abort, .pr_ioctl = udp6_ioctl, .pr_stat = udp6_stat, .pr_peeraddr = udp6_peeraddr, .pr_sockaddr = udp6_sockaddr, .pr_rcvd = udp6_rcvd, .pr_recvoob = udp6_recvoob, .pr_send = udp6_send, .pr_sendoob = udp6_sendoob, .pr_purgeif = udp6_purgeif, }; |
2 2 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 | /* $NetBSD: umodem.c,v 1.74 2020/04/12 01:10:54 simonb Exp $ */ /* * Copyright (c) 1998 The NetBSD Foundation, Inc. * All rights reserved. * * This code is derived from software contributed to The NetBSD Foundation * by Lennart Augustsson (lennart@augustsson.net) at * Carlstedt Research & Technology. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ /* * Comm Class spec: http://www.usb.org/developers/devclass_docs/usbccs10.pdf * http://www.usb.org/developers/devclass_docs/usbcdc11.pdf */ /* * TODO: * - Add error recovery in various places; the big problem is what * to do in a callback if there is an error. * - Implement a Call Device for modems without multiplexed commands. * */ #include <sys/cdefs.h> __KERNEL_RCSID(0, "$NetBSD: umodem.c,v 1.74 2020/04/12 01:10:54 simonb Exp $"); #include <sys/param.h> #include <sys/systm.h> #include <sys/kernel.h> #include <sys/ioctl.h> #include <sys/conf.h> #include <sys/tty.h> #include <sys/file.h> #include <sys/select.h> #include <sys/proc.h> #include <sys/vnode.h> #include <sys/device.h> #include <sys/poll.h> #include <dev/usb/usb.h> #include <dev/usb/usbcdc.h> #include <dev/usb/usbdi.h> #include <dev/usb/usbdi_util.h> #include <dev/usb/usbdevs.h> #include <dev/usb/usb_quirks.h> #include <dev/usb/ucomvar.h> #include <dev/usb/umodemvar.h> Static const struct ucom_methods umodem_methods = { .ucom_get_status = umodem_get_status, .ucom_set = umodem_set, .ucom_param = umodem_param, .ucom_ioctl = umodem_ioctl, .ucom_open = umodem_open, .ucom_close = umodem_close, }; static int umodem_match(device_t, cfdata_t, void *); static void umodem_attach(device_t, device_t, void *); static int umodem_detach(device_t, int); CFATTACH_DECL_NEW(umodem, sizeof(struct umodem_softc), umodem_match, umodem_attach, umodem_detach, NULL); static int umodem_match(device_t parent, cfdata_t match, void *aux) { struct usbif_attach_arg *uiaa = aux; usb_interface_descriptor_t *id; int cm, acm; if (uiaa->uiaa_class != UICLASS_CDC || uiaa->uiaa_subclass != UISUBCLASS_ABSTRACT_CONTROL_MODEL || !(uiaa->uiaa_proto == UIPROTO_CDC_NOCLASS || uiaa->uiaa_proto == UIPROTO_CDC_AT)) return UMATCH_NONE; id = usbd_get_interface_descriptor(uiaa->uiaa_iface); if (umodem_get_caps(uiaa->uiaa_device, &cm, &acm, id) == -1) return UMATCH_NONE; return UMATCH_IFACECLASS_IFACESUBCLASS_IFACEPROTO; } static void umodem_attach(device_t parent, device_t self, void *aux) { struct umodem_softc *sc = device_private(self); struct usbif_attach_arg *uiaa = aux; struct ucom_attach_args ucaa; memset(&ucaa, 0, sizeof(ucaa)); ucaa.ucaa_portno = UCOM_UNK_PORTNO; ucaa.ucaa_methods = &umodem_methods; ucaa.ucaa_info = NULL; if (!pmf_device_register(self, NULL, NULL)) aprint_error_dev(self, "couldn't establish power handler"); if (umodem_common_attach(self, sc, uiaa, &ucaa)) return; return; } static int umodem_detach(device_t self, int flags) { struct umodem_softc *sc = device_private(self); pmf_device_deregister(self); return umodem_common_detach(sc, flags); } |
95 97 2 26 95 92 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 | /* $NetBSD: route.h,v 1.129 2021/08/09 20:49:10 andvar Exp $ */ /* * Copyright (c) 1980, 1986, 1993 * The Regents of the University of California. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * @(#)route.h 8.5 (Berkeley) 2/8/95 */ #ifndef _NET_ROUTE_H_ #define _NET_ROUTE_H_ #include <sys/queue.h> #include <sys/socket.h> #include <sys/types.h> #include <net/if.h> #ifdef _KERNEL #include <sys/rwlock.h> #include <sys/condvar.h> #include <sys/pserialize.h> #include <sys/percpu.h> #endif #include <sys/psref.h> #if !(defined(_KERNEL) || defined(_STANDALONE)) #include <stdbool.h> #endif /* * Kernel resident routing tables. * * The routing tables are initialized when interface addresses * are set by making entries for all directly connected interfaces. */ /* * A route consists of a destination address and a reference * to a routing entry. These are often held by protocols * in their control blocks, e.g. inpcb. */ struct route { struct rtentry *_ro_rt; struct sockaddr *ro_sa; uint64_t ro_rtcache_generation; struct psref ro_psref; int ro_bound; }; /* * These numbers are used by reliable protocols for determining * retransmission behavior and are included in the routing structure. */ struct rt_metrics { uint64_t rmx_locks; /* Kernel must leave these values alone */ uint64_t rmx_mtu; /* MTU for this path */ uint64_t rmx_hopcount; /* max hops expected */ uint64_t rmx_recvpipe; /* inbound delay-bandwidth product */ uint64_t rmx_sendpipe; /* outbound delay-bandwidth product */ uint64_t rmx_ssthresh; /* outbound gateway buffer limit */ uint64_t rmx_rtt; /* estimated round trip time */ uint64_t rmx_rttvar; /* estimated rtt variance */ time_t rmx_expire; /* lifetime for route, e.g. redirect */ time_t rmx_pksent; /* packets sent using this route */ }; /* * rmx_rtt and rmx_rttvar are stored as microseconds; * RTTTOPRHZ(rtt) converts to a value suitable for use * by a protocol slowtimo counter. */ #define RTM_RTTUNIT 1000000 /* units for rtt, rttvar, as units per sec */ #define RTTTOPRHZ(r) ((r) / (RTM_RTTUNIT / PR_SLOWHZ)) /* * We distinguish between routes to hosts and routes to networks, * preferring the former if available. For each route we infer * the interface to use from the gateway address supplied when * the route was entered. Routes that forward packets through * gateways are marked so that the output routines know to address the * gateway rather than the ultimate destination. */ #ifndef RNF_NORMAL #include <net/radix.h> #endif struct rtentry { struct radix_node rt_nodes[2]; /* tree glue, and other values */ #define rt_mask(r) ((const struct sockaddr *)((r)->rt_nodes->rn_mask)) struct sockaddr *rt_gateway; /* value */ int rt_flags; /* up/down?, host/net */ int rt_refcnt; /* # held references */ uint64_t rt_use; /* raw # packets forwarded */ struct ifnet *rt_ifp; /* the answer: interface to use */ struct ifaddr *rt_ifa; /* the answer: interface to use */ uint32_t rt_ifa_seqno; void * rt_llinfo; /* pointer to link level info cache */ struct rt_metrics rt_rmx; /* metrics used by rx'ing protocols */ struct rtentry *rt_gwroute; /* implied entry for gatewayed routes */ LIST_HEAD(, rttimer) rt_timer; /* queue of timeouts for misc funcs */ struct rtentry *rt_parent; /* parent of cloned route */ struct sockaddr *_rt_key; struct sockaddr *rt_tag; /* route tagging info */ #ifdef _KERNEL kcondvar_t rt_cv; struct psref_target rt_psref; SLIST_ENTRY(rtentry) rt_free; /* queue of deferred frees */ #endif }; static __inline const struct sockaddr * rt_getkey(const struct rtentry *rt) { return rt->_rt_key; } /* * Following structure necessary for 4.3 compatibility; * We should eventually move it to a compat file. */ struct ortentry { uint32_t rt_hash; /* to speed lookups */ struct sockaddr rt_dst; /* key */ struct sockaddr rt_gateway; /* value */ int16_t rt_flags; /* up/down?, host/net */ int16_t rt_refcnt; /* # held references */ uint32_t rt_use; /* raw # packets forwarded */ struct ifnet *rt_ifp; /* the answer: interface to use */ }; #define RTF_UP 0x1 /* route usable */ #define RTF_GATEWAY 0x2 /* destination is a gateway */ #define RTF_HOST 0x4 /* host entry (net otherwise) */ #define RTF_REJECT 0x8 /* host or net unreachable */ #define RTF_DYNAMIC 0x10 /* created dynamically (by redirect) */ #define RTF_MODIFIED 0x20 /* modified dynamically (by redirect) */ #define RTF_DONE 0x40 /* message confirmed */ #define RTF_MASK 0x80 /* subnet mask present */ // #define RTF_CLONING 0x100 /* generate new routes on use */ #define RTF_CONNECTED 0x100 /* hosts on this route are neighbours */ // #define RTF_XRESOLVE 0x200 /* external daemon resolves name */ // #define RTF_LLINFO 0x400 /* generated by ARP or NDP */ #define RTF_LLDATA 0x400 /* used by apps to add/del L2 entries */ #define RTF_STATIC 0x800 /* manually added */ #define RTF_BLACKHOLE 0x1000 /* just discard pkts (during updates) */ // #define RTF_CLONED 0x2000 /* this is a cloned route */ #define RTF_PROTO2 0x4000 /* protocol specific routing flag */ #define RTF_PROTO1 0x8000 /* protocol specific routing flag */ #define RTF_SRC 0x10000 /* route has fixed source address */ #define RTF_ANNOUNCE 0x20000 /* announce new ARP or NDP entry */ #define RTF_LOCAL 0x40000 /* route represents a local address */ #define RTF_BROADCAST 0x80000 /* route represents a bcast address */ #define RTF_UPDATING 0x100000 /* route is updating */ /* * The flag is nevert set to rt_flags. It just tells rtrequest1 to set a passed * ifa to rt_ifa (via rti_ifa) and not replace rt_ifa in ifa_rtrequest. */ #define RTF_DONTCHANGEIFA 0x200000 /* suppress rt_ifa replacement */ /* * 0x400 is exposed to userland just for backward compatibility. For that * purpose, it should be shown as LLINFO. */ #define RTFBITS "\020\1UP\2GATEWAY\3HOST\4REJECT\5DYNAMIC\6MODIFIED\7DONE" \ "\010MASK_PRESENT\011CONNECTED\012XRESOLVE\013LLINFO\014STATIC" \ "\015BLACKHOLE\016CLONED\017PROTO2\020PROTO1\021SRC\022ANNOUNCE" \ "\023LOCAL\024BROADCAST\025UPDATING" /* * Routing statistics. */ struct rtstat { uint64_t rts_badredirect; /* bogus redirect calls */ uint64_t rts_dynamic; /* routes created by redirects */ uint64_t rts_newgateway; /* routes modified by redirects */ uint64_t rts_unreach; /* lookups which failed */ uint64_t rts_wildcard; /* lookups satisfied by a wildcard */ }; /* * Structures for routing messages. By forcing the first member to be aligned * at a 64-bit boundary, we also force the size to be a multiple of 64-bits. */ #if !defined(_KERNEL) || !defined(COMPAT_RTSOCK) /* * If we aren't being compiled for backwards compatibility, enforce 64-bit * alignment so any routing message is the same regardless if the kernel * is an ILP32 or LP64 kernel. */ #define __align64 __aligned(sizeof(uint64_t)) #else #define __align64 #endif struct rt_msghdr { u_short rtm_msglen __align64; /* to skip over non-understood messages */ u_char rtm_version; /* future binary compatibility */ u_char rtm_type; /* message type */ u_short rtm_index; /* index for associated ifp */ int rtm_flags; /* flags, incl. kern & message, e.g. DONE */ int rtm_addrs; /* bitmask identifying sockaddrs in msg */ pid_t rtm_pid; /* identify sender */ int rtm_seq; /* for sender to identify action */ int rtm_errno; /* why failed */ int rtm_use; /* from rtentry */ int rtm_inits; /* which metrics we are initializing */ struct rt_metrics rtm_rmx __align64; /* metrics themselves */ }; #undef __align64 #define RTM_VERSION 4 /* Up the ante and ignore older versions */ #define RTM_ADD 0x1 /* Add Route */ #define RTM_DELETE 0x2 /* Delete Route */ #define RTM_CHANGE 0x3 /* Change Metrics or flags */ #define RTM_GET 0x4 /* Report Metrics */ #define RTM_LOSING 0x5 /* Kernel Suspects Partitioning */ #define RTM_REDIRECT 0x6 /* Told to use different route */ #define RTM_MISS 0x7 /* Lookup failed on this address */ #define RTM_LOCK 0x8 /* fix specified metrics */ #define RTM_OLDADD 0x9 /* caused by SIOCADDRT */ #define RTM_OLDDEL 0xa /* caused by SIOCDELRT */ // #define RTM_RESOLVE 0xb /* req to resolve dst to LL addr */ #define RTM_ONEWADDR 0xc /* Old (pre-8.0) RTM_NEWADDR message */ #define RTM_ODELADDR 0xd /* Old (pre-8.0) RTM_DELADDR message */ #define RTM_OOIFINFO 0xe /* Old (pre-1.5) RTM_IFINFO message */ #define RTM_OIFINFO 0xf /* Old (pre-64bit time) RTM_IFINFO message */ #define RTM_IFANNOUNCE 0x10 /* iface arrival/departure */ #define RTM_IEEE80211 0x11 /* IEEE80211 wireless event */ #define RTM_SETGATE 0x12 /* set prototype gateway for clones * (see example in arp_rtrequest). */ #define RTM_LLINFO_UPD 0x13 /* indication to ARP/NDP/etc. that link-layer * address has changed */ #define RTM_IFINFO 0x14 /* iface/link going up/down etc. */ #define RTM_OCHGADDR 0x15 /* Old (pre-8.0) RTM_CHGADDR message */ #define RTM_NEWADDR 0x16 /* address being added to iface */ #define RTM_DELADDR 0x17 /* address being removed from iface */ #define RTM_CHGADDR 0x18 /* address properties changed */ #ifdef RTM_NAMES static const char *rtm_names[] = { "*none*", "add", "delete", "change", "get", "losing", "redirect", "miss", "lock", "oldadd", "olddel", "*resolve*", "onewaddr", "odeladdr", "ooifinfo", "oifinfo", "ifannounce", "ieee80211", "setgate", "llinfo_upd", "ifinfo", "ochgaddr", "newaddr", "deladdr", "chgaddr", }; #endif /* * setsockopt defines used for the filtering. */ #define RO_MSGFILTER 1 /* array of which rtm_type to send to client */ #define RO_MISSFILTER 2 /* array of sockaddrs to match miss dst */ #define RO_FILTSA_MAX 30 /* maximum number of sockaddrs per filter */ #define RTV_MTU 0x1 /* init or lock _mtu */ #define RTV_HOPCOUNT 0x2 /* init or lock _hopcount */ #define RTV_EXPIRE 0x4 /* init or lock _expire */ #define RTV_RPIPE 0x8 /* init or lock _recvpipe */ #define RTV_SPIPE 0x10 /* init or lock _sendpipe */ #define RTV_SSTHRESH 0x20 /* init or lock _ssthresh */ #define RTV_RTT 0x40 /* init or lock _rtt */ #define RTV_RTTVAR 0x80 /* init or lock _rttvar */ #define RTVBITS "\020\1MTU\2HOPCOUNT\3EXPIRE\4RECVPIPE\5SENDPIPE" \ "\6SSTHRESH\7RTT\010RTTVAR" /* * Bitmask values for rtm_addr. */ #define RTA_DST 0x1 /* destination sockaddr present */ #define RTA_GATEWAY 0x2 /* gateway sockaddr present */ #define RTA_NETMASK 0x4 /* netmask sockaddr present */ #define RTA_GENMASK 0x8 /* cloning mask sockaddr present */ #define RTA_IFP 0x10 /* interface name sockaddr present */ #define RTA_IFA 0x20 /* interface addr sockaddr present */ #define RTA_AUTHOR 0x40 /* sockaddr for author of redirect */ #define RTA_BRD 0x80 /* for NEWADDR, broadcast or p-p dest addr */ #define RTA_TAG 0x100 /* route tag */ #define RTABITS "\020\1DST\2GATEWAY\3NETMASK\4GENMASK\5IFP\6IFA\7AUTHOR" \ "\010BRD\011TAG" /* * Index offsets for sockaddr array for alternate internal encoding. */ #define RTAX_DST 0 /* destination sockaddr present */ #define RTAX_GATEWAY 1 /* gateway sockaddr present */ #define RTAX_NETMASK 2 /* netmask sockaddr present */ #define RTAX_GENMASK 3 /* cloning mask sockaddr present */ #define RTAX_IFP 4 /* interface name sockaddr present */ #define RTAX_IFA 5 /* interface addr sockaddr present */ #define RTAX_AUTHOR 6 /* sockaddr for author of redirect */ #define RTAX_BRD 7 /* for NEWADDR, broadcast or p-p dest addr */ #define RTAX_TAG 8 /* route tag */ #define RTAX_MAX 9 /* size of array to allocate */ #define RT_ROUNDUP2(a, n) ((a) > 0 ? (1 + (((a) - 1U) | ((n) - 1))) : (n)) #define RT_ROUNDUP(a) RT_ROUNDUP2((a), sizeof(uint64_t)) #define RT_ADVANCE(x, n) (x += RT_ROUNDUP((n)->sa_len)) struct rt_addrinfo { int rti_addrs; const struct sockaddr *rti_info[RTAX_MAX]; int rti_flags; struct ifaddr *rti_ifa; struct ifnet *rti_ifp; }; struct route_cb { int ip_count; int ip6_count; int unused1; int mpls_count; int any_count; }; /* * This structure, and the prototypes for the rt_timer_{init,remove_all, * add,timer} functions all used with the kind permission of BSDI. * These allow functions to be called for routes at specific times. */ struct rttimer { TAILQ_ENTRY(rttimer) rtt_next; /* entry on timer queue */ LIST_ENTRY(rttimer) rtt_link; /* multiple timers per rtentry */ struct rttimer_queue *rtt_queue; /* back pointer to queue */ struct rtentry *rtt_rt; /* Back pointer to the route */ void (*rtt_func)(struct rtentry *, struct rttimer *); time_t rtt_time; /* When this timer was registered */ }; struct rttimer_queue { long rtq_timeout; unsigned long rtq_count; TAILQ_HEAD(, rttimer) rtq_head; LIST_ENTRY(rttimer_queue) rtq_link; }; struct rtbl; typedef struct rtbl rtbl_t; #ifdef _KERNEL struct rtbl { struct radix_node_head t_rnh; }; struct rt_walkarg { int w_op; int w_arg; int w_given; int w_needed; void * w_where; int w_tmemsize; int w_tmemneeded; void * w_tmem; }; #if 0 #define RT_DPRINTF(__fmt, ...) do { } while (/*CONSTCOND*/0) #else #define RT_DPRINTF(__fmt, ...) /* do nothing */ #endif struct rtwalk { int (*rw_f)(struct rtentry *, void *); void *rw_v; }; /* * Global data specific to the routing socket. */ struct route_info { struct sockaddr ri_dst; struct sockaddr ri_src; struct route_cb ri_cb; int ri_maxqlen; struct ifqueue ri_intrq; void *ri_sih; }; extern struct route_info route_info; extern struct rtstat rtstat; struct socket; void rt_init(void); int rt_timer_add(struct rtentry *, void(*)(struct rtentry *, struct rttimer *), struct rttimer_queue *); unsigned long rt_timer_count(struct rttimer_queue *); void rt_timer_queue_change(struct rttimer_queue *, long); struct rttimer_queue * rt_timer_queue_create(u_int); void rt_timer_queue_destroy(struct rttimer_queue *); void rt_free(struct rtentry *); void rt_unref(struct rtentry *); int rt_update(struct rtentry *, struct rt_addrinfo *, void *); int rt_update_prepare(struct rtentry *); void rt_update_finish(struct rtentry *); void rt_newmsg(const int, const struct rtentry *); struct rtentry * rtalloc1(const struct sockaddr *, int); int rtinit(struct ifaddr *, int, int); void rtredirect(const struct sockaddr *, const struct sockaddr *, const struct sockaddr *, int, const struct sockaddr *, struct rtentry **); int rtrequest(int, const struct sockaddr *, const struct sockaddr *, const struct sockaddr *, int, struct rtentry **); int rtrequest1(int, struct rt_addrinfo *, struct rtentry **); int rtrequest_newmsg(const int, const struct sockaddr *, const struct sockaddr *, const struct sockaddr *, const int); int rt_ifa_addlocal(struct ifaddr *); int rt_ifa_remlocal(struct ifaddr *, struct ifaddr *); struct ifaddr * rt_get_ifa(struct rtentry *); void rt_replace_ifa(struct rtentry *, struct ifaddr *); int rt_setgate(struct rtentry *, const struct sockaddr *); const struct sockaddr * rt_settag(struct rtentry *, const struct sockaddr *); struct sockaddr * rt_gettag(const struct rtentry *); int rt_check_reject_route(const struct rtentry *, const struct ifnet *); void rt_delete_matched_entries(sa_family_t, int (*)(struct rtentry *, void *), void *); int rt_walktree(sa_family_t, int (*)(struct rtentry *, void *), void *); static __inline void rt_assert_referenced(const struct rtentry *rt) { KASSERT(rt->rt_refcnt > 0); } void rtcache_copy(struct route *, struct route *); void rtcache_free(struct route *); struct rtentry * rtcache_init(struct route *); struct rtentry * rtcache_init_noclone(struct route *); struct rtentry * rtcache_lookup2(struct route *, const struct sockaddr *, int, int *); int rtcache_setdst(struct route *, const struct sockaddr *); struct rtentry * rtcache_update(struct route *, int); static __inline void rtcache_invariants(const struct route *ro) { KASSERT(ro->ro_sa != NULL || ro->_ro_rt == NULL); } static __inline struct rtentry * rtcache_lookup1(struct route *ro, const struct sockaddr *dst, int clone) { int hit; return rtcache_lookup2(ro, dst, clone, &hit); } static __inline struct rtentry * rtcache_lookup(struct route *ro, const struct sockaddr *dst) { return rtcache_lookup1(ro, dst, 1); } static __inline const struct sockaddr * rtcache_getdst(const struct route *ro) { rtcache_invariants(ro); return ro->ro_sa; } struct rtentry * rtcache_validate(struct route *); void rtcache_unref(struct rtentry *, struct route *); percpu_t * rtcache_percpu_alloc(void); static inline struct route * rtcache_percpu_getref(percpu_t *pc) { return *(struct route **)percpu_getref(pc); } static inline void rtcache_percpu_putref(percpu_t *pc) { percpu_putref(pc); } /* rtsock */ void rt_ieee80211msg(struct ifnet *, int, void *, size_t); void rt_ifannouncemsg(struct ifnet *, int); void rt_ifmsg(struct ifnet *); void rt_missmsg(int, const struct rt_addrinfo *, int, int); struct mbuf * rt_msg1(int, struct rt_addrinfo *, void *, int); int rt_msg3(int, struct rt_addrinfo *, void *, struct rt_walkarg *, int *); void rt_addrmsg(int, struct ifaddr *); void rt_addrmsg_src(int, struct ifaddr *, const struct sockaddr *); void rt_addrmsg_rt(int, struct ifaddr *, int, struct rtentry *); void route_enqueue(struct mbuf *, int); struct llentry; void rt_clonedmsg(int, const struct sockaddr *, const struct sockaddr *, const uint8_t *, const struct ifnet *); void rt_setmetrics(void *, struct rtentry *); /* rtbl */ int rt_addaddr(rtbl_t *, struct rtentry *, const struct sockaddr *); void rt_assert_inactive(const struct rtentry *); struct rtentry * rt_deladdr(rtbl_t *, const struct sockaddr *, const struct sockaddr *); rtbl_t *rt_gettable(sa_family_t); int rt_inithead(rtbl_t **, int); struct rtentry * rt_lookup(rtbl_t *, const struct sockaddr *, const struct sockaddr *); struct rtentry * rt_matchaddr(rtbl_t *, const struct sockaddr *); int rt_refines(const struct sockaddr *, const struct sockaddr *); int rtbl_walktree(sa_family_t, int (*)(struct rtentry *, void *), void *); struct rtentry * rtbl_search_matched_entry(sa_family_t, int (*)(struct rtentry *, void *), void *); void rtbl_init(void); void sysctl_net_route_setup(struct sysctllog **, int, const char *); #endif /* _KERNEL */ #endif /* !_NET_ROUTE_H_ */ |
4314 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 | /* $NetBSD: userret.h,v 1.13 2018/07/26 09:29:08 maxv Exp $ */ /* * XXXfvdl same as i386 counterpart, but should probably be independent. */ /*- * Copyright (c) 1998, 2000 The NetBSD Foundation, Inc. * All rights reserved. * * This code is derived from software contributed to The NetBSD Foundation * by Charles M. Hannum. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ /*- * Copyright (c) 1990 The Regents of the University of California. * All rights reserved. * * This code is derived from software contributed to Berkeley by * William Jolitz. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * */ #include <sys/userret.h> static __inline void userret(struct lwp *); /* * Define the code needed before returning to user mode, for * trap and syscall. */ static __inline void userret(struct lwp *l) { /* Invoke MI userret code */ mi_userret(l); } |
2 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 | /* $NetBSD: rf_dagfuncs.c,v 1.35 2021/08/07 16:19:15 thorpej Exp $ */ /* * Copyright (c) 1995 Carnegie-Mellon University. * All rights reserved. * * Author: Mark Holland, William V. Courtright II * * Permission to use, copy, modify and distribute this software and * its documentation is hereby granted, provided that both the copyright * notice and this permission notice appear in all copies of the * software, derivative works or modified versions, and any portions * thereof, and that both notices appear in supporting documentation. * * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS" * CONDITION. CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND * FOR ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE. * * Carnegie Mellon requests users of this software to return to * * Software Distribution Coordinator or Software.Distribution@CS.CMU.EDU * School of Computer Science * Carnegie Mellon University * Pittsburgh PA 15213-3890 * * any improvements or extensions that they make and grant Carnegie the * rights to redistribute these changes. */ /* * dagfuncs.c -- DAG node execution routines * * Rules: * 1. Every DAG execution function must eventually cause node->status to * get set to "good" or "bad", and "FinishNode" to be called. In the * case of nodes that complete immediately (xor, NullNodeFunc, etc), * the node execution function can do these two things directly. In * the case of nodes that have to wait for some event (a disk read to * complete, a lock to be released, etc) to occur before they can * complete, this is typically achieved by having whatever module * is doing the operation call GenericWakeupFunc upon completion. * 2. DAG execution functions should check the status in the DAG header * and NOP out their operations if the status is not "enable". However, * execution functions that release resources must be sure to release * them even when they NOP out the function that would use them. * Functions that acquire resources should go ahead and acquire them * even when they NOP, so that a downstream release node will not have * to check to find out whether or not the acquire was suppressed. */ #include <sys/cdefs.h> __KERNEL_RCSID(0, "$NetBSD: rf_dagfuncs.c,v 1.35 2021/08/07 16:19:15 thorpej Exp $"); #include <sys/param.h> #include <sys/ioctl.h> #include "rf_archs.h" #include "rf_raid.h" #include "rf_dag.h" #include "rf_layout.h" #include "rf_etimer.h" #include "rf_acctrace.h" #include "rf_diskqueue.h" #include "rf_dagfuncs.h" #include "rf_general.h" #include "rf_engine.h" #include "rf_dagutils.h" #include "rf_kintf.h" #if RF_INCLUDE_PARITYLOGGING > 0 #include "rf_paritylog.h" #endif /* RF_INCLUDE_PARITYLOGGING > 0 */ void (*rf_DiskReadFunc) (RF_DagNode_t *); void (*rf_DiskWriteFunc) (RF_DagNode_t *); void (*rf_DiskReadUndoFunc) (RF_DagNode_t *); void (*rf_DiskWriteUndoFunc) (RF_DagNode_t *); void (*rf_RegularXorUndoFunc) (RF_DagNode_t *); void (*rf_SimpleXorUndoFunc) (RF_DagNode_t *); void (*rf_RecoveryXorUndoFunc) (RF_DagNode_t *); /***************************************************************************** * main (only) configuration routine for this module ****************************************************************************/ int rf_ConfigureDAGFuncs(RF_ShutdownList_t **listp) { RF_ASSERT(((sizeof(long) == 8) && RF_LONGSHIFT == 3) || ((sizeof(long) == 4) && RF_LONGSHIFT == 2)); rf_DiskReadFunc = rf_DiskReadFuncForThreads; rf_DiskReadUndoFunc = rf_DiskUndoFunc; rf_DiskWriteFunc = rf_DiskWriteFuncForThreads; rf_DiskWriteUndoFunc = rf_DiskUndoFunc; rf_RegularXorUndoFunc = rf_NullNodeUndoFunc; rf_SimpleXorUndoFunc = rf_NullNodeUndoFunc; rf_RecoveryXorUndoFunc = rf_NullNodeUndoFunc; return (0); } /***************************************************************************** * the execution function associated with a terminate node ****************************************************************************/ void rf_TerminateFunc(RF_DagNode_t *node) { RF_ASSERT(node->dagHdr->numCommits == node->dagHdr->numCommitNodes); node->status = rf_good; rf_FinishNode(node, RF_THREAD_CONTEXT); } void rf_TerminateUndoFunc(RF_DagNode_t *node) { } /***************************************************************************** * execution functions associated with a mirror node * * parameters: * * 0 - physical disk address of data * 1 - buffer for holding read data * 2 - parity stripe ID * 3 - flags * 4 - physical disk address of mirror (parity) * ****************************************************************************/ void rf_DiskReadMirrorIdleFunc(RF_DagNode_t *node) { /* select the mirror copy with the shortest queue and fill in node * parameters with physical disk address */ rf_SelectMirrorDiskIdle(node); rf_DiskReadFunc(node); } #if (RF_INCLUDE_CHAINDECLUSTER > 0) || (RF_INCLUDE_INTERDECLUSTER > 0) || (RF_DEBUG_VALIDATE_DAG > 0) void rf_DiskReadMirrorPartitionFunc(RF_DagNode_t *node) { /* select the mirror copy with the shortest queue and fill in node * parameters with physical disk address */ rf_SelectMirrorDiskPartition(node); rf_DiskReadFunc(node); } #endif void rf_DiskReadMirrorUndoFunc(RF_DagNode_t *node) { } #if RF_INCLUDE_PARITYLOGGING > 0 /***************************************************************************** * the execution function associated with a parity log update node ****************************************************************************/ void rf_ParityLogUpdateFunc(RF_DagNode_t *node) { RF_PhysDiskAddr_t *pda = (RF_PhysDiskAddr_t *) node->params[0].p; void *bf = (void *) node->params[1].p; RF_ParityLogData_t *logData; #if RF_ACC_TRACE > 0 RF_AccTraceEntry_t *tracerec = node->dagHdr->tracerec; RF_Etimer_t timer; #endif if (node->dagHdr->status == rf_enable) { #if RF_ACC_TRACE > 0 RF_ETIMER_START(timer); #endif logData = rf_CreateParityLogData(RF_UPDATE, pda, bf, (RF_Raid_t *) (node->dagHdr->raidPtr), node->wakeFunc, node, node->dagHdr->tracerec, timer); if (logData) rf_ParityLogAppend(logData, RF_FALSE, NULL, RF_FALSE); else { #if RF_ACC_TRACE > 0 RF_ETIMER_STOP(timer); RF_ETIMER_EVAL(timer); tracerec->plog_us += RF_ETIMER_VAL_US(timer); #endif (node->wakeFunc) (node, ENOMEM); } } } /***************************************************************************** * the execution function associated with a parity log overwrite node ****************************************************************************/ void rf_ParityLogOverwriteFunc(RF_DagNode_t *node) { RF_PhysDiskAddr_t *pda = (RF_PhysDiskAddr_t *) node->params[0].p; void *bf = (void *) node->params[1].p; RF_ParityLogData_t *logData; #if RF_ACC_TRACE > 0 RF_AccTraceEntry_t *tracerec = node->dagHdr->tracerec; RF_Etimer_t timer; #endif if (node->dagHdr->status == rf_enable) { #if RF_ACC_TRACE > 0 RF_ETIMER_START(timer); #endif logData = rf_CreateParityLogData(RF_OVERWRITE, pda, bf, (RF_Raid_t *) (node->dagHdr->raidPtr), node->wakeFunc, node, node->dagHdr->tracerec, timer); if (logData) rf_ParityLogAppend(logData, RF_FALSE, NULL, RF_FALSE); else { #if RF_ACC_TRACE > 0 RF_ETIMER_STOP(timer); RF_ETIMER_EVAL(timer); tracerec->plog_us += RF_ETIMER_VAL_US(timer); #endif (node->wakeFunc) (node, ENOMEM); } } } void rf_ParityLogUpdateUndoFunc(RF_DagNode_t *node) { } void rf_ParityLogOverwriteUndoFunc(RF_DagNode_t *node) { } #endif /* RF_INCLUDE_PARITYLOGGING > 0 */ /***************************************************************************** * the execution function associated with a NOP node ****************************************************************************/ void rf_NullNodeFunc(RF_DagNode_t *node) { node->status = rf_good; rf_FinishNode(node, RF_THREAD_CONTEXT); } void rf_NullNodeUndoFunc(RF_DagNode_t *node) { node->status = rf_undone; rf_FinishNode(node, RF_THREAD_CONTEXT); } /***************************************************************************** * the execution function associated with a disk-read node ****************************************************************************/ void rf_DiskReadFuncForThreads(RF_DagNode_t *node) { RF_DiskQueueData_t *req; RF_PhysDiskAddr_t *pda = (RF_PhysDiskAddr_t *) node->params[0].p; void *bf = (void *) node->params[1].p; RF_StripeNum_t parityStripeID = (RF_StripeNum_t) node->params[2].v; unsigned priority = RF_EXTRACT_PRIORITY(node->params[3].v); unsigned which_ru = RF_EXTRACT_RU(node->params[3].v); RF_IoType_t iotype = (node->dagHdr->status == rf_enable) ? RF_IO_TYPE_READ : RF_IO_TYPE_NOP; RF_DiskQueue_t *dqs = ((RF_Raid_t *) (node->dagHdr->raidPtr))->Queues; req = rf_CreateDiskQueueData(iotype, pda->startSector, pda->numSector, bf, parityStripeID, which_ru, node->wakeFunc, node, #if RF_ACC_TRACE > 0 node->dagHdr->tracerec, #else NULL, #endif (void *) (node->dagHdr->raidPtr), 0, node->dagHdr->bp); node->dagFuncData = (void *) req; rf_DiskIOEnqueue(&(dqs[pda->col]), req, priority); } /***************************************************************************** * the execution function associated with a disk-write node ****************************************************************************/ void rf_DiskWriteFuncForThreads(RF_DagNode_t *node) { RF_DiskQueueData_t *req; RF_PhysDiskAddr_t *pda = (RF_PhysDiskAddr_t *) node->params[0].p; void *bf = (void *) node->params[1].p; RF_StripeNum_t parityStripeID = (RF_StripeNum_t) node->params[2].v; unsigned priority = RF_EXTRACT_PRIORITY(node->params[3].v); unsigned which_ru = RF_EXTRACT_RU(node->params[3].v); RF_IoType_t iotype = (node->dagHdr->status == rf_enable) ? RF_IO_TYPE_WRITE : RF_IO_TYPE_NOP; RF_DiskQueue_t *dqs = ((RF_Raid_t *) (node->dagHdr->raidPtr))->Queues; /* normal processing (rollaway or forward recovery) begins here */ req = rf_CreateDiskQueueData(iotype, pda->startSector, pda->numSector, bf, parityStripeID, which_ru, node->wakeFunc, node, #if RF_ACC_TRACE > 0 node->dagHdr->tracerec, #else NULL, #endif (void *) (node->dagHdr->raidPtr), 0, node->dagHdr->bp); node->dagFuncData = (void *) req; rf_DiskIOEnqueue(&(dqs[pda->col]), req, priority); } /***************************************************************************** * the undo function for disk nodes * Note: this is not a proper undo of a write node, only locks are released. * old data is not restored to disk! ****************************************************************************/ void rf_DiskUndoFunc(RF_DagNode_t *node) { RF_DiskQueueData_t *req; RF_PhysDiskAddr_t *pda = (RF_PhysDiskAddr_t *) node->params[0].p; RF_DiskQueue_t *dqs = ((RF_Raid_t *) (node->dagHdr->raidPtr))->Queues; req = rf_CreateDiskQueueData(RF_IO_TYPE_NOP, 0L, 0, NULL, 0L, 0, node->wakeFunc, node, #if RF_ACC_TRACE > 0 node->dagHdr->tracerec, #else NULL, #endif (void *) (node->dagHdr->raidPtr), 0, NULL); node->dagFuncData = (void *) req; rf_DiskIOEnqueue(&(dqs[pda->col]), req, RF_IO_NORMAL_PRIORITY); } /***************************************************************************** * Callback routine for DiskRead and DiskWrite nodes. When the disk * op completes, the routine is called to set the node status and * inform the execution engine that the node has fired. ****************************************************************************/ void rf_GenericWakeupFunc(void *v, int status) { RF_DagNode_t *node = v; switch (node->status) { case rf_fired: if (status) node->status = rf_bad; else node->status = rf_good; break; case rf_recover: /* probably should never reach this case */ if (status) node->status = rf_panic; else node->status = rf_undone; break; default: printf("rf_GenericWakeupFunc:"); printf("node->status is %d,", node->status); printf("status is %d \n", status); RF_PANIC(); break; } if (node->dagFuncData) rf_FreeDiskQueueData((RF_DiskQueueData_t *) node->dagFuncData); rf_FinishNode(node, RF_INTR_CONTEXT); } /***************************************************************************** * there are three distinct types of xor nodes: * A "regular xor" is used in the fault-free case where the access * spans a complete stripe unit. It assumes that the result buffer is * one full stripe unit in size, and uses the stripe-unit-offset * values that it computes from the PDAs to determine where within the * stripe unit to XOR each argument buffer. * * A "simple xor" is used in the fault-free case where the access * touches only a portion of one (or two, in some cases) stripe * unit(s). It assumes that all the argument buffers are of the same * size and have the same stripe unit offset. * * A "recovery xor" is used in the degraded-mode case. It's similar * to the regular xor function except that it takes the failed PDA as * an additional parameter, and uses it to determine what portions of * the argument buffers need to be xor'd into the result buffer, and * where in the result buffer they should go. ****************************************************************************/ /* xor the params together and store the result in the result field. * assume the result field points to a buffer that is the size of one * SU, and use the pda params to determine where within the buffer to * XOR the input buffers. */ void rf_RegularXorFunc(RF_DagNode_t *node) { RF_Raid_t *raidPtr = (RF_Raid_t *) node->params[node->numParams - 1].p; #if RF_ACC_TRACE > 0 RF_AccTraceEntry_t *tracerec = node->dagHdr->tracerec; RF_Etimer_t timer; #endif int i, retcode; retcode = 0; if (node->dagHdr->status == rf_enable) { /* don't do the XOR if the input is the same as the output */ #if RF_ACC_TRACE > 0 RF_ETIMER_START(timer); #endif for (i = 0; i < node->numParams - 1; i += 2) if (node->params[i + 1].p != node->results[0]) { retcode = rf_XorIntoBuffer(raidPtr, (RF_PhysDiskAddr_t *) node->params[i].p, (char *) node->params[i + 1].p, (char *) node->results[0]); } #if RF_ACC_TRACE > 0 RF_ETIMER_STOP(timer); RF_ETIMER_EVAL(timer); tracerec->xor_us += RF_ETIMER_VAL_US(timer); #endif } rf_GenericWakeupFunc(node, retcode); /* call wake func * explicitly since no * I/O in this node */ } /* xor the inputs into the result buffer, ignoring placement issues */ void rf_SimpleXorFunc(RF_DagNode_t *node) { RF_Raid_t *raidPtr = (RF_Raid_t *) node->params[node->numParams - 1].p; int i, retcode = 0; #if RF_ACC_TRACE > 0 RF_AccTraceEntry_t *tracerec = node->dagHdr->tracerec; RF_Etimer_t timer; #endif if (node->dagHdr->status == rf_enable) { #if RF_ACC_TRACE > 0 RF_ETIMER_START(timer); #endif /* don't do the XOR if the input is the same as the output */ for (i = 0; i < node->numParams - 1; i += 2) if (node->params[i + 1].p != node->results[0]) { retcode = rf_bxor((char *) node->params[i + 1].p, (char *) node->results[0], rf_RaidAddressToByte(raidPtr, ((RF_PhysDiskAddr_t *) node->params[i].p)->numSector)); } #if RF_ACC_TRACE > 0 RF_ETIMER_STOP(timer); RF_ETIMER_EVAL(timer); tracerec->xor_us += RF_ETIMER_VAL_US(timer); #endif } rf_GenericWakeupFunc(node, retcode); /* call wake func * explicitly since no * I/O in this node */ } /* this xor is used by the degraded-mode dag functions to recover lost * data. the second-to-last parameter is the PDA for the failed * portion of the access. the code here looks at this PDA and assumes * that the xor target buffer is equal in size to the number of * sectors in the failed PDA. It then uses the other PDAs in the * parameter list to determine where within the target buffer the * corresponding data should be xored. */ void rf_RecoveryXorFunc(RF_DagNode_t *node) { RF_Raid_t *raidPtr = (RF_Raid_t *) node->params[node->numParams - 1].p; RF_RaidLayout_t *layoutPtr = (RF_RaidLayout_t *) & raidPtr->Layout; RF_PhysDiskAddr_t *failedPDA = (RF_PhysDiskAddr_t *) node->params[node->numParams - 2].p; int i, retcode = 0; RF_PhysDiskAddr_t *pda; int suoffset, failedSUOffset = rf_StripeUnitOffset(layoutPtr, failedPDA->startSector); char *srcbuf, *destbuf; #if RF_ACC_TRACE > 0 RF_AccTraceEntry_t *tracerec = node->dagHdr->tracerec; RF_Etimer_t timer; #endif if (node->dagHdr->status == rf_enable) { #if RF_ACC_TRACE > 0 RF_ETIMER_START(timer); #endif for (i = 0; i < node->numParams - 2; i += 2) if (node->params[i + 1].p != node->results[0]) { pda = (RF_PhysDiskAddr_t *) node->params[i].p; srcbuf = (char *) node->params[i + 1].p; suoffset = rf_StripeUnitOffset(layoutPtr, pda->startSector); destbuf = ((char *) node->results[0]) + rf_RaidAddressToByte(raidPtr, suoffset - failedSUOffset); retcode = rf_bxor(srcbuf, destbuf, rf_RaidAddressToByte(raidPtr, pda->numSector)); } #if RF_ACC_TRACE > 0 RF_ETIMER_STOP(timer); RF_ETIMER_EVAL(timer); tracerec->xor_us += RF_ETIMER_VAL_US(timer); #endif } rf_GenericWakeupFunc(node, retcode); } /***************************************************************************** * The next three functions are utilities used by the above * xor-execution functions. ****************************************************************************/ /* * this is just a glorified buffer xor. targbuf points to a buffer * that is one full stripe unit in size. srcbuf points to a buffer * that may be less than 1 SU, but never more. When the access * described by pda is one SU in size (which by implication means it's * SU-aligned), all that happens is (targbuf) <- (srcbuf ^ targbuf). * When the access is less than one SU in size the XOR occurs on only * the portion of targbuf identified in the pda. */ int rf_XorIntoBuffer(RF_Raid_t *raidPtr, RF_PhysDiskAddr_t *pda, char *srcbuf, char *targbuf) { char *targptr; int sectPerSU = raidPtr->Layout.sectorsPerStripeUnit; int SUOffset = pda->startSector % sectPerSU; int length, retcode = 0; RF_ASSERT(pda->numSector <= sectPerSU); targptr = targbuf + rf_RaidAddressToByte(raidPtr, SUOffset); length = rf_RaidAddressToByte(raidPtr, pda->numSector); retcode = rf_bxor(srcbuf, targptr, length); return (retcode); } /* it really should be the case that the buffer pointers (returned by * malloc) are aligned to the natural word size of the machine, so * this is the only case we optimize for. The length should always be * a multiple of the sector size, so there should be no problem with * leftover bytes at the end. */ int rf_bxor(char *src, char *dest, int len) { unsigned mask = sizeof(long) - 1, retcode = 0; if (!(((unsigned long) src) & mask) && !(((unsigned long) dest) & mask) && !(len & mask)) { retcode = rf_longword_bxor((unsigned long *) src, (unsigned long *) dest, len >> RF_LONGSHIFT); } else { RF_ASSERT(0); } return (retcode); } /* When XORing in kernel mode, we need to map each user page to kernel * space before we can access it. We don't want to assume anything * about which input buffers are in kernel/user space, nor about their * alignment, so in each loop we compute the maximum number of bytes * that we can xor without crossing any page boundaries, and do only * this many bytes before the next remap. * * len - is in longwords */ int rf_longword_bxor(unsigned long *src, unsigned long *dest, int len) { unsigned long *end = src + len; unsigned long d0, d1, d2, d3, s0, s1, s2, s3; /* temps */ unsigned long *pg_src, *pg_dest; /* per-page source/dest pointers */ int longs_this_time;/* # longwords to xor in the current iteration */ pg_src = src; pg_dest = dest; if (!pg_src || !pg_dest) return (EFAULT); while (len >= 4) { longs_this_time = RF_MIN(len, RF_MIN(RF_BLIP(pg_src), RF_BLIP(pg_dest)) >> RF_LONGSHIFT); /* note len in longwords */ src += longs_this_time; dest += longs_this_time; len -= longs_this_time; while (longs_this_time >= 4) { d0 = pg_dest[0]; d1 = pg_dest[1]; d2 = pg_dest[2]; d3 = pg_dest[3]; s0 = pg_src[0]; s1 = pg_src[1]; s2 = pg_src[2]; s3 = pg_src[3]; pg_dest[0] = d0 ^ s0; pg_dest[1] = d1 ^ s1; pg_dest[2] = d2 ^ s2; pg_dest[3] = d3 ^ s3; pg_src += 4; pg_dest += 4; longs_this_time -= 4; } while (longs_this_time > 0) { /* cannot cross any page * boundaries here */ *pg_dest++ ^= *pg_src++; longs_this_time--; } /* either we're done, or we've reached a page boundary on one * (or possibly both) of the pointers */ if (len) { if (RF_PAGE_ALIGNED(src)) pg_src = src; if (RF_PAGE_ALIGNED(dest)) pg_dest = dest; if (!pg_src || !pg_dest) return (EFAULT); } } while (src < end) { *pg_dest++ ^= *pg_src++; src++; dest++; len--; if (RF_PAGE_ALIGNED(src)) pg_src = src; if (RF_PAGE_ALIGNED(dest)) pg_dest = dest; } RF_ASSERT(len == 0); return (0); } #if 0 /* dst = a ^ b ^ c; a may equal dst see comment above longword_bxor len is length in longwords */ int rf_longword_bxor3(unsigned long *dst, unsigned long *a, unsigned long *b, unsigned long *c, int len, void *bp) { unsigned long a0, a1, a2, a3, b0, b1, b2, b3; unsigned long *pg_a, *pg_b, *pg_c, *pg_dst; /* per-page source/dest * pointers */ int longs_this_time;/* # longs to xor in the current iteration */ char dst_is_a = 0; pg_a = a; pg_b = b; pg_c = c; if (a == dst) { pg_dst = pg_a; dst_is_a = 1; } else { pg_dst = dst; } /* align dest to cache line. Can't cross a pg boundary on dst here. */ while ((((unsigned long) pg_dst) & 0x1f)) { *pg_dst++ = *pg_a++ ^ *pg_b++ ^ *pg_c++; dst++; a++; b++; c++; if (RF_PAGE_ALIGNED(a)) { pg_a = a; if (!pg_a) return (EFAULT); } if (RF_PAGE_ALIGNED(b)) { pg_b = a; if (!pg_b) return (EFAULT); } if (RF_PAGE_ALIGNED(c)) { pg_c = a; if (!pg_c) return (EFAULT); } len--; } while (len > 4) { longs_this_time = RF_MIN(len, RF_MIN(RF_BLIP(a), RF_MIN(RF_BLIP(b), RF_MIN(RF_BLIP(c), RF_BLIP(dst)))) >> RF_LONGSHIFT); a += longs_this_time; b += longs_this_time; c += longs_this_time; dst += longs_this_time; len -= longs_this_time; while (longs_this_time >= 4) { a0 = pg_a[0]; longs_this_time -= 4; a1 = pg_a[1]; a2 = pg_a[2]; a3 = pg_a[3]; pg_a += 4; b0 = pg_b[0]; b1 = pg_b[1]; b2 = pg_b[2]; b3 = pg_b[3]; /* start dual issue */ a0 ^= b0; b0 = pg_c[0]; pg_b += 4; a1 ^= b1; a2 ^= b2; a3 ^= b3; b1 = pg_c[1]; a0 ^= b0; b2 = pg_c[2]; a1 ^= b1; b3 = pg_c[3]; a2 ^= b2; pg_dst[0] = a0; a3 ^= b3; pg_dst[1] = a1; pg_c += 4; pg_dst[2] = a2; pg_dst[3] = a3; pg_dst += 4; } while (longs_this_time > 0) { /* cannot cross any page * boundaries here */ *pg_dst++ = *pg_a++ ^ *pg_b++ ^ *pg_c++; longs_this_time--; } if (len) { if (RF_PAGE_ALIGNED(a)) { pg_a = a; if (!pg_a) return (EFAULT); if (dst_is_a) pg_dst = pg_a; } if (RF_PAGE_ALIGNED(b)) { pg_b = b; if (!pg_b) return (EFAULT); } if (RF_PAGE_ALIGNED(c)) { pg_c = c; if (!pg_c) return (EFAULT); } if (!dst_is_a) if (RF_PAGE_ALIGNED(dst)) { pg_dst = dst; if (!pg_dst) return (EFAULT); } } } while (len) { *pg_dst++ = *pg_a++ ^ *pg_b++ ^ *pg_c++; dst++; a++; b++; c++; if (RF_PAGE_ALIGNED(a)) { pg_a = a; if (!pg_a) return (EFAULT); if (dst_is_a) pg_dst = pg_a; } if (RF_PAGE_ALIGNED(b)) { pg_b = b; if (!pg_b) return (EFAULT); } if (RF_PAGE_ALIGNED(c)) { pg_c = c; if (!pg_c) return (EFAULT); } if (!dst_is_a) if (RF_PAGE_ALIGNED(dst)) { pg_dst = dst; if (!pg_dst) return (EFAULT); } len--; } return (0); } int rf_bxor3(unsigned char *dst, unsigned char *a, unsigned char *b, unsigned char *c, unsigned long len, void *bp) { RF_ASSERT(((RF_UL(dst) | RF_UL(a) | RF_UL(b) | RF_UL(c) | len) & 0x7) == 0); return (rf_longword_bxor3((unsigned long *) dst, (unsigned long *) a, (unsigned long *) b, (unsigned long *) c, len >> RF_LONGSHIFT, bp)); } #endif |
3 3 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 | /* $NetBSD: if_smsc.c,v 1.93 2022/08/20 14:08:59 riastradh Exp $ */ /* $OpenBSD: if_smsc.c,v 1.4 2012/09/27 12:38:11 jsg Exp $ */ /* $FreeBSD: src/sys/dev/usb/net/if_smsc.c,v 1.1 2012/08/15 04:03:55 gonzo Exp $ */ /*- * Copyright (c) 2012 * Ben Gray <bgray@freebsd.org>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * SMSC LAN9xxx devices (http://www.smsc.com/) * * The LAN9500 & LAN9500A devices are stand-alone USB to Ethernet chips that * support USB 2.0 and 10/100 Mbps Ethernet. * * The LAN951x devices are an integrated USB hub and USB to Ethernet adapter. * The driver only covers the Ethernet part, the standard USB hub driver * supports the hub part. * * This driver is closely modelled on the Linux driver written and copyrighted * by SMSC. * * H/W TCP & UDP Checksum Offloading * --------------------------------- * The chip supports both tx and rx offloading of UDP & TCP checksums, this * feature can be dynamically enabled/disabled. * * RX checksuming is performed across bytes after the IPv4 header to the end of * the Ethernet frame, this means if the frame is padded with non-zero values * the H/W checksum will be incorrect, however the rx code compensates for this. * * TX checksuming is more complicated, the device requires a special header to * be prefixed onto the start of the frame which indicates the start and end * positions of the UDP or TCP frame. This requires the driver to manually * go through the packet data and decode the headers prior to sending. * On Linux they generally provide cues to the location of the csum and the * area to calculate it over, on FreeBSD we seem to have to do it all ourselves, * hence this is not as optimal and therefore h/w TX checksum is currently not * implemented. */ #include <sys/cdefs.h> __KERNEL_RCSID(0, "$NetBSD: if_smsc.c,v 1.93 2022/08/20 14:08:59 riastradh Exp $"); #ifdef _KERNEL_OPT #include "opt_usb.h" #endif #include <sys/param.h> #include <dev/usb/usbnet.h> #include <dev/usb/usbhist.h> #include <dev/usb/if_smscreg.h> #include "ioconf.h" struct smsc_softc { struct usbnet smsc_un; /* * The following stores the settings in the mac control (MAC_CSR) * register */ uint32_t sc_mac_csr; uint32_t sc_rev_id; uint32_t sc_coe_ctrl; }; #define SMSC_MIN_BUFSZ 2048 #define SMSC_MAX_BUFSZ 18944 /* * Various supported device vendors/products. */ static const struct usb_devno smsc_devs[] = { { USB_VENDOR_SMSC, |