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