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