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