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