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