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