1 /* $NetBSD: uipc_socket.c,v 1.168 2008/06/18 09:06:27 yamt Exp $ */ 2 3 /*- 4 * Copyright (c) 2002, 2007, 2008 The NetBSD Foundation, Inc. 5 * All rights reserved. 6 * 7 * This code is derived from software contributed to The NetBSD Foundation 8 * by Jason R. Thorpe of Wasabi Systems, Inc. 9 * 10 * Redistribution and use in source and binary forms, with or without 11 * modification, are permitted provided that the following conditions 12 * are met: 13 * 1. Redistributions of source code must retain the above copyright 14 * notice, this list of conditions and the following disclaimer. 15 * 2. Redistributions in binary form must reproduce the above copyright 16 * notice, this list of conditions and the following disclaimer in the 17 * documentation and/or other materials provided with the distribution. 18 * 19 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS 20 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED 21 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 22 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS 23 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 24 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 25 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 26 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 27 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 28 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 29 * POSSIBILITY OF SUCH DAMAGE. 30 */ 31 32 /* 33 * Copyright (c) 2004 The FreeBSD Foundation 34 * Copyright (c) 2004 Robert Watson 35 * Copyright (c) 1982, 1986, 1988, 1990, 1993 36 * The Regents of the University of California. All rights reserved. 37 * 38 * Redistribution and use in source and binary forms, with or without 39 * modification, are permitted provided that the following conditions 40 * are met: 41 * 1. Redistributions of source code must retain the above copyright 42 * notice, this list of conditions and the following disclaimer. 43 * 2. Redistributions in binary form must reproduce the above copyright 44 * notice, this list of conditions and the following disclaimer in the 45 * documentation and/or other materials provided with the distribution. 46 * 3. Neither the name of the University nor the names of its contributors 47 * may be used to endorse or promote products derived from this software 48 * without specific prior written permission. 49 * 50 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND 51 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 52 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 53 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE 54 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 55 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS 56 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 57 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 58 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY 59 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 60 * SUCH DAMAGE. 61 * 62 * @(#)uipc_socket.c 8.6 (Berkeley) 5/2/95 63 */ 64 65 #include <sys/cdefs.h> 66 __KERNEL_RCSID(0, "$NetBSD: uipc_socket.c,v 1.168 2008/06/18 09:06:27 yamt Exp $"); 67 68 #include "opt_sock_counters.h" 69 #include "opt_sosend_loan.h" 70 #include "opt_mbuftrace.h" 71 #include "opt_somaxkva.h" 72 #include "opt_multiprocessor.h" /* XXX */ 73 74 #include <sys/param.h> 75 #include <sys/systm.h> 76 #include <sys/proc.h> 77 #include <sys/file.h> 78 #include <sys/filedesc.h> 79 #include <sys/malloc.h> 80 #include <sys/mbuf.h> 81 #include <sys/domain.h> 82 #include <sys/kernel.h> 83 #include <sys/protosw.h> 84 #include <sys/socket.h> 85 #include <sys/socketvar.h> 86 #include <sys/signalvar.h> 87 #include <sys/resourcevar.h> 88 #include <sys/event.h> 89 #include <sys/poll.h> 90 #include <sys/kauth.h> 91 #include <sys/mutex.h> 92 #include <sys/condvar.h> 93 94 #include <uvm/uvm.h> 95 96 MALLOC_DEFINE(M_SOOPTS, "soopts", "socket options"); 97 MALLOC_DEFINE(M_SONAME, "soname", "socket name"); 98 99 extern const struct fileops socketops; 100 101 extern int somaxconn; /* patchable (XXX sysctl) */ 102 int somaxconn = SOMAXCONN; 103 kmutex_t *softnet_lock; 104 105 #ifdef SOSEND_COUNTERS 106 #include <sys/device.h> 107 108 static struct evcnt sosend_loan_big = EVCNT_INITIALIZER(EVCNT_TYPE_MISC, 109 NULL, "sosend", "loan big"); 110 static struct evcnt sosend_copy_big = EVCNT_INITIALIZER(EVCNT_TYPE_MISC, 111 NULL, "sosend", "copy big"); 112 static struct evcnt sosend_copy_small = EVCNT_INITIALIZER(EVCNT_TYPE_MISC, 113 NULL, "sosend", "copy small"); 114 static struct evcnt sosend_kvalimit = EVCNT_INITIALIZER(EVCNT_TYPE_MISC, 115 NULL, "sosend", "kva limit"); 116 117 #define SOSEND_COUNTER_INCR(ev) (ev)->ev_count++ 118 119 EVCNT_ATTACH_STATIC(sosend_loan_big); 120 EVCNT_ATTACH_STATIC(sosend_copy_big); 121 EVCNT_ATTACH_STATIC(sosend_copy_small); 122 EVCNT_ATTACH_STATIC(sosend_kvalimit); 123 #else 124 125 #define SOSEND_COUNTER_INCR(ev) /* nothing */ 126 127 #endif /* SOSEND_COUNTERS */ 128 129 static struct callback_entry sokva_reclaimerentry; 130 131 #if defined(SOSEND_NO_LOAN) || defined(MULTIPROCESSOR) 132 int sock_loan_thresh = -1; 133 #else 134 int sock_loan_thresh = 4096; 135 #endif 136 137 static kmutex_t so_pendfree_lock; 138 static struct mbuf *so_pendfree; 139 140 #ifndef SOMAXKVA 141 #define SOMAXKVA (16 * 1024 * 1024) 142 #endif 143 int somaxkva = SOMAXKVA; 144 static int socurkva; 145 static kcondvar_t socurkva_cv; 146 147 #define SOCK_LOAN_CHUNK 65536 148 149 static size_t sodopendfree(void); 150 static size_t sodopendfreel(void); 151 152 static vsize_t 153 sokvareserve(struct socket *so, vsize_t len) 154 { 155 int error; 156 157 mutex_enter(&so_pendfree_lock); 158 while (socurkva + len > somaxkva) { 159 size_t freed; 160 161 /* 162 * try to do pendfree. 163 */ 164 165 freed = sodopendfreel(); 166 167 /* 168 * if some kva was freed, try again. 169 */ 170 171 if (freed) 172 continue; 173 174 SOSEND_COUNTER_INCR(&sosend_kvalimit); 175 error = cv_wait_sig(&socurkva_cv, &so_pendfree_lock); 176 if (error) { 177 len = 0; 178 break; 179 } 180 } 181 socurkva += len; 182 mutex_exit(&so_pendfree_lock); 183 return len; 184 } 185 186 static void 187 sokvaunreserve(vsize_t len) 188 { 189 190 mutex_enter(&so_pendfree_lock); 191 socurkva -= len; 192 cv_broadcast(&socurkva_cv); 193 mutex_exit(&so_pendfree_lock); 194 } 195 196 /* 197 * sokvaalloc: allocate kva for loan. 198 */ 199 200 vaddr_t 201 sokvaalloc(vsize_t len, struct socket *so) 202 { 203 vaddr_t lva; 204 205 /* 206 * reserve kva. 207 */ 208 209 if (sokvareserve(so, len) == 0) 210 return 0; 211 212 /* 213 * allocate kva. 214 */ 215 216 lva = uvm_km_alloc(kernel_map, len, 0, UVM_KMF_VAONLY | UVM_KMF_WAITVA); 217 if (lva == 0) { 218 sokvaunreserve(len); 219 return (0); 220 } 221 222 return lva; 223 } 224 225 /* 226 * sokvafree: free kva for loan. 227 */ 228 229 void 230 sokvafree(vaddr_t sva, vsize_t len) 231 { 232 233 /* 234 * free kva. 235 */ 236 237 uvm_km_free(kernel_map, sva, len, UVM_KMF_VAONLY); 238 239 /* 240 * unreserve kva. 241 */ 242 243 sokvaunreserve(len); 244 } 245 246 static void 247 sodoloanfree(struct vm_page **pgs, void *buf, size_t size) 248 { 249 vaddr_t sva, eva; 250 vsize_t len; 251 int npgs; 252 253 KASSERT(pgs != NULL); 254 255 eva = round_page((vaddr_t) buf + size); 256 sva = trunc_page((vaddr_t) buf); 257 len = eva - sva; 258 npgs = len >> PAGE_SHIFT; 259 260 pmap_kremove(sva, len); 261 pmap_update(pmap_kernel()); 262 uvm_unloan(pgs, npgs, UVM_LOAN_TOPAGE); 263 sokvafree(sva, len); 264 } 265 266 static size_t 267 sodopendfree(void) 268 { 269 size_t rv; 270 271 if (__predict_true(so_pendfree == NULL)) 272 return 0; 273 274 mutex_enter(&so_pendfree_lock); 275 rv = sodopendfreel(); 276 mutex_exit(&so_pendfree_lock); 277 278 return rv; 279 } 280 281 /* 282 * sodopendfreel: free mbufs on "pendfree" list. 283 * unlock and relock so_pendfree_lock when freeing mbufs. 284 * 285 * => called with so_pendfree_lock held. 286 */ 287 288 static size_t 289 sodopendfreel(void) 290 { 291 struct mbuf *m, *next; 292 size_t rv = 0; 293 294 KASSERT(mutex_owned(&so_pendfree_lock)); 295 296 while (so_pendfree != NULL) { 297 m = so_pendfree; 298 so_pendfree = NULL; 299 mutex_exit(&so_pendfree_lock); 300 301 for (; m != NULL; m = next) { 302 next = m->m_next; 303 KASSERT((~m->m_flags & (M_EXT|M_EXT_PAGES)) == 0); 304 KASSERT(m->m_ext.ext_refcnt == 0); 305 306 rv += m->m_ext.ext_size; 307 sodoloanfree(m->m_ext.ext_pgs, m->m_ext.ext_buf, 308 m->m_ext.ext_size); 309 pool_cache_put(mb_cache, m); 310 } 311 312 mutex_enter(&so_pendfree_lock); 313 } 314 315 return (rv); 316 } 317 318 void 319 soloanfree(struct mbuf *m, void *buf, size_t size, void *arg) 320 { 321 322 KASSERT(m != NULL); 323 324 /* 325 * postpone freeing mbuf. 326 * 327 * we can't do it in interrupt context 328 * because we need to put kva back to kernel_map. 329 */ 330 331 mutex_enter(&so_pendfree_lock); 332 m->m_next = so_pendfree; 333 so_pendfree = m; 334 cv_broadcast(&socurkva_cv); 335 mutex_exit(&so_pendfree_lock); 336 } 337 338 static long 339 sosend_loan(struct socket *so, struct uio *uio, struct mbuf *m, long space) 340 { 341 struct iovec *iov = uio->uio_iov; 342 vaddr_t sva, eva; 343 vsize_t len; 344 vaddr_t lva; 345 int npgs, error; 346 vaddr_t va; 347 int i; 348 349 if (VMSPACE_IS_KERNEL_P(uio->uio_vmspace)) 350 return (0); 351 352 if (iov->iov_len < (size_t) space) 353 space = iov->iov_len; 354 if (space > SOCK_LOAN_CHUNK) 355 space = SOCK_LOAN_CHUNK; 356 357 eva = round_page((vaddr_t) iov->iov_base + space); 358 sva = trunc_page((vaddr_t) iov->iov_base); 359 len = eva - sva; 360 npgs = len >> PAGE_SHIFT; 361 362 KASSERT(npgs <= M_EXT_MAXPAGES); 363 364 lva = sokvaalloc(len, so); 365 if (lva == 0) 366 return 0; 367 368 error = uvm_loan(&uio->uio_vmspace->vm_map, sva, len, 369 m->m_ext.ext_pgs, UVM_LOAN_TOPAGE); 370 if (error) { 371 sokvafree(lva, len); 372 return (0); 373 } 374 375 for (i = 0, va = lva; i < npgs; i++, va += PAGE_SIZE) 376 pmap_kenter_pa(va, VM_PAGE_TO_PHYS(m->m_ext.ext_pgs[i]), 377 VM_PROT_READ); 378 pmap_update(pmap_kernel()); 379 380 lva += (vaddr_t) iov->iov_base & PAGE_MASK; 381 382 MEXTADD(m, (void *) lva, space, M_MBUF, soloanfree, so); 383 m->m_flags |= M_EXT_PAGES | M_EXT_ROMAP; 384 385 uio->uio_resid -= space; 386 /* uio_offset not updated, not set/used for write(2) */ 387 uio->uio_iov->iov_base = (char *)uio->uio_iov->iov_base + space; 388 uio->uio_iov->iov_len -= space; 389 if (uio->uio_iov->iov_len == 0) { 390 uio->uio_iov++; 391 uio->uio_iovcnt--; 392 } 393 394 return (space); 395 } 396 397 static int 398 sokva_reclaim_callback(struct callback_entry *ce, void *obj, void *arg) 399 { 400 401 KASSERT(ce == &sokva_reclaimerentry); 402 KASSERT(obj == NULL); 403 404 sodopendfree(); 405 if (!vm_map_starved_p(kernel_map)) { 406 return CALLBACK_CHAIN_ABORT; 407 } 408 return CALLBACK_CHAIN_CONTINUE; 409 } 410 411 struct mbuf * 412 getsombuf(struct socket *so, int type) 413 { 414 struct mbuf *m; 415 416 m = m_get(M_WAIT, type); 417 MCLAIM(m, so->so_mowner); 418 return m; 419 } 420 421 struct mbuf * 422 m_intopt(struct socket *so, int val) 423 { 424 struct mbuf *m; 425 426 m = getsombuf(so, MT_SOOPTS); 427 m->m_len = sizeof(int); 428 *mtod(m, int *) = val; 429 return m; 430 } 431 432 void 433 soinit(void) 434 { 435 436 mutex_init(&so_pendfree_lock, MUTEX_DEFAULT, IPL_VM); 437 softnet_lock = mutex_obj_alloc(MUTEX_DEFAULT, IPL_NONE); 438 cv_init(&socurkva_cv, "sokva"); 439 soinit2(); 440 441 /* Set the initial adjusted socket buffer size. */ 442 if (sb_max_set(sb_max)) 443 panic("bad initial sb_max value: %lu", sb_max); 444 445 callback_register(&vm_map_to_kernel(kernel_map)->vmk_reclaim_callback, 446 &sokva_reclaimerentry, NULL, sokva_reclaim_callback); 447 } 448 449 /* 450 * Socket operation routines. 451 * These routines are called by the routines in 452 * sys_socket.c or from a system process, and 453 * implement the semantics of socket operations by 454 * switching out to the protocol specific routines. 455 */ 456 /*ARGSUSED*/ 457 int 458 socreate(int dom, struct socket **aso, int type, int proto, struct lwp *l, 459 struct socket *lockso) 460 { 461 const struct protosw *prp; 462 struct socket *so; 463 uid_t uid; 464 int error; 465 kmutex_t *lock; 466 467 error = kauth_authorize_network(l->l_cred, KAUTH_NETWORK_SOCKET, 468 KAUTH_REQ_NETWORK_SOCKET_OPEN, KAUTH_ARG(dom), KAUTH_ARG(type), 469 KAUTH_ARG(proto)); 470 if (error != 0) 471 return error; 472 473 if (proto) 474 prp = pffindproto(dom, proto, type); 475 else 476 prp = pffindtype(dom, type); 477 if (prp == NULL) { 478 /* no support for domain */ 479 if (pffinddomain(dom) == 0) 480 return EAFNOSUPPORT; 481 /* no support for socket type */ 482 if (proto == 0 && type != 0) 483 return EPROTOTYPE; 484 return EPROTONOSUPPORT; 485 } 486 if (prp->pr_usrreq == NULL) 487 return EPROTONOSUPPORT; 488 if (prp->pr_type != type) 489 return EPROTOTYPE; 490 491 so = soget(true); 492 so->so_type = type; 493 so->so_proto = prp; 494 so->so_send = sosend; 495 so->so_receive = soreceive; 496 #ifdef MBUFTRACE 497 so->so_rcv.sb_mowner = &prp->pr_domain->dom_mowner; 498 so->so_snd.sb_mowner = &prp->pr_domain->dom_mowner; 499 so->so_mowner = &prp->pr_domain->dom_mowner; 500 #endif 501 uid = kauth_cred_geteuid(l->l_cred); 502 so->so_uidinfo = uid_find(uid); 503 so->so_egid = kauth_cred_getegid(l->l_cred); 504 so->so_cpid = l->l_proc->p_pid; 505 if (lockso != NULL) { 506 /* Caller wants us to share a lock. */ 507 lock = lockso->so_lock; 508 so->so_lock = lock; 509 mutex_obj_hold(lock); 510 mutex_enter(lock); 511 } else { 512 /* Lock assigned and taken during PRU_ATTACH. */ 513 } 514 error = (*prp->pr_usrreq)(so, PRU_ATTACH, NULL, 515 (struct mbuf *)(long)proto, NULL, l); 516 KASSERT(solocked(so)); 517 if (error != 0) { 518 so->so_state |= SS_NOFDREF; 519 sofree(so); 520 return error; 521 } 522 sounlock(so); 523 *aso = so; 524 return 0; 525 } 526 527 /* On success, write file descriptor to fdout and return zero. On 528 * failure, return non-zero; *fdout will be undefined. 529 */ 530 int 531 fsocreate(int domain, struct socket **sop, int type, int protocol, 532 struct lwp *l, int *fdout) 533 { 534 struct socket *so; 535 struct file *fp; 536 int fd, error; 537 538 if ((error = fd_allocfile(&fp, &fd)) != 0) 539 return (error); 540 fp->f_flag = FREAD|FWRITE; 541 fp->f_type = DTYPE_SOCKET; 542 fp->f_ops = &socketops; 543 error = socreate(domain, &so, type, protocol, l, NULL); 544 if (error != 0) { 545 fd_abort(curproc, fp, fd); 546 } else { 547 if (sop != NULL) 548 *sop = so; 549 fp->f_data = so; 550 fd_affix(curproc, fp, fd); 551 *fdout = fd; 552 } 553 return error; 554 } 555 556 int 557 sobind(struct socket *so, struct mbuf *nam, struct lwp *l) 558 { 559 int error; 560 561 solock(so); 562 error = (*so->so_proto->pr_usrreq)(so, PRU_BIND, NULL, nam, NULL, l); 563 sounlock(so); 564 return error; 565 } 566 567 int 568 solisten(struct socket *so, int backlog, struct lwp *l) 569 { 570 int error; 571 572 solock(so); 573 if ((so->so_state & (SS_ISCONNECTED | SS_ISCONNECTING | 574 SS_ISDISCONNECTING)) != 0) { 575 sounlock(so); 576 return (EOPNOTSUPP); 577 } 578 error = (*so->so_proto->pr_usrreq)(so, PRU_LISTEN, NULL, 579 NULL, NULL, l); 580 if (error != 0) { 581 sounlock(so); 582 return error; 583 } 584 if (TAILQ_EMPTY(&so->so_q)) 585 so->so_options |= SO_ACCEPTCONN; 586 if (backlog < 0) 587 backlog = 0; 588 so->so_qlimit = min(backlog, somaxconn); 589 sounlock(so); 590 return 0; 591 } 592 593 void 594 sofree(struct socket *so) 595 { 596 u_int refs; 597 598 KASSERT(solocked(so)); 599 600 if (so->so_pcb || (so->so_state & SS_NOFDREF) == 0) { 601 sounlock(so); 602 return; 603 } 604 if (so->so_head) { 605 /* 606 * We must not decommission a socket that's on the accept(2) 607 * queue. If we do, then accept(2) may hang after select(2) 608 * indicated that the listening socket was ready. 609 */ 610 if (!soqremque(so, 0)) { 611 sounlock(so); 612 return; 613 } 614 } 615 if (so->so_rcv.sb_hiwat) 616 (void)chgsbsize(so->so_uidinfo, &so->so_rcv.sb_hiwat, 0, 617 RLIM_INFINITY); 618 if (so->so_snd.sb_hiwat) 619 (void)chgsbsize(so->so_uidinfo, &so->so_snd.sb_hiwat, 0, 620 RLIM_INFINITY); 621 sbrelease(&so->so_snd, so); 622 KASSERT(!cv_has_waiters(&so->so_cv)); 623 KASSERT(!cv_has_waiters(&so->so_rcv.sb_cv)); 624 KASSERT(!cv_has_waiters(&so->so_snd.sb_cv)); 625 sorflush(so); 626 refs = so->so_aborting; /* XXX */ 627 sounlock(so); 628 if (refs == 0) /* XXX */ 629 soput(so); 630 } 631 632 /* 633 * Close a socket on last file table reference removal. 634 * Initiate disconnect if connected. 635 * Free socket when disconnect complete. 636 */ 637 int 638 soclose(struct socket *so) 639 { 640 struct socket *so2; 641 int error; 642 int error2; 643 644 error = 0; 645 solock(so); 646 if (so->so_options & SO_ACCEPTCONN) { 647 do { 648 if ((so2 = TAILQ_FIRST(&so->so_q0)) != 0) { 649 KASSERT(solocked2(so, so2)); 650 (void) soqremque(so2, 0); 651 /* soabort drops the lock. */ 652 (void) soabort(so2); 653 solock(so); 654 continue; 655 } 656 if ((so2 = TAILQ_FIRST(&so->so_q)) != 0) { 657 KASSERT(solocked2(so, so2)); 658 (void) soqremque(so2, 1); 659 /* soabort drops the lock. */ 660 (void) soabort(so2); 661 solock(so); 662 continue; 663 } 664 } while (0); 665 } 666 if (so->so_pcb == 0) 667 goto discard; 668 if (so->so_state & SS_ISCONNECTED) { 669 if ((so->so_state & SS_ISDISCONNECTING) == 0) { 670 error = sodisconnect(so); 671 if (error) 672 goto drop; 673 } 674 if (so->so_options & SO_LINGER) { 675 if ((so->so_state & SS_ISDISCONNECTING) && so->so_nbio) 676 goto drop; 677 while (so->so_state & SS_ISCONNECTED) { 678 error = sowait(so, so->so_linger * hz); 679 if (error) 680 break; 681 } 682 } 683 } 684 drop: 685 if (so->so_pcb) { 686 error2 = (*so->so_proto->pr_usrreq)(so, PRU_DETACH, 687 NULL, NULL, NULL, NULL); 688 if (error == 0) 689 error = error2; 690 } 691 discard: 692 if (so->so_state & SS_NOFDREF) 693 panic("soclose: NOFDREF"); 694 so->so_state |= SS_NOFDREF; 695 sofree(so); 696 return (error); 697 } 698 699 /* 700 * Must be called with the socket locked.. Will return with it unlocked. 701 */ 702 int 703 soabort(struct socket *so) 704 { 705 u_int refs; 706 int error; 707 708 KASSERT(solocked(so)); 709 KASSERT(so->so_head == NULL); 710 711 so->so_aborting++; /* XXX */ 712 error = (*so->so_proto->pr_usrreq)(so, PRU_ABORT, NULL, 713 NULL, NULL, NULL); 714 refs = --so->so_aborting; /* XXX */ 715 if (error || (refs == 0)) { 716 sofree(so); 717 } else { 718 sounlock(so); 719 } 720 return error; 721 } 722 723 int 724 soaccept(struct socket *so, struct mbuf *nam) 725 { 726 int error; 727 728 KASSERT(solocked(so)); 729 730 error = 0; 731 if ((so->so_state & SS_NOFDREF) == 0) 732 panic("soaccept: !NOFDREF"); 733 so->so_state &= ~SS_NOFDREF; 734 if ((so->so_state & SS_ISDISCONNECTED) == 0 || 735 (so->so_proto->pr_flags & PR_ABRTACPTDIS) == 0) 736 error = (*so->so_proto->pr_usrreq)(so, PRU_ACCEPT, 737 NULL, nam, NULL, NULL); 738 else 739 error = ECONNABORTED; 740 741 return (error); 742 } 743 744 int 745 soconnect(struct socket *so, struct mbuf *nam, struct lwp *l) 746 { 747 int error; 748 749 KASSERT(solocked(so)); 750 751 if (so->so_options & SO_ACCEPTCONN) 752 return (EOPNOTSUPP); 753 /* 754 * If protocol is connection-based, can only connect once. 755 * Otherwise, if connected, try to disconnect first. 756 * This allows user to disconnect by connecting to, e.g., 757 * a null address. 758 */ 759 if (so->so_state & (SS_ISCONNECTED|SS_ISCONNECTING) && 760 ((so->so_proto->pr_flags & PR_CONNREQUIRED) || 761 (error = sodisconnect(so)))) 762 error = EISCONN; 763 else 764 error = (*so->so_proto->pr_usrreq)(so, PRU_CONNECT, 765 NULL, nam, NULL, l); 766 return (error); 767 } 768 769 int 770 soconnect2(struct socket *so1, struct socket *so2) 771 { 772 int error; 773 774 KASSERT(solocked2(so1, so2)); 775 776 error = (*so1->so_proto->pr_usrreq)(so1, PRU_CONNECT2, 777 NULL, (struct mbuf *)so2, NULL, NULL); 778 return (error); 779 } 780 781 int 782 sodisconnect(struct socket *so) 783 { 784 int error; 785 786 KASSERT(solocked(so)); 787 788 if ((so->so_state & SS_ISCONNECTED) == 0) { 789 error = ENOTCONN; 790 } else if (so->so_state & SS_ISDISCONNECTING) { 791 error = EALREADY; 792 } else { 793 error = (*so->so_proto->pr_usrreq)(so, PRU_DISCONNECT, 794 NULL, NULL, NULL, NULL); 795 } 796 sodopendfree(); 797 return (error); 798 } 799 800 #define SBLOCKWAIT(f) (((f) & MSG_DONTWAIT) ? M_NOWAIT : M_WAITOK) 801 /* 802 * Send on a socket. 803 * If send must go all at once and message is larger than 804 * send buffering, then hard error. 805 * Lock against other senders. 806 * If must go all at once and not enough room now, then 807 * inform user that this would block and do nothing. 808 * Otherwise, if nonblocking, send as much as possible. 809 * The data to be sent is described by "uio" if nonzero, 810 * otherwise by the mbuf chain "top" (which must be null 811 * if uio is not). Data provided in mbuf chain must be small 812 * enough to send all at once. 813 * 814 * Returns nonzero on error, timeout or signal; callers 815 * must check for short counts if EINTR/ERESTART are returned. 816 * Data and control buffers are freed on return. 817 */ 818 int 819 sosend(struct socket *so, struct mbuf *addr, struct uio *uio, struct mbuf *top, 820 struct mbuf *control, int flags, struct lwp *l) 821 { 822 struct mbuf **mp, *m; 823 struct proc *p; 824 long space, len, resid, clen, mlen; 825 int error, s, dontroute, atomic; 826 827 p = l->l_proc; 828 sodopendfree(); 829 clen = 0; 830 831 /* 832 * solock() provides atomicity of access. splsoftnet() prevents 833 * protocol processing soft interrupts from interrupting us and 834 * blocking (expensive). 835 */ 836 s = splsoftnet(); 837 solock(so); 838 atomic = sosendallatonce(so) || top; 839 if (uio) 840 resid = uio->uio_resid; 841 else 842 resid = top->m_pkthdr.len; 843 /* 844 * In theory resid should be unsigned. 845 * However, space must be signed, as it might be less than 0 846 * if we over-committed, and we must use a signed comparison 847 * of space and resid. On the other hand, a negative resid 848 * causes us to loop sending 0-length segments to the protocol. 849 */ 850 if (resid < 0) { 851 error = EINVAL; 852 goto out; 853 } 854 dontroute = 855 (flags & MSG_DONTROUTE) && (so->so_options & SO_DONTROUTE) == 0 && 856 (so->so_proto->pr_flags & PR_ATOMIC); 857 l->l_ru.ru_msgsnd++; 858 if (control) 859 clen = control->m_len; 860 restart: 861 if ((error = sblock(&so->so_snd, SBLOCKWAIT(flags))) != 0) 862 goto out; 863 do { 864 if (so->so_state & SS_CANTSENDMORE) { 865 error = EPIPE; 866 goto release; 867 } 868 if (so->so_error) { 869 error = so->so_error; 870 so->so_error = 0; 871 goto release; 872 } 873 if ((so->so_state & SS_ISCONNECTED) == 0) { 874 if (so->so_proto->pr_flags & PR_CONNREQUIRED) { 875 if ((so->so_state & SS_ISCONFIRMING) == 0 && 876 !(resid == 0 && clen != 0)) { 877 error = ENOTCONN; 878 goto release; 879 } 880 } else if (addr == 0) { 881 error = EDESTADDRREQ; 882 goto release; 883 } 884 } 885 space = sbspace(&so->so_snd); 886 if (flags & MSG_OOB) 887 space += 1024; 888 if ((atomic && resid > so->so_snd.sb_hiwat) || 889 clen > so->so_snd.sb_hiwat) { 890 error = EMSGSIZE; 891 goto release; 892 } 893 if (space < resid + clen && 894 (atomic || space < so->so_snd.sb_lowat || space < clen)) { 895 if (so->so_nbio) { 896 error = EWOULDBLOCK; 897 goto release; 898 } 899 sbunlock(&so->so_snd); 900 error = sbwait(&so->so_snd); 901 if (error) 902 goto out; 903 goto restart; 904 } 905 mp = ⊤ 906 space -= clen; 907 do { 908 if (uio == NULL) { 909 /* 910 * Data is prepackaged in "top". 911 */ 912 resid = 0; 913 if (flags & MSG_EOR) 914 top->m_flags |= M_EOR; 915 } else do { 916 sounlock(so); 917 splx(s); 918 if (top == NULL) { 919 m = m_gethdr(M_WAIT, MT_DATA); 920 mlen = MHLEN; 921 m->m_pkthdr.len = 0; 922 m->m_pkthdr.rcvif = NULL; 923 } else { 924 m = m_get(M_WAIT, MT_DATA); 925 mlen = MLEN; 926 } 927 MCLAIM(m, so->so_snd.sb_mowner); 928 if (sock_loan_thresh >= 0 && 929 uio->uio_iov->iov_len >= sock_loan_thresh && 930 space >= sock_loan_thresh && 931 (len = sosend_loan(so, uio, m, 932 space)) != 0) { 933 SOSEND_COUNTER_INCR(&sosend_loan_big); 934 space -= len; 935 goto have_data; 936 } 937 if (resid >= MINCLSIZE && space >= MCLBYTES) { 938 SOSEND_COUNTER_INCR(&sosend_copy_big); 939 m_clget(m, M_WAIT); 940 if ((m->m_flags & M_EXT) == 0) 941 goto nopages; 942 mlen = MCLBYTES; 943 if (atomic && top == 0) { 944 len = lmin(MCLBYTES - max_hdr, 945 resid); 946 m->m_data += max_hdr; 947 } else 948 len = lmin(MCLBYTES, resid); 949 space -= len; 950 } else { 951 nopages: 952 SOSEND_COUNTER_INCR(&sosend_copy_small); 953 len = lmin(lmin(mlen, resid), space); 954 space -= len; 955 /* 956 * For datagram protocols, leave room 957 * for protocol headers in first mbuf. 958 */ 959 if (atomic && top == 0 && len < mlen) 960 MH_ALIGN(m, len); 961 } 962 error = uiomove(mtod(m, void *), (int)len, uio); 963 have_data: 964 resid = uio->uio_resid; 965 m->m_len = len; 966 *mp = m; 967 top->m_pkthdr.len += len; 968 s = splsoftnet(); 969 solock(so); 970 if (error != 0) 971 goto release; 972 mp = &m->m_next; 973 if (resid <= 0) { 974 if (flags & MSG_EOR) 975 top->m_flags |= M_EOR; 976 break; 977 } 978 } while (space > 0 && atomic); 979 980 if (so->so_state & SS_CANTSENDMORE) { 981 error = EPIPE; 982 goto release; 983 } 984 if (dontroute) 985 so->so_options |= SO_DONTROUTE; 986 if (resid > 0) 987 so->so_state |= SS_MORETOCOME; 988 error = (*so->so_proto->pr_usrreq)(so, 989 (flags & MSG_OOB) ? PRU_SENDOOB : PRU_SEND, 990 top, addr, control, curlwp); 991 if (dontroute) 992 so->so_options &= ~SO_DONTROUTE; 993 if (resid > 0) 994 so->so_state &= ~SS_MORETOCOME; 995 clen = 0; 996 control = NULL; 997 top = NULL; 998 mp = ⊤ 999 if (error != 0) 1000 goto release; 1001 } while (resid && space > 0); 1002 } while (resid); 1003 1004 release: 1005 sbunlock(&so->so_snd); 1006 out: 1007 sounlock(so); 1008 splx(s); 1009 if (top) 1010 m_freem(top); 1011 if (control) 1012 m_freem(control); 1013 return (error); 1014 } 1015 1016 /* 1017 * Following replacement or removal of the first mbuf on the first 1018 * mbuf chain of a socket buffer, push necessary state changes back 1019 * into the socket buffer so that other consumers see the values 1020 * consistently. 'nextrecord' is the callers locally stored value of 1021 * the original value of sb->sb_mb->m_nextpkt which must be restored 1022 * when the lead mbuf changes. NOTE: 'nextrecord' may be NULL. 1023 */ 1024 static void 1025 sbsync(struct sockbuf *sb, struct mbuf *nextrecord) 1026 { 1027 1028 KASSERT(solocked(sb->sb_so)); 1029 1030 /* 1031 * First, update for the new value of nextrecord. If necessary, 1032 * make it the first record. 1033 */ 1034 if (sb->sb_mb != NULL) 1035 sb->sb_mb->m_nextpkt = nextrecord; 1036 else 1037 sb->sb_mb = nextrecord; 1038 1039 /* 1040 * Now update any dependent socket buffer fields to reflect 1041 * the new state. This is an inline of SB_EMPTY_FIXUP, with 1042 * the addition of a second clause that takes care of the 1043 * case where sb_mb has been updated, but remains the last 1044 * record. 1045 */ 1046 if (sb->sb_mb == NULL) { 1047 sb->sb_mbtail = NULL; 1048 sb->sb_lastrecord = NULL; 1049 } else if (sb->sb_mb->m_nextpkt == NULL) 1050 sb->sb_lastrecord = sb->sb_mb; 1051 } 1052 1053 /* 1054 * Implement receive operations on a socket. 1055 * We depend on the way that records are added to the sockbuf 1056 * by sbappend*. In particular, each record (mbufs linked through m_next) 1057 * must begin with an address if the protocol so specifies, 1058 * followed by an optional mbuf or mbufs containing ancillary data, 1059 * and then zero or more mbufs of data. 1060 * In order to avoid blocking network interrupts for the entire time here, 1061 * we splx() while doing the actual copy to user space. 1062 * Although the sockbuf is locked, new data may still be appended, 1063 * and thus we must maintain consistency of the sockbuf during that time. 1064 * 1065 * The caller may receive the data as a single mbuf chain by supplying 1066 * an mbuf **mp0 for use in returning the chain. The uio is then used 1067 * only for the count in uio_resid. 1068 */ 1069 int 1070 soreceive(struct socket *so, struct mbuf **paddr, struct uio *uio, 1071 struct mbuf **mp0, struct mbuf **controlp, int *flagsp) 1072 { 1073 struct lwp *l = curlwp; 1074 struct mbuf *m, **mp, *mt; 1075 int atomic, flags, len, error, s, offset, moff, type, orig_resid; 1076 const struct protosw *pr; 1077 struct mbuf *nextrecord; 1078 int mbuf_removed = 0; 1079 const struct domain *dom; 1080 1081 pr = so->so_proto; 1082 atomic = pr->pr_flags & PR_ATOMIC; 1083 dom = pr->pr_domain; 1084 mp = mp0; 1085 type = 0; 1086 orig_resid = uio->uio_resid; 1087 1088 if (paddr != NULL) 1089 *paddr = NULL; 1090 if (controlp != NULL) 1091 *controlp = NULL; 1092 if (flagsp != NULL) 1093 flags = *flagsp &~ MSG_EOR; 1094 else 1095 flags = 0; 1096 1097 if ((flags & MSG_DONTWAIT) == 0) 1098 sodopendfree(); 1099 1100 if (flags & MSG_OOB) { 1101 m = m_get(M_WAIT, MT_DATA); 1102 solock(so); 1103 error = (*pr->pr_usrreq)(so, PRU_RCVOOB, m, 1104 (struct mbuf *)(long)(flags & MSG_PEEK), NULL, l); 1105 sounlock(so); 1106 if (error) 1107 goto bad; 1108 do { 1109 error = uiomove(mtod(m, void *), 1110 (int) min(uio->uio_resid, m->m_len), uio); 1111 m = m_free(m); 1112 } while (uio->uio_resid > 0 && error == 0 && m); 1113 bad: 1114 if (m != NULL) 1115 m_freem(m); 1116 return error; 1117 } 1118 if (mp != NULL) 1119 *mp = NULL; 1120 1121 /* 1122 * solock() provides atomicity of access. splsoftnet() prevents 1123 * protocol processing soft interrupts from interrupting us and 1124 * blocking (expensive). 1125 */ 1126 s = splsoftnet(); 1127 solock(so); 1128 if (so->so_state & SS_ISCONFIRMING && uio->uio_resid) 1129 (*pr->pr_usrreq)(so, PRU_RCVD, NULL, NULL, NULL, l); 1130 1131 restart: 1132 if ((error = sblock(&so->so_rcv, SBLOCKWAIT(flags))) != 0) { 1133 sounlock(so); 1134 splx(s); 1135 return error; 1136 } 1137 1138 m = so->so_rcv.sb_mb; 1139 /* 1140 * If we have less data than requested, block awaiting more 1141 * (subject to any timeout) if: 1142 * 1. the current count is less than the low water mark, 1143 * 2. MSG_WAITALL is set, and it is possible to do the entire 1144 * receive operation at once if we block (resid <= hiwat), or 1145 * 3. MSG_DONTWAIT is not set. 1146 * If MSG_WAITALL is set but resid is larger than the receive buffer, 1147 * we have to do the receive in sections, and thus risk returning 1148 * a short count if a timeout or signal occurs after we start. 1149 */ 1150 if (m == NULL || 1151 ((flags & MSG_DONTWAIT) == 0 && 1152 so->so_rcv.sb_cc < uio->uio_resid && 1153 (so->so_rcv.sb_cc < so->so_rcv.sb_lowat || 1154 ((flags & MSG_WAITALL) && 1155 uio->uio_resid <= so->so_rcv.sb_hiwat)) && 1156 m->m_nextpkt == NULL && !atomic)) { 1157 #ifdef DIAGNOSTIC 1158 if (m == NULL && so->so_rcv.sb_cc) 1159 panic("receive 1"); 1160 #endif 1161 if (so->so_error) { 1162 if (m != NULL) 1163 goto dontblock; 1164 error = so->so_error; 1165 if ((flags & MSG_PEEK) == 0) 1166 so->so_error = 0; 1167 goto release; 1168 } 1169 if (so->so_state & SS_CANTRCVMORE) { 1170 if (m != NULL) 1171 goto dontblock; 1172 else 1173 goto release; 1174 } 1175 for (; m != NULL; m = m->m_next) 1176 if (m->m_type == MT_OOBDATA || (m->m_flags & M_EOR)) { 1177 m = so->so_rcv.sb_mb; 1178 goto dontblock; 1179 } 1180 if ((so->so_state & (SS_ISCONNECTED|SS_ISCONNECTING)) == 0 && 1181 (so->so_proto->pr_flags & PR_CONNREQUIRED)) { 1182 error = ENOTCONN; 1183 goto release; 1184 } 1185 if (uio->uio_resid == 0) 1186 goto release; 1187 if (so->so_nbio || (flags & MSG_DONTWAIT)) { 1188 error = EWOULDBLOCK; 1189 goto release; 1190 } 1191 SBLASTRECORDCHK(&so->so_rcv, "soreceive sbwait 1"); 1192 SBLASTMBUFCHK(&so->so_rcv, "soreceive sbwait 1"); 1193 sbunlock(&so->so_rcv); 1194 error = sbwait(&so->so_rcv); 1195 if (error != 0) { 1196 sounlock(so); 1197 splx(s); 1198 return error; 1199 } 1200 goto restart; 1201 } 1202 dontblock: 1203 /* 1204 * On entry here, m points to the first record of the socket buffer. 1205 * From this point onward, we maintain 'nextrecord' as a cache of the 1206 * pointer to the next record in the socket buffer. We must keep the 1207 * various socket buffer pointers and local stack versions of the 1208 * pointers in sync, pushing out modifications before dropping the 1209 * socket lock, and re-reading them when picking it up. 1210 * 1211 * Otherwise, we will race with the network stack appending new data 1212 * or records onto the socket buffer by using inconsistent/stale 1213 * versions of the field, possibly resulting in socket buffer 1214 * corruption. 1215 * 1216 * By holding the high-level sblock(), we prevent simultaneous 1217 * readers from pulling off the front of the socket buffer. 1218 */ 1219 if (l != NULL) 1220 l->l_ru.ru_msgrcv++; 1221 KASSERT(m == so->so_rcv.sb_mb); 1222 SBLASTRECORDCHK(&so->so_rcv, "soreceive 1"); 1223 SBLASTMBUFCHK(&so->so_rcv, "soreceive 1"); 1224 nextrecord = m->m_nextpkt; 1225 if (pr->pr_flags & PR_ADDR) { 1226 #ifdef DIAGNOSTIC 1227 if (m->m_type != MT_SONAME) 1228 panic("receive 1a"); 1229 #endif 1230 orig_resid = 0; 1231 if (flags & MSG_PEEK) { 1232 if (paddr) 1233 *paddr = m_copy(m, 0, m->m_len); 1234 m = m->m_next; 1235 } else { 1236 sbfree(&so->so_rcv, m); 1237 mbuf_removed = 1; 1238 if (paddr != NULL) { 1239 *paddr = m; 1240 so->so_rcv.sb_mb = m->m_next; 1241 m->m_next = NULL; 1242 m = so->so_rcv.sb_mb; 1243 } else { 1244 MFREE(m, so->so_rcv.sb_mb); 1245 m = so->so_rcv.sb_mb; 1246 } 1247 sbsync(&so->so_rcv, nextrecord); 1248 } 1249 } 1250 1251 /* 1252 * Process one or more MT_CONTROL mbufs present before any data mbufs 1253 * in the first mbuf chain on the socket buffer. If MSG_PEEK, we 1254 * just copy the data; if !MSG_PEEK, we call into the protocol to 1255 * perform externalization (or freeing if controlp == NULL). 1256 */ 1257 if (__predict_false(m != NULL && m->m_type == MT_CONTROL)) { 1258 struct mbuf *cm = NULL, *cmn; 1259 struct mbuf **cme = &cm; 1260 1261 do { 1262 if (flags & MSG_PEEK) { 1263 if (controlp != NULL) { 1264 *controlp = m_copy(m, 0, m->m_len); 1265 controlp = &(*controlp)->m_next; 1266 } 1267 m = m->m_next; 1268 } else { 1269 sbfree(&so->so_rcv, m); 1270 so->so_rcv.sb_mb = m->m_next; 1271 m->m_next = NULL; 1272 *cme = m; 1273 cme = &(*cme)->m_next; 1274 m = so->so_rcv.sb_mb; 1275 } 1276 } while (m != NULL && m->m_type == MT_CONTROL); 1277 if ((flags & MSG_PEEK) == 0) 1278 sbsync(&so->so_rcv, nextrecord); 1279 for (; cm != NULL; cm = cmn) { 1280 cmn = cm->m_next; 1281 cm->m_next = NULL; 1282 type = mtod(cm, struct cmsghdr *)->cmsg_type; 1283 if (controlp != NULL) { 1284 if (dom->dom_externalize != NULL && 1285 type == SCM_RIGHTS) { 1286 sounlock(so); 1287 splx(s); 1288 error = (*dom->dom_externalize)(cm, l); 1289 s = splsoftnet(); 1290 solock(so); 1291 } 1292 *controlp = cm; 1293 while (*controlp != NULL) 1294 controlp = &(*controlp)->m_next; 1295 } else { 1296 /* 1297 * Dispose of any SCM_RIGHTS message that went 1298 * through the read path rather than recv. 1299 */ 1300 if (dom->dom_dispose != NULL && 1301 type == SCM_RIGHTS) { 1302 sounlock(so); 1303 (*dom->dom_dispose)(cm); 1304 solock(so); 1305 } 1306 m_freem(cm); 1307 } 1308 } 1309 if (m != NULL) 1310 nextrecord = so->so_rcv.sb_mb->m_nextpkt; 1311 else 1312 nextrecord = so->so_rcv.sb_mb; 1313 orig_resid = 0; 1314 } 1315 1316 /* If m is non-NULL, we have some data to read. */ 1317 if (__predict_true(m != NULL)) { 1318 type = m->m_type; 1319 if (type == MT_OOBDATA) 1320 flags |= MSG_OOB; 1321 } 1322 SBLASTRECORDCHK(&so->so_rcv, "soreceive 2"); 1323 SBLASTMBUFCHK(&so->so_rcv, "soreceive 2"); 1324 1325 moff = 0; 1326 offset = 0; 1327 while (m != NULL && uio->uio_resid > 0 && error == 0) { 1328 if (m->m_type == MT_OOBDATA) { 1329 if (type != MT_OOBDATA) 1330 break; 1331 } else if (type == MT_OOBDATA) 1332 break; 1333 #ifdef DIAGNOSTIC 1334 else if (m->m_type != MT_DATA && m->m_type != MT_HEADER) 1335 panic("receive 3"); 1336 #endif 1337 so->so_state &= ~SS_RCVATMARK; 1338 len = uio->uio_resid; 1339 if (so->so_oobmark && len > so->so_oobmark - offset) 1340 len = so->so_oobmark - offset; 1341 if (len > m->m_len - moff) 1342 len = m->m_len - moff; 1343 /* 1344 * If mp is set, just pass back the mbufs. 1345 * Otherwise copy them out via the uio, then free. 1346 * Sockbuf must be consistent here (points to current mbuf, 1347 * it points to next record) when we drop priority; 1348 * we must note any additions to the sockbuf when we 1349 * block interrupts again. 1350 */ 1351 if (mp == NULL) { 1352 SBLASTRECORDCHK(&so->so_rcv, "soreceive uiomove"); 1353 SBLASTMBUFCHK(&so->so_rcv, "soreceive uiomove"); 1354 sounlock(so); 1355 splx(s); 1356 error = uiomove(mtod(m, char *) + moff, (int)len, uio); 1357 s = splsoftnet(); 1358 solock(so); 1359 if (error != 0) { 1360 /* 1361 * If any part of the record has been removed 1362 * (such as the MT_SONAME mbuf, which will 1363 * happen when PR_ADDR, and thus also 1364 * PR_ATOMIC, is set), then drop the entire 1365 * record to maintain the atomicity of the 1366 * receive operation. 1367 * 1368 * This avoids a later panic("receive 1a") 1369 * when compiled with DIAGNOSTIC. 1370 */ 1371 if (m && mbuf_removed && atomic) 1372 (void) sbdroprecord(&so->so_rcv); 1373 1374 goto release; 1375 } 1376 } else 1377 uio->uio_resid -= len; 1378 if (len == m->m_len - moff) { 1379 if (m->m_flags & M_EOR) 1380 flags |= MSG_EOR; 1381 if (flags & MSG_PEEK) { 1382 m = m->m_next; 1383 moff = 0; 1384 } else { 1385 nextrecord = m->m_nextpkt; 1386 sbfree(&so->so_rcv, m); 1387 if (mp) { 1388 *mp = m; 1389 mp = &m->m_next; 1390 so->so_rcv.sb_mb = m = m->m_next; 1391 *mp = NULL; 1392 } else { 1393 MFREE(m, so->so_rcv.sb_mb); 1394 m = so->so_rcv.sb_mb; 1395 } 1396 /* 1397 * If m != NULL, we also know that 1398 * so->so_rcv.sb_mb != NULL. 1399 */ 1400 KASSERT(so->so_rcv.sb_mb == m); 1401 if (m) { 1402 m->m_nextpkt = nextrecord; 1403 if (nextrecord == NULL) 1404 so->so_rcv.sb_lastrecord = m; 1405 } else { 1406 so->so_rcv.sb_mb = nextrecord; 1407 SB_EMPTY_FIXUP(&so->so_rcv); 1408 } 1409 SBLASTRECORDCHK(&so->so_rcv, "soreceive 3"); 1410 SBLASTMBUFCHK(&so->so_rcv, "soreceive 3"); 1411 } 1412 } else if (flags & MSG_PEEK) 1413 moff += len; 1414 else { 1415 if (mp != NULL) { 1416 mt = m_copym(m, 0, len, M_NOWAIT); 1417 if (__predict_false(mt == NULL)) { 1418 sounlock(so); 1419 mt = m_copym(m, 0, len, M_WAIT); 1420 solock(so); 1421 } 1422 *mp = mt; 1423 } 1424 m->m_data += len; 1425 m->m_len -= len; 1426 so->so_rcv.sb_cc -= len; 1427 } 1428 if (so->so_oobmark) { 1429 if ((flags & MSG_PEEK) == 0) { 1430 so->so_oobmark -= len; 1431 if (so->so_oobmark == 0) { 1432 so->so_state |= SS_RCVATMARK; 1433 break; 1434 } 1435 } else { 1436 offset += len; 1437 if (offset == so->so_oobmark) 1438 break; 1439 } 1440 } 1441 if (flags & MSG_EOR) 1442 break; 1443 /* 1444 * If the MSG_WAITALL flag is set (for non-atomic socket), 1445 * we must not quit until "uio->uio_resid == 0" or an error 1446 * termination. If a signal/timeout occurs, return 1447 * with a short count but without error. 1448 * Keep sockbuf locked against other readers. 1449 */ 1450 while (flags & MSG_WAITALL && m == NULL && uio->uio_resid > 0 && 1451 !sosendallatonce(so) && !nextrecord) { 1452 if (so->so_error || so->so_state & SS_CANTRCVMORE) 1453 break; 1454 /* 1455 * If we are peeking and the socket receive buffer is 1456 * full, stop since we can't get more data to peek at. 1457 */ 1458 if ((flags & MSG_PEEK) && sbspace(&so->so_rcv) <= 0) 1459 break; 1460 /* 1461 * If we've drained the socket buffer, tell the 1462 * protocol in case it needs to do something to 1463 * get it filled again. 1464 */ 1465 if ((pr->pr_flags & PR_WANTRCVD) && so->so_pcb) 1466 (*pr->pr_usrreq)(so, PRU_RCVD, 1467 NULL, (struct mbuf *)(long)flags, NULL, l); 1468 SBLASTRECORDCHK(&so->so_rcv, "soreceive sbwait 2"); 1469 SBLASTMBUFCHK(&so->so_rcv, "soreceive sbwait 2"); 1470 error = sbwait(&so->so_rcv); 1471 if (error != 0) { 1472 sbunlock(&so->so_rcv); 1473 sounlock(so); 1474 splx(s); 1475 return 0; 1476 } 1477 if ((m = so->so_rcv.sb_mb) != NULL) 1478 nextrecord = m->m_nextpkt; 1479 } 1480 } 1481 1482 if (m && atomic) { 1483 flags |= MSG_TRUNC; 1484 if ((flags & MSG_PEEK) == 0) 1485 (void) sbdroprecord(&so->so_rcv); 1486 } 1487 if ((flags & MSG_PEEK) == 0) { 1488 if (m == NULL) { 1489 /* 1490 * First part is an inline SB_EMPTY_FIXUP(). Second 1491 * part makes sure sb_lastrecord is up-to-date if 1492 * there is still data in the socket buffer. 1493 */ 1494 so->so_rcv.sb_mb = nextrecord; 1495 if (so->so_rcv.sb_mb == NULL) { 1496 so->so_rcv.sb_mbtail = NULL; 1497 so->so_rcv.sb_lastrecord = NULL; 1498 } else if (nextrecord->m_nextpkt == NULL) 1499 so->so_rcv.sb_lastrecord = nextrecord; 1500 } 1501 SBLASTRECORDCHK(&so->so_rcv, "soreceive 4"); 1502 SBLASTMBUFCHK(&so->so_rcv, "soreceive 4"); 1503 if (pr->pr_flags & PR_WANTRCVD && so->so_pcb) 1504 (*pr->pr_usrreq)(so, PRU_RCVD, NULL, 1505 (struct mbuf *)(long)flags, NULL, l); 1506 } 1507 if (orig_resid == uio->uio_resid && orig_resid && 1508 (flags & MSG_EOR) == 0 && (so->so_state & SS_CANTRCVMORE) == 0) { 1509 sbunlock(&so->so_rcv); 1510 goto restart; 1511 } 1512 1513 if (flagsp != NULL) 1514 *flagsp |= flags; 1515 release: 1516 sbunlock(&so->so_rcv); 1517 sounlock(so); 1518 splx(s); 1519 return error; 1520 } 1521 1522 int 1523 soshutdown(struct socket *so, int how) 1524 { 1525 const struct protosw *pr; 1526 int error; 1527 1528 KASSERT(solocked(so)); 1529 1530 pr = so->so_proto; 1531 if (!(how == SHUT_RD || how == SHUT_WR || how == SHUT_RDWR)) 1532 return (EINVAL); 1533 1534 if (how == SHUT_RD || how == SHUT_RDWR) { 1535 sorflush(so); 1536 error = 0; 1537 } 1538 if (how == SHUT_WR || how == SHUT_RDWR) 1539 error = (*pr->pr_usrreq)(so, PRU_SHUTDOWN, NULL, 1540 NULL, NULL, NULL); 1541 1542 return error; 1543 } 1544 1545 void 1546 sorflush(struct socket *so) 1547 { 1548 struct sockbuf *sb, asb; 1549 const struct protosw *pr; 1550 1551 KASSERT(solocked(so)); 1552 1553 sb = &so->so_rcv; 1554 pr = so->so_proto; 1555 socantrcvmore(so); 1556 sb->sb_flags |= SB_NOINTR; 1557 (void )sblock(sb, M_WAITOK); 1558 sbunlock(sb); 1559 asb = *sb; 1560 /* 1561 * Clear most of the sockbuf structure, but leave some of the 1562 * fields valid. 1563 */ 1564 memset(&sb->sb_startzero, 0, 1565 sizeof(*sb) - offsetof(struct sockbuf, sb_startzero)); 1566 if (pr->pr_flags & PR_RIGHTS && pr->pr_domain->dom_dispose) { 1567 sounlock(so); 1568 (*pr->pr_domain->dom_dispose)(asb.sb_mb); 1569 solock(so); 1570 } 1571 sbrelease(&asb, so); 1572 } 1573 1574 static int 1575 sosetopt1(struct socket *so, int level, int optname, struct mbuf *m) 1576 { 1577 int optval, val; 1578 struct linger *l; 1579 struct sockbuf *sb; 1580 struct timeval *tv; 1581 1582 switch (optname) { 1583 1584 case SO_LINGER: 1585 if (m == NULL || m->m_len != sizeof(struct linger)) 1586 return EINVAL; 1587 l = mtod(m, struct linger *); 1588 if (l->l_linger < 0 || l->l_linger > USHRT_MAX || 1589 l->l_linger > (INT_MAX / hz)) 1590 return EDOM; 1591 so->so_linger = l->l_linger; 1592 if (l->l_onoff) 1593 so->so_options |= SO_LINGER; 1594 else 1595 so->so_options &= ~SO_LINGER; 1596 break; 1597 1598 case SO_DEBUG: 1599 case SO_KEEPALIVE: 1600 case SO_DONTROUTE: 1601 case SO_USELOOPBACK: 1602 case SO_BROADCAST: 1603 case SO_REUSEADDR: 1604 case SO_REUSEPORT: 1605 case SO_OOBINLINE: 1606 case SO_TIMESTAMP: 1607 if (m == NULL || m->m_len < sizeof(int)) 1608 return EINVAL; 1609 if (*mtod(m, int *)) 1610 so->so_options |= optname; 1611 else 1612 so->so_options &= ~optname; 1613 break; 1614 1615 case SO_SNDBUF: 1616 case SO_RCVBUF: 1617 case SO_SNDLOWAT: 1618 case SO_RCVLOWAT: 1619 if (m == NULL || m->m_len < sizeof(int)) 1620 return EINVAL; 1621 1622 /* 1623 * Values < 1 make no sense for any of these 1624 * options, so disallow them. 1625 */ 1626 optval = *mtod(m, int *); 1627 if (optval < 1) 1628 return EINVAL; 1629 1630 switch (optname) { 1631 1632 case SO_SNDBUF: 1633 case SO_RCVBUF: 1634 sb = (optname == SO_SNDBUF) ? 1635 &so->so_snd : &so->so_rcv; 1636 if (sbreserve(sb, (u_long)optval, so) == 0) 1637 return ENOBUFS; 1638 sb->sb_flags &= ~SB_AUTOSIZE; 1639 break; 1640 1641 /* 1642 * Make sure the low-water is never greater than 1643 * the high-water. 1644 */ 1645 case SO_SNDLOWAT: 1646 so->so_snd.sb_lowat = 1647 (optval > so->so_snd.sb_hiwat) ? 1648 so->so_snd.sb_hiwat : optval; 1649 break; 1650 case SO_RCVLOWAT: 1651 so->so_rcv.sb_lowat = 1652 (optval > so->so_rcv.sb_hiwat) ? 1653 so->so_rcv.sb_hiwat : optval; 1654 break; 1655 } 1656 break; 1657 1658 case SO_SNDTIMEO: 1659 case SO_RCVTIMEO: 1660 if (m == NULL || m->m_len < sizeof(*tv)) 1661 return EINVAL; 1662 tv = mtod(m, struct timeval *); 1663 if (tv->tv_sec > (INT_MAX - tv->tv_usec / tick) / hz) 1664 return EDOM; 1665 val = tv->tv_sec * hz + tv->tv_usec / tick; 1666 if (val == 0 && tv->tv_usec != 0) 1667 val = 1; 1668 1669 switch (optname) { 1670 1671 case SO_SNDTIMEO: 1672 so->so_snd.sb_timeo = val; 1673 break; 1674 case SO_RCVTIMEO: 1675 so->so_rcv.sb_timeo = val; 1676 break; 1677 } 1678 break; 1679 1680 default: 1681 return ENOPROTOOPT; 1682 } 1683 return 0; 1684 } 1685 1686 int 1687 sosetopt(struct socket *so, int level, int optname, struct mbuf *m) 1688 { 1689 int error, prerr; 1690 1691 solock(so); 1692 if (level == SOL_SOCKET) 1693 error = sosetopt1(so, level, optname, m); 1694 else 1695 error = ENOPROTOOPT; 1696 1697 if ((error == 0 || error == ENOPROTOOPT) && 1698 so->so_proto != NULL && so->so_proto->pr_ctloutput != NULL) { 1699 /* give the protocol stack a shot */ 1700 prerr = (*so->so_proto->pr_ctloutput)(PRCO_SETOPT, so, level, 1701 optname, &m); 1702 if (prerr == 0) 1703 error = 0; 1704 else if (prerr != ENOPROTOOPT) 1705 error = prerr; 1706 } else if (m != NULL) 1707 (void)m_free(m); 1708 sounlock(so); 1709 return error; 1710 } 1711 1712 int 1713 sogetopt(struct socket *so, int level, int optname, struct mbuf **mp) 1714 { 1715 struct mbuf *m; 1716 int error; 1717 1718 solock(so); 1719 if (level != SOL_SOCKET) { 1720 if (so->so_proto && so->so_proto->pr_ctloutput) { 1721 error = ((*so->so_proto->pr_ctloutput) 1722 (PRCO_GETOPT, so, level, optname, mp)); 1723 } else 1724 error = (ENOPROTOOPT); 1725 } else { 1726 m = m_get(M_WAIT, MT_SOOPTS); 1727 m->m_len = sizeof(int); 1728 1729 switch (optname) { 1730 1731 case SO_LINGER: 1732 m->m_len = sizeof(struct linger); 1733 mtod(m, struct linger *)->l_onoff = 1734 (so->so_options & SO_LINGER) ? 1 : 0; 1735 mtod(m, struct linger *)->l_linger = so->so_linger; 1736 break; 1737 1738 case SO_USELOOPBACK: 1739 case SO_DONTROUTE: 1740 case SO_DEBUG: 1741 case SO_KEEPALIVE: 1742 case SO_REUSEADDR: 1743 case SO_REUSEPORT: 1744 case SO_BROADCAST: 1745 case SO_OOBINLINE: 1746 case SO_TIMESTAMP: 1747 *mtod(m, int *) = (so->so_options & optname) ? 1 : 0; 1748 break; 1749 1750 case SO_TYPE: 1751 *mtod(m, int *) = so->so_type; 1752 break; 1753 1754 case SO_ERROR: 1755 *mtod(m, int *) = so->so_error; 1756 so->so_error = 0; 1757 break; 1758 1759 case SO_SNDBUF: 1760 *mtod(m, int *) = so->so_snd.sb_hiwat; 1761 break; 1762 1763 case SO_RCVBUF: 1764 *mtod(m, int *) = so->so_rcv.sb_hiwat; 1765 break; 1766 1767 case SO_SNDLOWAT: 1768 *mtod(m, int *) = so->so_snd.sb_lowat; 1769 break; 1770 1771 case SO_RCVLOWAT: 1772 *mtod(m, int *) = so->so_rcv.sb_lowat; 1773 break; 1774 1775 case SO_SNDTIMEO: 1776 case SO_RCVTIMEO: 1777 { 1778 int val = (optname == SO_SNDTIMEO ? 1779 so->so_snd.sb_timeo : so->so_rcv.sb_timeo); 1780 1781 m->m_len = sizeof(struct timeval); 1782 mtod(m, struct timeval *)->tv_sec = val / hz; 1783 mtod(m, struct timeval *)->tv_usec = 1784 (val % hz) * tick; 1785 break; 1786 } 1787 1788 case SO_OVERFLOWED: 1789 *mtod(m, int *) = so->so_rcv.sb_overflowed; 1790 break; 1791 1792 default: 1793 sounlock(so); 1794 (void)m_free(m); 1795 return (ENOPROTOOPT); 1796 } 1797 *mp = m; 1798 error = 0; 1799 } 1800 1801 sounlock(so); 1802 return (error); 1803 } 1804 1805 void 1806 sohasoutofband(struct socket *so) 1807 { 1808 1809 fownsignal(so->so_pgid, SIGURG, POLL_PRI, POLLPRI|POLLRDBAND, so); 1810 selnotify(&so->so_rcv.sb_sel, POLLPRI | POLLRDBAND, 0); 1811 } 1812 1813 static void 1814 filt_sordetach(struct knote *kn) 1815 { 1816 struct socket *so; 1817 1818 so = ((file_t *)kn->kn_obj)->f_data; 1819 solock(so); 1820 SLIST_REMOVE(&so->so_rcv.sb_sel.sel_klist, kn, knote, kn_selnext); 1821 if (SLIST_EMPTY(&so->so_rcv.sb_sel.sel_klist)) 1822 so->so_rcv.sb_flags &= ~SB_KNOTE; 1823 sounlock(so); 1824 } 1825 1826 /*ARGSUSED*/ 1827 static int 1828 filt_soread(struct knote *kn, long hint) 1829 { 1830 struct socket *so; 1831 int rv; 1832 1833 so = ((file_t *)kn->kn_obj)->f_data; 1834 if (hint != NOTE_SUBMIT) 1835 solock(so); 1836 kn->kn_data = so->so_rcv.sb_cc; 1837 if (so->so_state & SS_CANTRCVMORE) { 1838 kn->kn_flags |= EV_EOF; 1839 kn->kn_fflags = so->so_error; 1840 rv = 1; 1841 } else if (so->so_error) /* temporary udp error */ 1842 rv = 1; 1843 else if (kn->kn_sfflags & NOTE_LOWAT) 1844 rv = (kn->kn_data >= kn->kn_sdata); 1845 else 1846 rv = (kn->kn_data >= so->so_rcv.sb_lowat); 1847 if (hint != NOTE_SUBMIT) 1848 sounlock(so); 1849 return rv; 1850 } 1851 1852 static void 1853 filt_sowdetach(struct knote *kn) 1854 { 1855 struct socket *so; 1856 1857 so = ((file_t *)kn->kn_obj)->f_data; 1858 solock(so); 1859 SLIST_REMOVE(&so->so_snd.sb_sel.sel_klist, kn, knote, kn_selnext); 1860 if (SLIST_EMPTY(&so->so_snd.sb_sel.sel_klist)) 1861 so->so_snd.sb_flags &= ~SB_KNOTE; 1862 sounlock(so); 1863 } 1864 1865 /*ARGSUSED*/ 1866 static int 1867 filt_sowrite(struct knote *kn, long hint) 1868 { 1869 struct socket *so; 1870 int rv; 1871 1872 so = ((file_t *)kn->kn_obj)->f_data; 1873 if (hint != NOTE_SUBMIT) 1874 solock(so); 1875 kn->kn_data = sbspace(&so->so_snd); 1876 if (so->so_state & SS_CANTSENDMORE) { 1877 kn->kn_flags |= EV_EOF; 1878 kn->kn_fflags = so->so_error; 1879 rv = 1; 1880 } else if (so->so_error) /* temporary udp error */ 1881 rv = 1; 1882 else if (((so->so_state & SS_ISCONNECTED) == 0) && 1883 (so->so_proto->pr_flags & PR_CONNREQUIRED)) 1884 rv = 0; 1885 else if (kn->kn_sfflags & NOTE_LOWAT) 1886 rv = (kn->kn_data >= kn->kn_sdata); 1887 else 1888 rv = (kn->kn_data >= so->so_snd.sb_lowat); 1889 if (hint != NOTE_SUBMIT) 1890 sounlock(so); 1891 return rv; 1892 } 1893 1894 /*ARGSUSED*/ 1895 static int 1896 filt_solisten(struct knote *kn, long hint) 1897 { 1898 struct socket *so; 1899 int rv; 1900 1901 so = ((file_t *)kn->kn_obj)->f_data; 1902 1903 /* 1904 * Set kn_data to number of incoming connections, not 1905 * counting partial (incomplete) connections. 1906 */ 1907 if (hint != NOTE_SUBMIT) 1908 solock(so); 1909 kn->kn_data = so->so_qlen; 1910 rv = (kn->kn_data > 0); 1911 if (hint != NOTE_SUBMIT) 1912 sounlock(so); 1913 return rv; 1914 } 1915 1916 static const struct filterops solisten_filtops = 1917 { 1, NULL, filt_sordetach, filt_solisten }; 1918 static const struct filterops soread_filtops = 1919 { 1, NULL, filt_sordetach, filt_soread }; 1920 static const struct filterops sowrite_filtops = 1921 { 1, NULL, filt_sowdetach, filt_sowrite }; 1922 1923 int 1924 soo_kqfilter(struct file *fp, struct knote *kn) 1925 { 1926 struct socket *so; 1927 struct sockbuf *sb; 1928 1929 so = ((file_t *)kn->kn_obj)->f_data; 1930 solock(so); 1931 switch (kn->kn_filter) { 1932 case EVFILT_READ: 1933 if (so->so_options & SO_ACCEPTCONN) 1934 kn->kn_fop = &solisten_filtops; 1935 else 1936 kn->kn_fop = &soread_filtops; 1937 sb = &so->so_rcv; 1938 break; 1939 case EVFILT_WRITE: 1940 kn->kn_fop = &sowrite_filtops; 1941 sb = &so->so_snd; 1942 break; 1943 default: 1944 sounlock(so); 1945 return (EINVAL); 1946 } 1947 SLIST_INSERT_HEAD(&sb->sb_sel.sel_klist, kn, kn_selnext); 1948 sb->sb_flags |= SB_KNOTE; 1949 sounlock(so); 1950 return (0); 1951 } 1952 1953 static int 1954 sodopoll(struct socket *so, int events) 1955 { 1956 int revents; 1957 1958 revents = 0; 1959 1960 if (events & (POLLIN | POLLRDNORM)) 1961 if (soreadable(so)) 1962 revents |= events & (POLLIN | POLLRDNORM); 1963 1964 if (events & (POLLOUT | POLLWRNORM)) 1965 if (sowritable(so)) 1966 revents |= events & (POLLOUT | POLLWRNORM); 1967 1968 if (events & (POLLPRI | POLLRDBAND)) 1969 if (so->so_oobmark || (so->so_state & SS_RCVATMARK)) 1970 revents |= events & (POLLPRI | POLLRDBAND); 1971 1972 return revents; 1973 } 1974 1975 int 1976 sopoll(struct socket *so, int events) 1977 { 1978 int revents = 0; 1979 1980 #ifndef DIAGNOSTIC 1981 /* 1982 * Do a quick, unlocked check in expectation that the socket 1983 * will be ready for I/O. Don't do this check if DIAGNOSTIC, 1984 * as the solocked() assertions will fail. 1985 */ 1986 if ((revents = sodopoll(so, events)) != 0) 1987 return revents; 1988 #endif 1989 1990 solock(so); 1991 if ((revents = sodopoll(so, events)) == 0) { 1992 if (events & (POLLIN | POLLPRI | POLLRDNORM | POLLRDBAND)) { 1993 selrecord(curlwp, &so->so_rcv.sb_sel); 1994 so->so_rcv.sb_flags |= SB_NOTIFY; 1995 } 1996 1997 if (events & (POLLOUT | POLLWRNORM)) { 1998 selrecord(curlwp, &so->so_snd.sb_sel); 1999 so->so_snd.sb_flags |= SB_NOTIFY; 2000 } 2001 } 2002 sounlock(so); 2003 2004 return revents; 2005 } 2006 2007 2008 #include <sys/sysctl.h> 2009 2010 static int sysctl_kern_somaxkva(SYSCTLFN_PROTO); 2011 2012 /* 2013 * sysctl helper routine for kern.somaxkva. ensures that the given 2014 * value is not too small. 2015 * (XXX should we maybe make sure it's not too large as well?) 2016 */ 2017 static int 2018 sysctl_kern_somaxkva(SYSCTLFN_ARGS) 2019 { 2020 int error, new_somaxkva; 2021 struct sysctlnode node; 2022 2023 new_somaxkva = somaxkva; 2024 node = *rnode; 2025 node.sysctl_data = &new_somaxkva; 2026 error = sysctl_lookup(SYSCTLFN_CALL(&node)); 2027 if (error || newp == NULL) 2028 return (error); 2029 2030 if (new_somaxkva < (16 * 1024 * 1024)) /* sanity */ 2031 return (EINVAL); 2032 2033 mutex_enter(&so_pendfree_lock); 2034 somaxkva = new_somaxkva; 2035 cv_broadcast(&socurkva_cv); 2036 mutex_exit(&so_pendfree_lock); 2037 2038 return (error); 2039 } 2040 2041 SYSCTL_SETUP(sysctl_kern_somaxkva_setup, "sysctl kern.somaxkva setup") 2042 { 2043 2044 sysctl_createv(clog, 0, NULL, NULL, 2045 CTLFLAG_PERMANENT, 2046 CTLTYPE_NODE, "kern", NULL, 2047 NULL, 0, NULL, 0, 2048 CTL_KERN, CTL_EOL); 2049 2050 sysctl_createv(clog, 0, NULL, NULL, 2051 CTLFLAG_PERMANENT|CTLFLAG_READWRITE, 2052 CTLTYPE_INT, "somaxkva", 2053 SYSCTL_DESCR("Maximum amount of kernel memory to be " 2054 "used for socket buffers"), 2055 sysctl_kern_somaxkva, 0, NULL, 0, 2056 CTL_KERN, KERN_SOMAXKVA, CTL_EOL); 2057 } 2058