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