Home | History | Annotate | Line # | Download | only in kern
uipc_socket.c revision 1.161
      1 /*	$NetBSD: uipc_socket.c,v 1.161 2008/04/27 14:26:58 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.161 2008/04/27 14:26:58 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 	u_int refs;
    598 
    599 	KASSERT(solocked(so));
    600 
    601 	if (so->so_pcb || (so->so_state & SS_NOFDREF) == 0) {
    602 		sounlock(so);
    603 		return;
    604 	}
    605 	if (so->so_head) {
    606 		/*
    607 		 * We must not decommission a socket that's on the accept(2)
    608 		 * queue.  If we do, then accept(2) may hang after select(2)
    609 		 * indicated that the listening socket was ready.
    610 		 */
    611 		if (!soqremque(so, 0)) {
    612 			sounlock(so);
    613 			return;
    614 		}
    615 	}
    616 	if (so->so_rcv.sb_hiwat)
    617 		(void)chgsbsize(so->so_uidinfo, &so->so_rcv.sb_hiwat, 0,
    618 		    RLIM_INFINITY);
    619 	if (so->so_snd.sb_hiwat)
    620 		(void)chgsbsize(so->so_uidinfo, &so->so_snd.sb_hiwat, 0,
    621 		    RLIM_INFINITY);
    622 	sbrelease(&so->so_snd, so);
    623 	KASSERT(!cv_has_waiters(&so->so_cv));
    624 	KASSERT(!cv_has_waiters(&so->so_rcv.sb_cv));
    625 	KASSERT(!cv_has_waiters(&so->so_snd.sb_cv));
    626 	sorflush(so);
    627 	refs = so->so_aborting;	/* XXX */
    628 	sounlock(so);
    629 	if (refs == 0)		/* XXX */
    630 		soput(so);
    631 }
    632 
    633 /*
    634  * Close a socket on last file table reference removal.
    635  * Initiate disconnect if connected.
    636  * Free socket when disconnect complete.
    637  */
    638 int
    639 soclose(struct socket *so)
    640 {
    641 	struct socket	*so2;
    642 	int		error;
    643 	int		error2;
    644 
    645 	error = 0;
    646 	solock(so);
    647 	if (so->so_options & SO_ACCEPTCONN) {
    648 		do {
    649 			if ((so2 = TAILQ_FIRST(&so->so_q0)) != 0) {
    650 				KASSERT(solocked2(so, so2));
    651 				(void) soqremque(so2, 0);
    652 				/* soabort drops the lock. */
    653 				(void) soabort(so2);
    654 				solock(so);
    655 				continue;
    656 			}
    657 			if ((so2 = TAILQ_FIRST(&so->so_q)) != 0) {
    658 				KASSERT(solocked2(so, so2));
    659 				(void) soqremque(so2, 1);
    660 				/* soabort drops the lock. */
    661 				(void) soabort(so2);
    662 				solock(so);
    663 				continue;
    664 			}
    665 		} while (0);
    666 	}
    667 	if (so->so_pcb == 0)
    668 		goto discard;
    669 	if (so->so_state & SS_ISCONNECTED) {
    670 		if ((so->so_state & SS_ISDISCONNECTING) == 0) {
    671 			error = sodisconnect(so);
    672 			if (error)
    673 				goto drop;
    674 		}
    675 		if (so->so_options & SO_LINGER) {
    676 			if ((so->so_state & SS_ISDISCONNECTING) && so->so_nbio)
    677 				goto drop;
    678 			while (so->so_state & SS_ISCONNECTED) {
    679 				error = sowait(so, so->so_linger * hz);
    680 				if (error)
    681 					break;
    682 			}
    683 		}
    684 	}
    685  drop:
    686 	if (so->so_pcb) {
    687 		error2 = (*so->so_proto->pr_usrreq)(so, PRU_DETACH,
    688 		    NULL, NULL, NULL, NULL);
    689 		if (error == 0)
    690 			error = error2;
    691 	}
    692  discard:
    693 	if (so->so_state & SS_NOFDREF)
    694 		panic("soclose: NOFDREF");
    695 	so->so_state |= SS_NOFDREF;
    696 	sofree(so);
    697 	return (error);
    698 }
    699 
    700 /*
    701  * Must be called with the socket locked..  Will return with it unlocked.
    702  */
    703 int
    704 soabort(struct socket *so)
    705 {
    706 	u_int refs;
    707 	int error;
    708 
    709 	KASSERT(solocked(so));
    710 	KASSERT(so->so_head == NULL);
    711 
    712 	so->so_aborting++;		/* XXX */
    713 	error = (*so->so_proto->pr_usrreq)(so, PRU_ABORT, NULL,
    714 	    NULL, NULL, NULL);
    715 	refs = --so->so_aborting;	/* XXX */
    716 	if (error) {
    717 		sofree(so);
    718 	} else {
    719 		sounlock(so);
    720 		if (refs == 0)
    721 			sofree(so);
    722 	}
    723 	return error;
    724 }
    725 
    726 int
    727 soaccept(struct socket *so, struct mbuf *nam)
    728 {
    729 	int	error;
    730 
    731 	KASSERT(solocked(so));
    732 
    733 	error = 0;
    734 	if ((so->so_state & SS_NOFDREF) == 0)
    735 		panic("soaccept: !NOFDREF");
    736 	so->so_state &= ~SS_NOFDREF;
    737 	if ((so->so_state & SS_ISDISCONNECTED) == 0 ||
    738 	    (so->so_proto->pr_flags & PR_ABRTACPTDIS) == 0)
    739 		error = (*so->so_proto->pr_usrreq)(so, PRU_ACCEPT,
    740 		    NULL, nam, NULL, NULL);
    741 	else
    742 		error = ECONNABORTED;
    743 
    744 	return (error);
    745 }
    746 
    747 int
    748 soconnect(struct socket *so, struct mbuf *nam, struct lwp *l)
    749 {
    750 	int		error;
    751 
    752 	KASSERT(solocked(so));
    753 
    754 	if (so->so_options & SO_ACCEPTCONN)
    755 		return (EOPNOTSUPP);
    756 	/*
    757 	 * If protocol is connection-based, can only connect once.
    758 	 * Otherwise, if connected, try to disconnect first.
    759 	 * This allows user to disconnect by connecting to, e.g.,
    760 	 * a null address.
    761 	 */
    762 	if (so->so_state & (SS_ISCONNECTED|SS_ISCONNECTING) &&
    763 	    ((so->so_proto->pr_flags & PR_CONNREQUIRED) ||
    764 	    (error = sodisconnect(so))))
    765 		error = EISCONN;
    766 	else
    767 		error = (*so->so_proto->pr_usrreq)(so, PRU_CONNECT,
    768 		    NULL, nam, NULL, l);
    769 	return (error);
    770 }
    771 
    772 int
    773 soconnect2(struct socket *so1, struct socket *so2)
    774 {
    775 	int	error;
    776 
    777 	KASSERT(solocked2(so1, so2));
    778 
    779 	error = (*so1->so_proto->pr_usrreq)(so1, PRU_CONNECT2,
    780 	    NULL, (struct mbuf *)so2, NULL, NULL);
    781 	return (error);
    782 }
    783 
    784 int
    785 sodisconnect(struct socket *so)
    786 {
    787 	int	error;
    788 
    789 	KASSERT(solocked(so));
    790 
    791 	if ((so->so_state & SS_ISCONNECTED) == 0) {
    792 		error = ENOTCONN;
    793 	} else if (so->so_state & SS_ISDISCONNECTING) {
    794 		error = EALREADY;
    795 	} else {
    796 		error = (*so->so_proto->pr_usrreq)(so, PRU_DISCONNECT,
    797 		    NULL, NULL, NULL, NULL);
    798 	}
    799 	sodopendfree();
    800 	return (error);
    801 }
    802 
    803 #define	SBLOCKWAIT(f)	(((f) & MSG_DONTWAIT) ? M_NOWAIT : M_WAITOK)
    804 /*
    805  * Send on a socket.
    806  * If send must go all at once and message is larger than
    807  * send buffering, then hard error.
    808  * Lock against other senders.
    809  * If must go all at once and not enough room now, then
    810  * inform user that this would block and do nothing.
    811  * Otherwise, if nonblocking, send as much as possible.
    812  * The data to be sent is described by "uio" if nonzero,
    813  * otherwise by the mbuf chain "top" (which must be null
    814  * if uio is not).  Data provided in mbuf chain must be small
    815  * enough to send all at once.
    816  *
    817  * Returns nonzero on error, timeout or signal; callers
    818  * must check for short counts if EINTR/ERESTART are returned.
    819  * Data and control buffers are freed on return.
    820  */
    821 int
    822 sosend(struct socket *so, struct mbuf *addr, struct uio *uio, struct mbuf *top,
    823 	struct mbuf *control, int flags, struct lwp *l)
    824 {
    825 	struct mbuf	**mp, *m;
    826 	struct proc	*p;
    827 	long		space, len, resid, clen, mlen;
    828 	int		error, s, dontroute, atomic;
    829 
    830 	p = l->l_proc;
    831 	sodopendfree();
    832 	clen = 0;
    833 
    834 	/*
    835 	 * solock() provides atomicity of access.  splsoftnet() prevents
    836 	 * protocol processing soft interrupts from interrupting us and
    837 	 * blocking (expensive).
    838 	 */
    839 	s = splsoftnet();
    840 	solock(so);
    841 	atomic = sosendallatonce(so) || top;
    842 	if (uio)
    843 		resid = uio->uio_resid;
    844 	else
    845 		resid = top->m_pkthdr.len;
    846 	/*
    847 	 * In theory resid should be unsigned.
    848 	 * However, space must be signed, as it might be less than 0
    849 	 * if we over-committed, and we must use a signed comparison
    850 	 * of space and resid.  On the other hand, a negative resid
    851 	 * causes us to loop sending 0-length segments to the protocol.
    852 	 */
    853 	if (resid < 0) {
    854 		error = EINVAL;
    855 		goto out;
    856 	}
    857 	dontroute =
    858 	    (flags & MSG_DONTROUTE) && (so->so_options & SO_DONTROUTE) == 0 &&
    859 	    (so->so_proto->pr_flags & PR_ATOMIC);
    860 	if (l)
    861 		l->l_ru.ru_msgsnd++;
    862 	if (control)
    863 		clen = control->m_len;
    864  restart:
    865 	if ((error = sblock(&so->so_snd, SBLOCKWAIT(flags))) != 0)
    866 		goto out;
    867 	do {
    868 		if (so->so_state & SS_CANTSENDMORE) {
    869 			error = EPIPE;
    870 			goto release;
    871 		}
    872 		if (so->so_error) {
    873 			error = so->so_error;
    874 			so->so_error = 0;
    875 			goto release;
    876 		}
    877 		if ((so->so_state & SS_ISCONNECTED) == 0) {
    878 			if (so->so_proto->pr_flags & PR_CONNREQUIRED) {
    879 				if ((so->so_state & SS_ISCONFIRMING) == 0 &&
    880 				    !(resid == 0 && clen != 0)) {
    881 					error = ENOTCONN;
    882 					goto release;
    883 				}
    884 			} else if (addr == 0) {
    885 				error = EDESTADDRREQ;
    886 				goto release;
    887 			}
    888 		}
    889 		space = sbspace(&so->so_snd);
    890 		if (flags & MSG_OOB)
    891 			space += 1024;
    892 		if ((atomic && resid > so->so_snd.sb_hiwat) ||
    893 		    clen > so->so_snd.sb_hiwat) {
    894 			error = EMSGSIZE;
    895 			goto release;
    896 		}
    897 		if (space < resid + clen &&
    898 		    (atomic || space < so->so_snd.sb_lowat || space < clen)) {
    899 			if (so->so_nbio) {
    900 				error = EWOULDBLOCK;
    901 				goto release;
    902 			}
    903 			sbunlock(&so->so_snd);
    904 			error = sbwait(&so->so_snd);
    905 			if (error)
    906 				goto out;
    907 			goto restart;
    908 		}
    909 		mp = &top;
    910 		space -= clen;
    911 		do {
    912 			if (uio == NULL) {
    913 				/*
    914 				 * Data is prepackaged in "top".
    915 				 */
    916 				resid = 0;
    917 				if (flags & MSG_EOR)
    918 					top->m_flags |= M_EOR;
    919 			} else do {
    920 				sounlock(so);
    921 				splx(s);
    922 				if (top == NULL) {
    923 					m = m_gethdr(M_WAIT, MT_DATA);
    924 					mlen = MHLEN;
    925 					m->m_pkthdr.len = 0;
    926 					m->m_pkthdr.rcvif = NULL;
    927 				} else {
    928 					m = m_get(M_WAIT, MT_DATA);
    929 					mlen = MLEN;
    930 				}
    931 				MCLAIM(m, so->so_snd.sb_mowner);
    932 				if (sock_loan_thresh >= 0 &&
    933 				    uio->uio_iov->iov_len >= sock_loan_thresh &&
    934 				    space >= sock_loan_thresh &&
    935 				    (len = sosend_loan(so, uio, m,
    936 						       space)) != 0) {
    937 					SOSEND_COUNTER_INCR(&sosend_loan_big);
    938 					space -= len;
    939 					goto have_data;
    940 				}
    941 				if (resid >= MINCLSIZE && space >= MCLBYTES) {
    942 					SOSEND_COUNTER_INCR(&sosend_copy_big);
    943 					m_clget(m, M_WAIT);
    944 					if ((m->m_flags & M_EXT) == 0)
    945 						goto nopages;
    946 					mlen = MCLBYTES;
    947 					if (atomic && top == 0) {
    948 						len = lmin(MCLBYTES - max_hdr,
    949 						    resid);
    950 						m->m_data += max_hdr;
    951 					} else
    952 						len = lmin(MCLBYTES, resid);
    953 					space -= len;
    954 				} else {
    955  nopages:
    956 					SOSEND_COUNTER_INCR(&sosend_copy_small);
    957 					len = lmin(lmin(mlen, resid), space);
    958 					space -= len;
    959 					/*
    960 					 * For datagram protocols, leave room
    961 					 * for protocol headers in first mbuf.
    962 					 */
    963 					if (atomic && top == 0 && len < mlen)
    964 						MH_ALIGN(m, len);
    965 				}
    966 				error = uiomove(mtod(m, void *), (int)len, uio);
    967  have_data:
    968 				resid = uio->uio_resid;
    969 				m->m_len = len;
    970 				*mp = m;
    971 				top->m_pkthdr.len += len;
    972 				s = splsoftnet();
    973 				solock(so);
    974 				if (error != 0)
    975 					goto release;
    976 				mp = &m->m_next;
    977 				if (resid <= 0) {
    978 					if (flags & MSG_EOR)
    979 						top->m_flags |= M_EOR;
    980 					break;
    981 				}
    982 			} while (space > 0 && atomic);
    983 
    984 			if (so->so_state & SS_CANTSENDMORE) {
    985 				error = EPIPE;
    986 				goto release;
    987 			}
    988 			if (dontroute)
    989 				so->so_options |= SO_DONTROUTE;
    990 			if (resid > 0)
    991 				so->so_state |= SS_MORETOCOME;
    992 			error = (*so->so_proto->pr_usrreq)(so,
    993 			    (flags & MSG_OOB) ? PRU_SENDOOB : PRU_SEND,
    994 			    top, addr, control, curlwp);
    995 			if (dontroute)
    996 				so->so_options &= ~SO_DONTROUTE;
    997 			if (resid > 0)
    998 				so->so_state &= ~SS_MORETOCOME;
    999 			clen = 0;
   1000 			control = NULL;
   1001 			top = NULL;
   1002 			mp = &top;
   1003 			if (error != 0)
   1004 				goto release;
   1005 		} while (resid && space > 0);
   1006 	} while (resid);
   1007 
   1008  release:
   1009 	sbunlock(&so->so_snd);
   1010  out:
   1011 	sounlock(so);
   1012 	splx(s);
   1013 	if (top)
   1014 		m_freem(top);
   1015 	if (control)
   1016 		m_freem(control);
   1017 	return (error);
   1018 }
   1019 
   1020 /*
   1021  * Following replacement or removal of the first mbuf on the first
   1022  * mbuf chain of a socket buffer, push necessary state changes back
   1023  * into the socket buffer so that other consumers see the values
   1024  * consistently.  'nextrecord' is the callers locally stored value of
   1025  * the original value of sb->sb_mb->m_nextpkt which must be restored
   1026  * when the lead mbuf changes.  NOTE: 'nextrecord' may be NULL.
   1027  */
   1028 static void
   1029 sbsync(struct sockbuf *sb, struct mbuf *nextrecord)
   1030 {
   1031 
   1032 	KASSERT(solocked(sb->sb_so));
   1033 
   1034 	/*
   1035 	 * First, update for the new value of nextrecord.  If necessary,
   1036 	 * make it the first record.
   1037 	 */
   1038 	if (sb->sb_mb != NULL)
   1039 		sb->sb_mb->m_nextpkt = nextrecord;
   1040 	else
   1041 		sb->sb_mb = nextrecord;
   1042 
   1043         /*
   1044          * Now update any dependent socket buffer fields to reflect
   1045          * the new state.  This is an inline of SB_EMPTY_FIXUP, with
   1046          * the addition of a second clause that takes care of the
   1047          * case where sb_mb has been updated, but remains the last
   1048          * record.
   1049          */
   1050         if (sb->sb_mb == NULL) {
   1051                 sb->sb_mbtail = NULL;
   1052                 sb->sb_lastrecord = NULL;
   1053         } else if (sb->sb_mb->m_nextpkt == NULL)
   1054                 sb->sb_lastrecord = sb->sb_mb;
   1055 }
   1056 
   1057 /*
   1058  * Implement receive operations on a socket.
   1059  * We depend on the way that records are added to the sockbuf
   1060  * by sbappend*.  In particular, each record (mbufs linked through m_next)
   1061  * must begin with an address if the protocol so specifies,
   1062  * followed by an optional mbuf or mbufs containing ancillary data,
   1063  * and then zero or more mbufs of data.
   1064  * In order to avoid blocking network interrupts for the entire time here,
   1065  * we splx() while doing the actual copy to user space.
   1066  * Although the sockbuf is locked, new data may still be appended,
   1067  * and thus we must maintain consistency of the sockbuf during that time.
   1068  *
   1069  * The caller may receive the data as a single mbuf chain by supplying
   1070  * an mbuf **mp0 for use in returning the chain.  The uio is then used
   1071  * only for the count in uio_resid.
   1072  */
   1073 int
   1074 soreceive(struct socket *so, struct mbuf **paddr, struct uio *uio,
   1075 	struct mbuf **mp0, struct mbuf **controlp, int *flagsp)
   1076 {
   1077 	struct lwp *l = curlwp;
   1078 	struct mbuf	*m, **mp, *mt;
   1079 	int atomic, flags, len, error, s, offset, moff, type, orig_resid;
   1080 	const struct protosw	*pr;
   1081 	struct mbuf	*nextrecord;
   1082 	int		mbuf_removed = 0;
   1083 	const struct domain *dom;
   1084 
   1085 	pr = so->so_proto;
   1086 	atomic = pr->pr_flags & PR_ATOMIC;
   1087 	dom = pr->pr_domain;
   1088 	mp = mp0;
   1089 	type = 0;
   1090 	orig_resid = uio->uio_resid;
   1091 
   1092 	if (paddr != NULL)
   1093 		*paddr = NULL;
   1094 	if (controlp != NULL)
   1095 		*controlp = NULL;
   1096 	if (flagsp != NULL)
   1097 		flags = *flagsp &~ MSG_EOR;
   1098 	else
   1099 		flags = 0;
   1100 
   1101 	if ((flags & MSG_DONTWAIT) == 0)
   1102 		sodopendfree();
   1103 
   1104 	if (flags & MSG_OOB) {
   1105 		m = m_get(M_WAIT, MT_DATA);
   1106 		solock(so);
   1107 		error = (*pr->pr_usrreq)(so, PRU_RCVOOB, m,
   1108 		    (struct mbuf *)(long)(flags & MSG_PEEK), NULL, l);
   1109 		sounlock(so);
   1110 		if (error)
   1111 			goto bad;
   1112 		do {
   1113 			error = uiomove(mtod(m, void *),
   1114 			    (int) min(uio->uio_resid, m->m_len), uio);
   1115 			m = m_free(m);
   1116 		} while (uio->uio_resid > 0 && error == 0 && m);
   1117  bad:
   1118 		if (m != NULL)
   1119 			m_freem(m);
   1120 		return error;
   1121 	}
   1122 	if (mp != NULL)
   1123 		*mp = NULL;
   1124 
   1125 	/*
   1126 	 * solock() provides atomicity of access.  splsoftnet() prevents
   1127 	 * protocol processing soft interrupts from interrupting us and
   1128 	 * blocking (expensive).
   1129 	 */
   1130 	s = splsoftnet();
   1131 	solock(so);
   1132 	if (so->so_state & SS_ISCONFIRMING && uio->uio_resid)
   1133 		(*pr->pr_usrreq)(so, PRU_RCVD, NULL, NULL, NULL, l);
   1134 
   1135  restart:
   1136 	if ((error = sblock(&so->so_rcv, SBLOCKWAIT(flags))) != 0) {
   1137 		sounlock(so);
   1138 		splx(s);
   1139 		return error;
   1140 	}
   1141 
   1142 	m = so->so_rcv.sb_mb;
   1143 	/*
   1144 	 * If we have less data than requested, block awaiting more
   1145 	 * (subject to any timeout) if:
   1146 	 *   1. the current count is less than the low water mark,
   1147 	 *   2. MSG_WAITALL is set, and it is possible to do the entire
   1148 	 *	receive operation at once if we block (resid <= hiwat), or
   1149 	 *   3. MSG_DONTWAIT is not set.
   1150 	 * If MSG_WAITALL is set but resid is larger than the receive buffer,
   1151 	 * we have to do the receive in sections, and thus risk returning
   1152 	 * a short count if a timeout or signal occurs after we start.
   1153 	 */
   1154 	if (m == NULL ||
   1155 	    ((flags & MSG_DONTWAIT) == 0 &&
   1156 	     so->so_rcv.sb_cc < uio->uio_resid &&
   1157 	     (so->so_rcv.sb_cc < so->so_rcv.sb_lowat ||
   1158 	      ((flags & MSG_WAITALL) &&
   1159 	       uio->uio_resid <= so->so_rcv.sb_hiwat)) &&
   1160 	     m->m_nextpkt == NULL && !atomic)) {
   1161 #ifdef DIAGNOSTIC
   1162 		if (m == NULL && so->so_rcv.sb_cc)
   1163 			panic("receive 1");
   1164 #endif
   1165 		if (so->so_error) {
   1166 			if (m != NULL)
   1167 				goto dontblock;
   1168 			error = so->so_error;
   1169 			if ((flags & MSG_PEEK) == 0)
   1170 				so->so_error = 0;
   1171 			goto release;
   1172 		}
   1173 		if (so->so_state & SS_CANTRCVMORE) {
   1174 			if (m != NULL)
   1175 				goto dontblock;
   1176 			else
   1177 				goto release;
   1178 		}
   1179 		for (; m != NULL; m = m->m_next)
   1180 			if (m->m_type == MT_OOBDATA  || (m->m_flags & M_EOR)) {
   1181 				m = so->so_rcv.sb_mb;
   1182 				goto dontblock;
   1183 			}
   1184 		if ((so->so_state & (SS_ISCONNECTED|SS_ISCONNECTING)) == 0 &&
   1185 		    (so->so_proto->pr_flags & PR_CONNREQUIRED)) {
   1186 			error = ENOTCONN;
   1187 			goto release;
   1188 		}
   1189 		if (uio->uio_resid == 0)
   1190 			goto release;
   1191 		if (so->so_nbio || (flags & MSG_DONTWAIT)) {
   1192 			error = EWOULDBLOCK;
   1193 			goto release;
   1194 		}
   1195 		SBLASTRECORDCHK(&so->so_rcv, "soreceive sbwait 1");
   1196 		SBLASTMBUFCHK(&so->so_rcv, "soreceive sbwait 1");
   1197 		sbunlock(&so->so_rcv);
   1198 		error = sbwait(&so->so_rcv);
   1199 		if (error != 0) {
   1200 			sounlock(so);
   1201 			splx(s);
   1202 			return error;
   1203 		}
   1204 		goto restart;
   1205 	}
   1206  dontblock:
   1207 	/*
   1208 	 * On entry here, m points to the first record of the socket buffer.
   1209 	 * From this point onward, we maintain 'nextrecord' as a cache of the
   1210 	 * pointer to the next record in the socket buffer.  We must keep the
   1211 	 * various socket buffer pointers and local stack versions of the
   1212 	 * pointers in sync, pushing out modifications before dropping the
   1213 	 * socket lock, and re-reading them when picking it up.
   1214 	 *
   1215 	 * Otherwise, we will race with the network stack appending new data
   1216 	 * or records onto the socket buffer by using inconsistent/stale
   1217 	 * versions of the field, possibly resulting in socket buffer
   1218 	 * corruption.
   1219 	 *
   1220 	 * By holding the high-level sblock(), we prevent simultaneous
   1221 	 * readers from pulling off the front of the socket buffer.
   1222 	 */
   1223 	if (l != NULL)
   1224 		l->l_ru.ru_msgrcv++;
   1225 	KASSERT(m == so->so_rcv.sb_mb);
   1226 	SBLASTRECORDCHK(&so->so_rcv, "soreceive 1");
   1227 	SBLASTMBUFCHK(&so->so_rcv, "soreceive 1");
   1228 	nextrecord = m->m_nextpkt;
   1229 	if (pr->pr_flags & PR_ADDR) {
   1230 #ifdef DIAGNOSTIC
   1231 		if (m->m_type != MT_SONAME)
   1232 			panic("receive 1a");
   1233 #endif
   1234 		orig_resid = 0;
   1235 		if (flags & MSG_PEEK) {
   1236 			if (paddr)
   1237 				*paddr = m_copy(m, 0, m->m_len);
   1238 			m = m->m_next;
   1239 		} else {
   1240 			sbfree(&so->so_rcv, m);
   1241 			mbuf_removed = 1;
   1242 			if (paddr != NULL) {
   1243 				*paddr = m;
   1244 				so->so_rcv.sb_mb = m->m_next;
   1245 				m->m_next = NULL;
   1246 				m = so->so_rcv.sb_mb;
   1247 			} else {
   1248 				MFREE(m, so->so_rcv.sb_mb);
   1249 				m = so->so_rcv.sb_mb;
   1250 			}
   1251 			sbsync(&so->so_rcv, nextrecord);
   1252 		}
   1253 	}
   1254 
   1255 	/*
   1256 	 * Process one or more MT_CONTROL mbufs present before any data mbufs
   1257 	 * in the first mbuf chain on the socket buffer.  If MSG_PEEK, we
   1258 	 * just copy the data; if !MSG_PEEK, we call into the protocol to
   1259 	 * perform externalization (or freeing if controlp == NULL).
   1260 	 */
   1261 	if (__predict_false(m != NULL && m->m_type == MT_CONTROL)) {
   1262 		struct mbuf *cm = NULL, *cmn;
   1263 		struct mbuf **cme = &cm;
   1264 
   1265 		do {
   1266 			if (flags & MSG_PEEK) {
   1267 				if (controlp != NULL) {
   1268 					*controlp = m_copy(m, 0, m->m_len);
   1269 					controlp = &(*controlp)->m_next;
   1270 				}
   1271 				m = m->m_next;
   1272 			} else {
   1273 				sbfree(&so->so_rcv, m);
   1274 				so->so_rcv.sb_mb = m->m_next;
   1275 				m->m_next = NULL;
   1276 				*cme = m;
   1277 				cme = &(*cme)->m_next;
   1278 				m = so->so_rcv.sb_mb;
   1279 			}
   1280 		} while (m != NULL && m->m_type == MT_CONTROL);
   1281 		if ((flags & MSG_PEEK) == 0)
   1282 			sbsync(&so->so_rcv, nextrecord);
   1283 		for (; cm != NULL; cm = cmn) {
   1284 			cmn = cm->m_next;
   1285 			cm->m_next = NULL;
   1286 			type = mtod(cm, struct cmsghdr *)->cmsg_type;
   1287 			if (controlp != NULL) {
   1288 				if (dom->dom_externalize != NULL &&
   1289 				    type == SCM_RIGHTS) {
   1290 					sounlock(so);
   1291 					splx(s);
   1292 					error = (*dom->dom_externalize)(cm, l);
   1293 					s = splsoftnet();
   1294 					solock(so);
   1295 				}
   1296 				*controlp = cm;
   1297 				while (*controlp != NULL)
   1298 					controlp = &(*controlp)->m_next;
   1299 			} else {
   1300 				/*
   1301 				 * Dispose of any SCM_RIGHTS message that went
   1302 				 * through the read path rather than recv.
   1303 				 */
   1304 				if (dom->dom_dispose != NULL &&
   1305 				    type == SCM_RIGHTS) {
   1306 				    	sounlock(so);
   1307 					(*dom->dom_dispose)(cm);
   1308 					solock(so);
   1309 				}
   1310 				m_freem(cm);
   1311 			}
   1312 		}
   1313 		if (m != NULL)
   1314 			nextrecord = so->so_rcv.sb_mb->m_nextpkt;
   1315 		else
   1316 			nextrecord = so->so_rcv.sb_mb;
   1317 		orig_resid = 0;
   1318 	}
   1319 
   1320 	/* If m is non-NULL, we have some data to read. */
   1321 	if (__predict_true(m != NULL)) {
   1322 		type = m->m_type;
   1323 		if (type == MT_OOBDATA)
   1324 			flags |= MSG_OOB;
   1325 	}
   1326 	SBLASTRECORDCHK(&so->so_rcv, "soreceive 2");
   1327 	SBLASTMBUFCHK(&so->so_rcv, "soreceive 2");
   1328 
   1329 	moff = 0;
   1330 	offset = 0;
   1331 	while (m != NULL && uio->uio_resid > 0 && error == 0) {
   1332 		if (m->m_type == MT_OOBDATA) {
   1333 			if (type != MT_OOBDATA)
   1334 				break;
   1335 		} else if (type == MT_OOBDATA)
   1336 			break;
   1337 #ifdef DIAGNOSTIC
   1338 		else if (m->m_type != MT_DATA && m->m_type != MT_HEADER)
   1339 			panic("receive 3");
   1340 #endif
   1341 		so->so_state &= ~SS_RCVATMARK;
   1342 		len = uio->uio_resid;
   1343 		if (so->so_oobmark && len > so->so_oobmark - offset)
   1344 			len = so->so_oobmark - offset;
   1345 		if (len > m->m_len - moff)
   1346 			len = m->m_len - moff;
   1347 		/*
   1348 		 * If mp is set, just pass back the mbufs.
   1349 		 * Otherwise copy them out via the uio, then free.
   1350 		 * Sockbuf must be consistent here (points to current mbuf,
   1351 		 * it points to next record) when we drop priority;
   1352 		 * we must note any additions to the sockbuf when we
   1353 		 * block interrupts again.
   1354 		 */
   1355 		if (mp == NULL) {
   1356 			SBLASTRECORDCHK(&so->so_rcv, "soreceive uiomove");
   1357 			SBLASTMBUFCHK(&so->so_rcv, "soreceive uiomove");
   1358 			sounlock(so);
   1359 			splx(s);
   1360 			error = uiomove(mtod(m, char *) + moff, (int)len, uio);
   1361 			s = splsoftnet();
   1362 			solock(so);
   1363 			if (error != 0) {
   1364 				/*
   1365 				 * If any part of the record has been removed
   1366 				 * (such as the MT_SONAME mbuf, which will
   1367 				 * happen when PR_ADDR, and thus also
   1368 				 * PR_ATOMIC, is set), then drop the entire
   1369 				 * record to maintain the atomicity of the
   1370 				 * receive operation.
   1371 				 *
   1372 				 * This avoids a later panic("receive 1a")
   1373 				 * when compiled with DIAGNOSTIC.
   1374 				 */
   1375 				if (m && mbuf_removed && atomic)
   1376 					(void) sbdroprecord(&so->so_rcv);
   1377 
   1378 				goto release;
   1379 			}
   1380 		} else
   1381 			uio->uio_resid -= len;
   1382 		if (len == m->m_len - moff) {
   1383 			if (m->m_flags & M_EOR)
   1384 				flags |= MSG_EOR;
   1385 			if (flags & MSG_PEEK) {
   1386 				m = m->m_next;
   1387 				moff = 0;
   1388 			} else {
   1389 				nextrecord = m->m_nextpkt;
   1390 				sbfree(&so->so_rcv, m);
   1391 				if (mp) {
   1392 					*mp = m;
   1393 					mp = &m->m_next;
   1394 					so->so_rcv.sb_mb = m = m->m_next;
   1395 					*mp = NULL;
   1396 				} else {
   1397 					MFREE(m, so->so_rcv.sb_mb);
   1398 					m = so->so_rcv.sb_mb;
   1399 				}
   1400 				/*
   1401 				 * If m != NULL, we also know that
   1402 				 * so->so_rcv.sb_mb != NULL.
   1403 				 */
   1404 				KASSERT(so->so_rcv.sb_mb == m);
   1405 				if (m) {
   1406 					m->m_nextpkt = nextrecord;
   1407 					if (nextrecord == NULL)
   1408 						so->so_rcv.sb_lastrecord = m;
   1409 				} else {
   1410 					so->so_rcv.sb_mb = nextrecord;
   1411 					SB_EMPTY_FIXUP(&so->so_rcv);
   1412 				}
   1413 				SBLASTRECORDCHK(&so->so_rcv, "soreceive 3");
   1414 				SBLASTMBUFCHK(&so->so_rcv, "soreceive 3");
   1415 			}
   1416 		} else if (flags & MSG_PEEK)
   1417 			moff += len;
   1418 		else {
   1419 			if (mp != NULL) {
   1420 				mt = m_copym(m, 0, len, M_NOWAIT);
   1421 				if (__predict_false(mt == NULL)) {
   1422 					sounlock(so);
   1423 					mt = m_copym(m, 0, len, M_WAIT);
   1424 					solock(so);
   1425 				}
   1426 				*mp = mt;
   1427 			}
   1428 			m->m_data += len;
   1429 			m->m_len -= len;
   1430 			so->so_rcv.sb_cc -= len;
   1431 		}
   1432 		if (so->so_oobmark) {
   1433 			if ((flags & MSG_PEEK) == 0) {
   1434 				so->so_oobmark -= len;
   1435 				if (so->so_oobmark == 0) {
   1436 					so->so_state |= SS_RCVATMARK;
   1437 					break;
   1438 				}
   1439 			} else {
   1440 				offset += len;
   1441 				if (offset == so->so_oobmark)
   1442 					break;
   1443 			}
   1444 		}
   1445 		if (flags & MSG_EOR)
   1446 			break;
   1447 		/*
   1448 		 * If the MSG_WAITALL flag is set (for non-atomic socket),
   1449 		 * we must not quit until "uio->uio_resid == 0" or an error
   1450 		 * termination.  If a signal/timeout occurs, return
   1451 		 * with a short count but without error.
   1452 		 * Keep sockbuf locked against other readers.
   1453 		 */
   1454 		while (flags & MSG_WAITALL && m == NULL && uio->uio_resid > 0 &&
   1455 		    !sosendallatonce(so) && !nextrecord) {
   1456 			if (so->so_error || so->so_state & SS_CANTRCVMORE)
   1457 				break;
   1458 			/*
   1459 			 * If we are peeking and the socket receive buffer is
   1460 			 * full, stop since we can't get more data to peek at.
   1461 			 */
   1462 			if ((flags & MSG_PEEK) && sbspace(&so->so_rcv) <= 0)
   1463 				break;
   1464 			/*
   1465 			 * If we've drained the socket buffer, tell the
   1466 			 * protocol in case it needs to do something to
   1467 			 * get it filled again.
   1468 			 */
   1469 			if ((pr->pr_flags & PR_WANTRCVD) && so->so_pcb)
   1470 				(*pr->pr_usrreq)(so, PRU_RCVD,
   1471 				    NULL, (struct mbuf *)(long)flags, NULL, l);
   1472 			SBLASTRECORDCHK(&so->so_rcv, "soreceive sbwait 2");
   1473 			SBLASTMBUFCHK(&so->so_rcv, "soreceive sbwait 2");
   1474 			error = sbwait(&so->so_rcv);
   1475 			if (error != 0) {
   1476 				sbunlock(&so->so_rcv);
   1477 				sounlock(so);
   1478 				splx(s);
   1479 				return 0;
   1480 			}
   1481 			if ((m = so->so_rcv.sb_mb) != NULL)
   1482 				nextrecord = m->m_nextpkt;
   1483 		}
   1484 	}
   1485 
   1486 	if (m && atomic) {
   1487 		flags |= MSG_TRUNC;
   1488 		if ((flags & MSG_PEEK) == 0)
   1489 			(void) sbdroprecord(&so->so_rcv);
   1490 	}
   1491 	if ((flags & MSG_PEEK) == 0) {
   1492 		if (m == NULL) {
   1493 			/*
   1494 			 * First part is an inline SB_EMPTY_FIXUP().  Second
   1495 			 * part makes sure sb_lastrecord is up-to-date if
   1496 			 * there is still data in the socket buffer.
   1497 			 */
   1498 			so->so_rcv.sb_mb = nextrecord;
   1499 			if (so->so_rcv.sb_mb == NULL) {
   1500 				so->so_rcv.sb_mbtail = NULL;
   1501 				so->so_rcv.sb_lastrecord = NULL;
   1502 			} else if (nextrecord->m_nextpkt == NULL)
   1503 				so->so_rcv.sb_lastrecord = nextrecord;
   1504 		}
   1505 		SBLASTRECORDCHK(&so->so_rcv, "soreceive 4");
   1506 		SBLASTMBUFCHK(&so->so_rcv, "soreceive 4");
   1507 		if (pr->pr_flags & PR_WANTRCVD && so->so_pcb)
   1508 			(*pr->pr_usrreq)(so, PRU_RCVD, NULL,
   1509 			    (struct mbuf *)(long)flags, NULL, l);
   1510 	}
   1511 	if (orig_resid == uio->uio_resid && orig_resid &&
   1512 	    (flags & MSG_EOR) == 0 && (so->so_state & SS_CANTRCVMORE) == 0) {
   1513 		sbunlock(&so->so_rcv);
   1514 		goto restart;
   1515 	}
   1516 
   1517 	if (flagsp != NULL)
   1518 		*flagsp |= flags;
   1519  release:
   1520 	sbunlock(&so->so_rcv);
   1521 	sounlock(so);
   1522 	splx(s);
   1523 	return error;
   1524 }
   1525 
   1526 int
   1527 soshutdown(struct socket *so, int how)
   1528 {
   1529 	const struct protosw	*pr;
   1530 	int	error;
   1531 
   1532 	KASSERT(solocked(so));
   1533 
   1534 	pr = so->so_proto;
   1535 	if (!(how == SHUT_RD || how == SHUT_WR || how == SHUT_RDWR))
   1536 		return (EINVAL);
   1537 
   1538 	if (how == SHUT_RD || how == SHUT_RDWR) {
   1539 		sorflush(so);
   1540 		error = 0;
   1541 	}
   1542 	if (how == SHUT_WR || how == SHUT_RDWR)
   1543 		error = (*pr->pr_usrreq)(so, PRU_SHUTDOWN, NULL,
   1544 		    NULL, NULL, NULL);
   1545 
   1546 	return error;
   1547 }
   1548 
   1549 void
   1550 sorflush(struct socket *so)
   1551 {
   1552 	struct sockbuf	*sb, asb;
   1553 	const struct protosw	*pr;
   1554 
   1555 	KASSERT(solocked(so));
   1556 
   1557 	sb = &so->so_rcv;
   1558 	pr = so->so_proto;
   1559 	socantrcvmore(so);
   1560 	sb->sb_flags |= SB_NOINTR;
   1561 	(void )sblock(sb, M_WAITOK);
   1562 	sbunlock(sb);
   1563 	asb = *sb;
   1564 	/*
   1565 	 * Clear most of the sockbuf structure, but leave some of the
   1566 	 * fields valid.
   1567 	 */
   1568 	memset(&sb->sb_startzero, 0,
   1569 	    sizeof(*sb) - offsetof(struct sockbuf, sb_startzero));
   1570 	if (pr->pr_flags & PR_RIGHTS && pr->pr_domain->dom_dispose) {
   1571 		sounlock(so);
   1572 		(*pr->pr_domain->dom_dispose)(asb.sb_mb);
   1573 		solock(so);
   1574 	}
   1575 	sbrelease(&asb, so);
   1576 }
   1577 
   1578 static int
   1579 sosetopt1(struct socket *so, int level, int optname, struct mbuf *m)
   1580 {
   1581 	int optval, val;
   1582 	struct linger	*l;
   1583 	struct sockbuf	*sb;
   1584 	struct timeval *tv;
   1585 
   1586 	switch (optname) {
   1587 
   1588 	case SO_LINGER:
   1589 		if (m == NULL || m->m_len != sizeof(struct linger))
   1590 			return EINVAL;
   1591 		l = mtod(m, struct linger *);
   1592 		if (l->l_linger < 0 || l->l_linger > USHRT_MAX ||
   1593 		    l->l_linger > (INT_MAX / hz))
   1594 			return EDOM;
   1595 		so->so_linger = l->l_linger;
   1596 		if (l->l_onoff)
   1597 			so->so_options |= SO_LINGER;
   1598 		else
   1599 			so->so_options &= ~SO_LINGER;
   1600 		break;
   1601 
   1602 	case SO_DEBUG:
   1603 	case SO_KEEPALIVE:
   1604 	case SO_DONTROUTE:
   1605 	case SO_USELOOPBACK:
   1606 	case SO_BROADCAST:
   1607 	case SO_REUSEADDR:
   1608 	case SO_REUSEPORT:
   1609 	case SO_OOBINLINE:
   1610 	case SO_TIMESTAMP:
   1611 		if (m == NULL || m->m_len < sizeof(int))
   1612 			return EINVAL;
   1613 		if (*mtod(m, int *))
   1614 			so->so_options |= optname;
   1615 		else
   1616 			so->so_options &= ~optname;
   1617 		break;
   1618 
   1619 	case SO_SNDBUF:
   1620 	case SO_RCVBUF:
   1621 	case SO_SNDLOWAT:
   1622 	case SO_RCVLOWAT:
   1623 		if (m == NULL || m->m_len < sizeof(int))
   1624 			return EINVAL;
   1625 
   1626 		/*
   1627 		 * Values < 1 make no sense for any of these
   1628 		 * options, so disallow them.
   1629 		 */
   1630 		optval = *mtod(m, int *);
   1631 		if (optval < 1)
   1632 			return EINVAL;
   1633 
   1634 		switch (optname) {
   1635 
   1636 		case SO_SNDBUF:
   1637 		case SO_RCVBUF:
   1638 			sb = (optname == SO_SNDBUF) ?
   1639 			    &so->so_snd : &so->so_rcv;
   1640 			if (sbreserve(sb, (u_long)optval, so) == 0)
   1641 				return ENOBUFS;
   1642 			sb->sb_flags &= ~SB_AUTOSIZE;
   1643 			break;
   1644 
   1645 		/*
   1646 		 * Make sure the low-water is never greater than
   1647 		 * the high-water.
   1648 		 */
   1649 		case SO_SNDLOWAT:
   1650 			so->so_snd.sb_lowat =
   1651 			    (optval > so->so_snd.sb_hiwat) ?
   1652 			    so->so_snd.sb_hiwat : optval;
   1653 			break;
   1654 		case SO_RCVLOWAT:
   1655 			so->so_rcv.sb_lowat =
   1656 			    (optval > so->so_rcv.sb_hiwat) ?
   1657 			    so->so_rcv.sb_hiwat : optval;
   1658 			break;
   1659 		}
   1660 		break;
   1661 
   1662 	case SO_SNDTIMEO:
   1663 	case SO_RCVTIMEO:
   1664 		if (m == NULL || m->m_len < sizeof(*tv))
   1665 			return EINVAL;
   1666 		tv = mtod(m, struct timeval *);
   1667 		if (tv->tv_sec > (INT_MAX - tv->tv_usec / tick) / hz)
   1668 			return EDOM;
   1669 		val = tv->tv_sec * hz + tv->tv_usec / tick;
   1670 		if (val == 0 && tv->tv_usec != 0)
   1671 			val = 1;
   1672 
   1673 		switch (optname) {
   1674 
   1675 		case SO_SNDTIMEO:
   1676 			so->so_snd.sb_timeo = val;
   1677 			break;
   1678 		case SO_RCVTIMEO:
   1679 			so->so_rcv.sb_timeo = val;
   1680 			break;
   1681 		}
   1682 		break;
   1683 
   1684 	default:
   1685 		return ENOPROTOOPT;
   1686 	}
   1687 	return 0;
   1688 }
   1689 
   1690 int
   1691 sosetopt(struct socket *so, int level, int optname, struct mbuf *m)
   1692 {
   1693 	int error, prerr;
   1694 
   1695 	solock(so);
   1696 	if (level == SOL_SOCKET)
   1697 		error = sosetopt1(so, level, optname, m);
   1698 	else
   1699 		error = ENOPROTOOPT;
   1700 
   1701 	if ((error == 0 || error == ENOPROTOOPT) &&
   1702 	    so->so_proto != NULL && so->so_proto->pr_ctloutput != NULL) {
   1703 		/* give the protocol stack a shot */
   1704 		prerr = (*so->so_proto->pr_ctloutput)(PRCO_SETOPT, so, level,
   1705 		    optname, &m);
   1706 		if (prerr == 0)
   1707 			error = 0;
   1708 		else if (prerr != ENOPROTOOPT)
   1709 			error = prerr;
   1710 	} else if (m != NULL)
   1711 		(void)m_free(m);
   1712 	sounlock(so);
   1713 	return error;
   1714 }
   1715 
   1716 int
   1717 sogetopt(struct socket *so, int level, int optname, struct mbuf **mp)
   1718 {
   1719 	struct mbuf	*m;
   1720 	int		error;
   1721 
   1722 	solock(so);
   1723 	if (level != SOL_SOCKET) {
   1724 		if (so->so_proto && so->so_proto->pr_ctloutput) {
   1725 			error = ((*so->so_proto->pr_ctloutput)
   1726 				  (PRCO_GETOPT, so, level, optname, mp));
   1727 		} else
   1728 			error = (ENOPROTOOPT);
   1729 	} else {
   1730 		m = m_get(M_WAIT, MT_SOOPTS);
   1731 		m->m_len = sizeof(int);
   1732 
   1733 		switch (optname) {
   1734 
   1735 		case SO_LINGER:
   1736 			m->m_len = sizeof(struct linger);
   1737 			mtod(m, struct linger *)->l_onoff =
   1738 			    (so->so_options & SO_LINGER) ? 1 : 0;
   1739 			mtod(m, struct linger *)->l_linger = so->so_linger;
   1740 			break;
   1741 
   1742 		case SO_USELOOPBACK:
   1743 		case SO_DONTROUTE:
   1744 		case SO_DEBUG:
   1745 		case SO_KEEPALIVE:
   1746 		case SO_REUSEADDR:
   1747 		case SO_REUSEPORT:
   1748 		case SO_BROADCAST:
   1749 		case SO_OOBINLINE:
   1750 		case SO_TIMESTAMP:
   1751 			*mtod(m, int *) = (so->so_options & optname) ? 1 : 0;
   1752 			break;
   1753 
   1754 		case SO_TYPE:
   1755 			*mtod(m, int *) = so->so_type;
   1756 			break;
   1757 
   1758 		case SO_ERROR:
   1759 			*mtod(m, int *) = so->so_error;
   1760 			so->so_error = 0;
   1761 			break;
   1762 
   1763 		case SO_SNDBUF:
   1764 			*mtod(m, int *) = so->so_snd.sb_hiwat;
   1765 			break;
   1766 
   1767 		case SO_RCVBUF:
   1768 			*mtod(m, int *) = so->so_rcv.sb_hiwat;
   1769 			break;
   1770 
   1771 		case SO_SNDLOWAT:
   1772 			*mtod(m, int *) = so->so_snd.sb_lowat;
   1773 			break;
   1774 
   1775 		case SO_RCVLOWAT:
   1776 			*mtod(m, int *) = so->so_rcv.sb_lowat;
   1777 			break;
   1778 
   1779 		case SO_SNDTIMEO:
   1780 		case SO_RCVTIMEO:
   1781 		    {
   1782 			int val = (optname == SO_SNDTIMEO ?
   1783 			     so->so_snd.sb_timeo : so->so_rcv.sb_timeo);
   1784 
   1785 			m->m_len = sizeof(struct timeval);
   1786 			mtod(m, struct timeval *)->tv_sec = val / hz;
   1787 			mtod(m, struct timeval *)->tv_usec =
   1788 			    (val % hz) * tick;
   1789 			break;
   1790 		    }
   1791 
   1792 		case SO_OVERFLOWED:
   1793 			*mtod(m, int *) = so->so_rcv.sb_overflowed;
   1794 			break;
   1795 
   1796 		default:
   1797 			sounlock(so);
   1798 			(void)m_free(m);
   1799 			return (ENOPROTOOPT);
   1800 		}
   1801 		*mp = m;
   1802 		error = 0;
   1803 	}
   1804 
   1805 	sounlock(so);
   1806 	return (error);
   1807 }
   1808 
   1809 void
   1810 sohasoutofband(struct socket *so)
   1811 {
   1812 
   1813 	fownsignal(so->so_pgid, SIGURG, POLL_PRI, POLLPRI|POLLRDBAND, so);
   1814 	selnotify(&so->so_rcv.sb_sel, POLLPRI | POLLRDBAND, 0);
   1815 }
   1816 
   1817 static void
   1818 filt_sordetach(struct knote *kn)
   1819 {
   1820 	struct socket	*so;
   1821 
   1822 	so = ((file_t *)kn->kn_obj)->f_data;
   1823 	solock(so);
   1824 	SLIST_REMOVE(&so->so_rcv.sb_sel.sel_klist, kn, knote, kn_selnext);
   1825 	if (SLIST_EMPTY(&so->so_rcv.sb_sel.sel_klist))
   1826 		so->so_rcv.sb_flags &= ~SB_KNOTE;
   1827 	sounlock(so);
   1828 }
   1829 
   1830 /*ARGSUSED*/
   1831 static int
   1832 filt_soread(struct knote *kn, long hint)
   1833 {
   1834 	struct socket	*so;
   1835 	int rv;
   1836 
   1837 	so = ((file_t *)kn->kn_obj)->f_data;
   1838 	if (hint != NOTE_SUBMIT)
   1839 		solock(so);
   1840 	kn->kn_data = so->so_rcv.sb_cc;
   1841 	if (so->so_state & SS_CANTRCVMORE) {
   1842 		kn->kn_flags |= EV_EOF;
   1843 		kn->kn_fflags = so->so_error;
   1844 		rv = 1;
   1845 	} else if (so->so_error)	/* temporary udp error */
   1846 		rv = 1;
   1847 	else if (kn->kn_sfflags & NOTE_LOWAT)
   1848 		rv = (kn->kn_data >= kn->kn_sdata);
   1849 	else
   1850 		rv = (kn->kn_data >= so->so_rcv.sb_lowat);
   1851 	if (hint != NOTE_SUBMIT)
   1852 		sounlock(so);
   1853 	return rv;
   1854 }
   1855 
   1856 static void
   1857 filt_sowdetach(struct knote *kn)
   1858 {
   1859 	struct socket	*so;
   1860 
   1861 	so = ((file_t *)kn->kn_obj)->f_data;
   1862 	solock(so);
   1863 	SLIST_REMOVE(&so->so_snd.sb_sel.sel_klist, kn, knote, kn_selnext);
   1864 	if (SLIST_EMPTY(&so->so_snd.sb_sel.sel_klist))
   1865 		so->so_snd.sb_flags &= ~SB_KNOTE;
   1866 	sounlock(so);
   1867 }
   1868 
   1869 /*ARGSUSED*/
   1870 static int
   1871 filt_sowrite(struct knote *kn, long hint)
   1872 {
   1873 	struct socket	*so;
   1874 	int rv;
   1875 
   1876 	so = ((file_t *)kn->kn_obj)->f_data;
   1877 	if (hint != NOTE_SUBMIT)
   1878 		solock(so);
   1879 	kn->kn_data = sbspace(&so->so_snd);
   1880 	if (so->so_state & SS_CANTSENDMORE) {
   1881 		kn->kn_flags |= EV_EOF;
   1882 		kn->kn_fflags = so->so_error;
   1883 		rv = 1;
   1884 	} else if (so->so_error)	/* temporary udp error */
   1885 		rv = 1;
   1886 	else if (((so->so_state & SS_ISCONNECTED) == 0) &&
   1887 	    (so->so_proto->pr_flags & PR_CONNREQUIRED))
   1888 		rv = 0;
   1889 	else if (kn->kn_sfflags & NOTE_LOWAT)
   1890 		rv = (kn->kn_data >= kn->kn_sdata);
   1891 	else
   1892 		rv = (kn->kn_data >= so->so_snd.sb_lowat);
   1893 	if (hint != NOTE_SUBMIT)
   1894 		sounlock(so);
   1895 	return rv;
   1896 }
   1897 
   1898 /*ARGSUSED*/
   1899 static int
   1900 filt_solisten(struct knote *kn, long hint)
   1901 {
   1902 	struct socket	*so;
   1903 	int rv;
   1904 
   1905 	so = ((file_t *)kn->kn_obj)->f_data;
   1906 
   1907 	/*
   1908 	 * Set kn_data to number of incoming connections, not
   1909 	 * counting partial (incomplete) connections.
   1910 	 */
   1911 	if (hint != NOTE_SUBMIT)
   1912 		solock(so);
   1913 	kn->kn_data = so->so_qlen;
   1914 	rv = (kn->kn_data > 0);
   1915 	if (hint != NOTE_SUBMIT)
   1916 		sounlock(so);
   1917 	return rv;
   1918 }
   1919 
   1920 static const struct filterops solisten_filtops =
   1921 	{ 1, NULL, filt_sordetach, filt_solisten };
   1922 static const struct filterops soread_filtops =
   1923 	{ 1, NULL, filt_sordetach, filt_soread };
   1924 static const struct filterops sowrite_filtops =
   1925 	{ 1, NULL, filt_sowdetach, filt_sowrite };
   1926 
   1927 int
   1928 soo_kqfilter(struct file *fp, struct knote *kn)
   1929 {
   1930 	struct socket	*so;
   1931 	struct sockbuf	*sb;
   1932 
   1933 	so = ((file_t *)kn->kn_obj)->f_data;
   1934 	solock(so);
   1935 	switch (kn->kn_filter) {
   1936 	case EVFILT_READ:
   1937 		if (so->so_options & SO_ACCEPTCONN)
   1938 			kn->kn_fop = &solisten_filtops;
   1939 		else
   1940 			kn->kn_fop = &soread_filtops;
   1941 		sb = &so->so_rcv;
   1942 		break;
   1943 	case EVFILT_WRITE:
   1944 		kn->kn_fop = &sowrite_filtops;
   1945 		sb = &so->so_snd;
   1946 		break;
   1947 	default:
   1948 		sounlock(so);
   1949 		return (EINVAL);
   1950 	}
   1951 	SLIST_INSERT_HEAD(&sb->sb_sel.sel_klist, kn, kn_selnext);
   1952 	sb->sb_flags |= SB_KNOTE;
   1953 	sounlock(so);
   1954 	return (0);
   1955 }
   1956 
   1957 static int
   1958 sodopoll(struct socket *so, int events)
   1959 {
   1960 	int revents;
   1961 
   1962 	revents = 0;
   1963 
   1964 	if (events & (POLLIN | POLLRDNORM))
   1965 		if (soreadable(so))
   1966 			revents |= events & (POLLIN | POLLRDNORM);
   1967 
   1968 	if (events & (POLLOUT | POLLWRNORM))
   1969 		if (sowritable(so))
   1970 			revents |= events & (POLLOUT | POLLWRNORM);
   1971 
   1972 	if (events & (POLLPRI | POLLRDBAND))
   1973 		if (so->so_oobmark || (so->so_state & SS_RCVATMARK))
   1974 			revents |= events & (POLLPRI | POLLRDBAND);
   1975 
   1976 	return revents;
   1977 }
   1978 
   1979 int
   1980 sopoll(struct socket *so, int events)
   1981 {
   1982 	int revents = 0;
   1983 
   1984 #ifndef DIAGNOSTIC
   1985 	/*
   1986 	 * Do a quick, unlocked check in expectation that the socket
   1987 	 * will be ready for I/O.  Don't do this check if DIAGNOSTIC,
   1988 	 * as the solocked() assertions will fail.
   1989 	 */
   1990 	if ((revents = sodopoll(so, events)) != 0)
   1991 		return revents;
   1992 #endif
   1993 
   1994 	solock(so);
   1995 	if ((revents = sodopoll(so, events)) == 0) {
   1996 		if (events & (POLLIN | POLLPRI | POLLRDNORM | POLLRDBAND)) {
   1997 			selrecord(curlwp, &so->so_rcv.sb_sel);
   1998 			so->so_rcv.sb_flags |= SB_NOTIFY;
   1999 		}
   2000 
   2001 		if (events & (POLLOUT | POLLWRNORM)) {
   2002 			selrecord(curlwp, &so->so_snd.sb_sel);
   2003 			so->so_snd.sb_flags |= SB_NOTIFY;
   2004 		}
   2005 	}
   2006 	sounlock(so);
   2007 
   2008 	return revents;
   2009 }
   2010 
   2011 
   2012 #include <sys/sysctl.h>
   2013 
   2014 static int sysctl_kern_somaxkva(SYSCTLFN_PROTO);
   2015 
   2016 /*
   2017  * sysctl helper routine for kern.somaxkva.  ensures that the given
   2018  * value is not too small.
   2019  * (XXX should we maybe make sure it's not too large as well?)
   2020  */
   2021 static int
   2022 sysctl_kern_somaxkva(SYSCTLFN_ARGS)
   2023 {
   2024 	int error, new_somaxkva;
   2025 	struct sysctlnode node;
   2026 
   2027 	new_somaxkva = somaxkva;
   2028 	node = *rnode;
   2029 	node.sysctl_data = &new_somaxkva;
   2030 	error = sysctl_lookup(SYSCTLFN_CALL(&node));
   2031 	if (error || newp == NULL)
   2032 		return (error);
   2033 
   2034 	if (new_somaxkva < (16 * 1024 * 1024)) /* sanity */
   2035 		return (EINVAL);
   2036 
   2037 	mutex_enter(&so_pendfree_lock);
   2038 	somaxkva = new_somaxkva;
   2039 	cv_broadcast(&socurkva_cv);
   2040 	mutex_exit(&so_pendfree_lock);
   2041 
   2042 	return (error);
   2043 }
   2044 
   2045 SYSCTL_SETUP(sysctl_kern_somaxkva_setup, "sysctl kern.somaxkva setup")
   2046 {
   2047 
   2048 	sysctl_createv(clog, 0, NULL, NULL,
   2049 		       CTLFLAG_PERMANENT,
   2050 		       CTLTYPE_NODE, "kern", NULL,
   2051 		       NULL, 0, NULL, 0,
   2052 		       CTL_KERN, CTL_EOL);
   2053 
   2054 	sysctl_createv(clog, 0, NULL, NULL,
   2055 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   2056 		       CTLTYPE_INT, "somaxkva",
   2057 		       SYSCTL_DESCR("Maximum amount of kernel memory to be "
   2058 				    "used for socket buffers"),
   2059 		       sysctl_kern_somaxkva, 0, NULL, 0,
   2060 		       CTL_KERN, KERN_SOMAXKVA, CTL_EOL);
   2061 }
   2062