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