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