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