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