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