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