Home | History | Annotate | Line # | Download | only in kern
uipc_socket.c revision 1.100
      1 /*	$NetBSD: uipc_socket.c,v 1.100 2004/04/25 16:42:41 simonb Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 2002 The NetBSD Foundation, Inc.
      5  * All rights reserved.
      6  *
      7  * This code is derived from software contributed to The NetBSD Foundation
      8  * by Jason R. Thorpe of Wasabi Systems, Inc.
      9  *
     10  * Redistribution and use in source and binary forms, with or without
     11  * modification, are permitted provided that the following conditions
     12  * are met:
     13  * 1. Redistributions of source code must retain the above copyright
     14  *    notice, this list of conditions and the following disclaimer.
     15  * 2. Redistributions in binary form must reproduce the above copyright
     16  *    notice, this list of conditions and the following disclaimer in the
     17  *    documentation and/or other materials provided with the distribution.
     18  * 3. All advertising materials mentioning features or use of this software
     19  *    must display the following acknowledgement:
     20  *	This product includes software developed by the NetBSD
     21  *	Foundation, Inc. and its contributors.
     22  * 4. Neither the name of The NetBSD Foundation nor the names of its
     23  *    contributors may be used to endorse or promote products derived
     24  *    from this software without specific prior written permission.
     25  *
     26  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
     27  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     28  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     29  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
     30  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     31  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     32  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     33  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     34  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     35  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     36  * POSSIBILITY OF SUCH DAMAGE.
     37  */
     38 
     39 /*
     40  * Copyright (c) 1982, 1986, 1988, 1990, 1993
     41  *	The Regents of the University of California.  All rights reserved.
     42  *
     43  * Redistribution and use in source and binary forms, with or without
     44  * modification, are permitted provided that the following conditions
     45  * are met:
     46  * 1. Redistributions of source code must retain the above copyright
     47  *    notice, this list of conditions and the following disclaimer.
     48  * 2. Redistributions in binary form must reproduce the above copyright
     49  *    notice, this list of conditions and the following disclaimer in the
     50  *    documentation and/or other materials provided with the distribution.
     51  * 3. Neither the name of the University nor the names of its contributors
     52  *    may be used to endorse or promote products derived from this software
     53  *    without specific prior written permission.
     54  *
     55  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     56  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     57  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     58  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     59  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     60  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     61  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     62  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     63  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     64  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     65  * SUCH DAMAGE.
     66  *
     67  *	@(#)uipc_socket.c	8.6 (Berkeley) 5/2/95
     68  */
     69 
     70 #include <sys/cdefs.h>
     71 __KERNEL_RCSID(0, "$NetBSD: uipc_socket.c,v 1.100 2004/04/25 16:42:41 simonb Exp $");
     72 
     73 #include "opt_sock_counters.h"
     74 #include "opt_sosend_loan.h"
     75 #include "opt_mbuftrace.h"
     76 #include "opt_somaxkva.h"
     77 
     78 #include <sys/param.h>
     79 #include <sys/systm.h>
     80 #include <sys/proc.h>
     81 #include <sys/file.h>
     82 #include <sys/malloc.h>
     83 #include <sys/mbuf.h>
     84 #include <sys/domain.h>
     85 #include <sys/kernel.h>
     86 #include <sys/protosw.h>
     87 #include <sys/socket.h>
     88 #include <sys/socketvar.h>
     89 #include <sys/signalvar.h>
     90 #include <sys/resourcevar.h>
     91 #include <sys/pool.h>
     92 #include <sys/event.h>
     93 #include <sys/poll.h>
     94 
     95 #include <uvm/uvm.h>
     96 
     97 POOL_INIT(socket_pool, sizeof(struct socket), 0, 0, 0, "sockpl", NULL);
     98 
     99 MALLOC_DEFINE(M_SOOPTS, "soopts", "socket options");
    100 MALLOC_DEFINE(M_SONAME, "soname", "socket name");
    101 
    102 extern int	somaxconn;			/* patchable (XXX sysctl) */
    103 int		somaxconn = SOMAXCONN;
    104 
    105 #ifdef SOSEND_COUNTERS
    106 #include <sys/device.h>
    107 
    108 struct evcnt sosend_loan_big = EVCNT_INITIALIZER(EVCNT_TYPE_MISC,
    109     NULL, "sosend", "loan big");
    110 struct evcnt sosend_copy_big = EVCNT_INITIALIZER(EVCNT_TYPE_MISC,
    111     NULL, "sosend", "copy big");
    112 struct evcnt sosend_copy_small = EVCNT_INITIALIZER(EVCNT_TYPE_MISC,
    113     NULL, "sosend", "copy small");
    114 struct evcnt sosend_kvalimit = EVCNT_INITIALIZER(EVCNT_TYPE_MISC,
    115     NULL, "sosend", "kva limit");
    116 
    117 #define	SOSEND_COUNTER_INCR(ev)		(ev)->ev_count++
    118 
    119 #else
    120 
    121 #define	SOSEND_COUNTER_INCR(ev)		/* nothing */
    122 
    123 #endif /* SOSEND_COUNTERS */
    124 
    125 void
    126 soinit(void)
    127 {
    128 
    129 	/* Set the initial adjusted socket buffer size. */
    130 	if (sb_max_set(sb_max))
    131 		panic("bad initial sb_max value: %lu\n", sb_max);
    132 
    133 #ifdef SOSEND_COUNTERS
    134 	evcnt_attach_static(&sosend_loan_big);
    135 	evcnt_attach_static(&sosend_copy_big);
    136 	evcnt_attach_static(&sosend_copy_small);
    137 	evcnt_attach_static(&sosend_kvalimit);
    138 #endif /* SOSEND_COUNTERS */
    139 }
    140 
    141 #ifdef SOSEND_NO_LOAN
    142 int use_sosend_loan = 0;
    143 #else
    144 int use_sosend_loan = 1;
    145 #endif
    146 
    147 struct simplelock so_pendfree_slock = SIMPLELOCK_INITIALIZER;
    148 struct mbuf *so_pendfree;
    149 
    150 #ifndef SOMAXKVA
    151 #define	SOMAXKVA (16 * 1024 * 1024)
    152 #endif
    153 int somaxkva = SOMAXKVA;
    154 int socurkva;
    155 int sokvawaiters;
    156 
    157 #define	SOCK_LOAN_THRESH	4096
    158 #define	SOCK_LOAN_CHUNK		65536
    159 
    160 static size_t sodopendfree(struct socket *);
    161 static size_t sodopendfreel(struct socket *);
    162 static __inline vsize_t sokvareserve(struct socket *, vsize_t);
    163 static __inline void sokvaunreserve(vsize_t);
    164 
    165 static __inline vsize_t
    166 sokvareserve(struct socket *so, vsize_t len)
    167 {
    168 	int s;
    169 	int error;
    170 
    171 	s = splvm();
    172 	simple_lock(&so_pendfree_slock);
    173 	while (socurkva + len > somaxkva) {
    174 		size_t freed;
    175 
    176 		/*
    177 		 * try to do pendfree.
    178 		 */
    179 
    180 		freed = sodopendfreel(so);
    181 
    182 		/*
    183 		 * if some kva was freed, try again.
    184 		 */
    185 
    186 		if (freed)
    187 			continue;
    188 
    189 		SOSEND_COUNTER_INCR(&sosend_kvalimit);
    190 		sokvawaiters++;
    191 		error = ltsleep(&socurkva, PVM | PCATCH, "sokva", 0,
    192 		    &so_pendfree_slock);
    193 		sokvawaiters--;
    194 		if (error) {
    195 			len = 0;
    196 			break;
    197 		}
    198 	}
    199 	socurkva += len;
    200 	simple_unlock(&so_pendfree_slock);
    201 	splx(s);
    202 	return len;
    203 }
    204 
    205 static __inline void
    206 sokvaunreserve(vsize_t len)
    207 {
    208 	int s;
    209 
    210 	s = splvm();
    211 	simple_lock(&so_pendfree_slock);
    212 	socurkva -= len;
    213 	if (sokvawaiters)
    214 		wakeup(&socurkva);
    215 	simple_unlock(&so_pendfree_slock);
    216 	splx(s);
    217 }
    218 
    219 /*
    220  * sokvaalloc: allocate kva for loan.
    221  */
    222 
    223 vaddr_t
    224 sokvaalloc(vsize_t len, struct socket *so)
    225 {
    226 	vaddr_t lva;
    227 
    228 	/*
    229 	 * reserve kva.
    230 	 */
    231 
    232 	if (sokvareserve(so, len) == 0)
    233 		return 0;
    234 
    235 	/*
    236 	 * allocate kva.
    237 	 */
    238 
    239 	lva = uvm_km_valloc_wait(kernel_map, len);
    240 	if (lva == 0) {
    241 		sokvaunreserve(len);
    242 		return (0);
    243 	}
    244 
    245 	return lva;
    246 }
    247 
    248 /*
    249  * sokvafree: free kva for loan.
    250  */
    251 
    252 void
    253 sokvafree(vaddr_t sva, vsize_t len)
    254 {
    255 
    256 	/*
    257 	 * free kva.
    258 	 */
    259 
    260 	uvm_km_free(kernel_map, sva, len);
    261 
    262 	/*
    263 	 * unreserve kva.
    264 	 */
    265 
    266 	sokvaunreserve(len);
    267 }
    268 
    269 static void
    270 sodoloanfree(struct vm_page **pgs, caddr_t buf, size_t size)
    271 {
    272 	vaddr_t va, sva, eva;
    273 	vsize_t len;
    274 	paddr_t pa;
    275 	int i, npgs;
    276 
    277 	eva = round_page((vaddr_t) buf + size);
    278 	sva = trunc_page((vaddr_t) buf);
    279 	len = eva - sva;
    280 	npgs = len >> PAGE_SHIFT;
    281 
    282 	if (__predict_false(pgs == NULL)) {
    283 		pgs = alloca(npgs * sizeof(*pgs));
    284 
    285 		for (i = 0, va = sva; va < eva; i++, va += PAGE_SIZE) {
    286 			if (pmap_extract(pmap_kernel(), va, &pa) == FALSE)
    287 				panic("sodoloanfree: va 0x%lx not mapped", va);
    288 			pgs[i] = PHYS_TO_VM_PAGE(pa);
    289 		}
    290 	}
    291 
    292 	pmap_kremove(sva, len);
    293 	pmap_update(pmap_kernel());
    294 	uvm_unloan(pgs, npgs, UVM_LOAN_TOPAGE);
    295 	sokvafree(sva, len);
    296 }
    297 
    298 static size_t
    299 sodopendfree(struct socket *so)
    300 {
    301 	int s;
    302 	size_t rv;
    303 
    304 	s = splvm();
    305 	simple_lock(&so_pendfree_slock);
    306 	rv = sodopendfreel(so);
    307 	simple_unlock(&so_pendfree_slock);
    308 	splx(s);
    309 
    310 	return rv;
    311 }
    312 
    313 /*
    314  * sodopendfreel: free mbufs on "pendfree" list.
    315  * unlock and relock so_pendfree_slock when freeing mbufs.
    316  *
    317  * => called with so_pendfree_slock held.
    318  * => called at splvm.
    319  */
    320 
    321 static size_t
    322 sodopendfreel(struct socket *so)
    323 {
    324 	size_t rv = 0;
    325 
    326 	LOCK_ASSERT(simple_lock_held(&so_pendfree_slock));
    327 
    328 	for (;;) {
    329 		struct mbuf *m;
    330 		struct mbuf *next;
    331 
    332 		m = so_pendfree;
    333 		if (m == NULL)
    334 			break;
    335 		so_pendfree = NULL;
    336 		simple_unlock(&so_pendfree_slock);
    337 		/* XXX splx */
    338 
    339 		for (; m != NULL; m = next) {
    340 			next = m->m_next;
    341 
    342 			rv += m->m_ext.ext_size;
    343 			sodoloanfree((m->m_flags & M_EXT_PAGES) ?
    344 			    m->m_ext.ext_pgs : NULL, m->m_ext.ext_buf,
    345 			    m->m_ext.ext_size);
    346 			pool_cache_put(&mbpool_cache, m);
    347 		}
    348 
    349 		/* XXX splvm */
    350 		simple_lock(&so_pendfree_slock);
    351 	}
    352 
    353 	return (rv);
    354 }
    355 
    356 void
    357 soloanfree(struct mbuf *m, caddr_t buf, size_t size, void *arg)
    358 {
    359 	int s;
    360 
    361 	if (m == NULL) {
    362 
    363 		/*
    364 		 * called from MEXTREMOVE.
    365 		 */
    366 
    367 		sodoloanfree(NULL, buf, size);
    368 		return;
    369 	}
    370 
    371 	/*
    372 	 * postpone freeing mbuf.
    373 	 *
    374 	 * we can't do it in interrupt context
    375 	 * because we need to put kva back to kernel_map.
    376 	 */
    377 
    378 	s = splvm();
    379 	simple_lock(&so_pendfree_slock);
    380 	m->m_next = so_pendfree;
    381 	so_pendfree = m;
    382 	if (sokvawaiters)
    383 		wakeup(&socurkva);
    384 	simple_unlock(&so_pendfree_slock);
    385 	splx(s);
    386 }
    387 
    388 static long
    389 sosend_loan(struct socket *so, struct uio *uio, struct mbuf *m, long space)
    390 {
    391 	struct iovec *iov = uio->uio_iov;
    392 	vaddr_t sva, eva;
    393 	vsize_t len;
    394 	vaddr_t lva, va;
    395 	int npgs, i, error;
    396 
    397 	if (uio->uio_segflg != UIO_USERSPACE)
    398 		return (0);
    399 
    400 	if (iov->iov_len < (size_t) space)
    401 		space = iov->iov_len;
    402 	if (space > SOCK_LOAN_CHUNK)
    403 		space = SOCK_LOAN_CHUNK;
    404 
    405 	eva = round_page((vaddr_t) iov->iov_base + space);
    406 	sva = trunc_page((vaddr_t) iov->iov_base);
    407 	len = eva - sva;
    408 	npgs = len >> PAGE_SHIFT;
    409 
    410 	/* XXX KDASSERT */
    411 	KASSERT(npgs <= M_EXT_MAXPAGES);
    412 
    413 	lva = sokvaalloc(len, so);
    414 	if (lva == 0)
    415 		return 0;
    416 
    417 	error = uvm_loan(&uio->uio_procp->p_vmspace->vm_map, sva, len,
    418 	    m->m_ext.ext_pgs, UVM_LOAN_TOPAGE);
    419 	if (error) {
    420 		sokvafree(lva, len);
    421 		return (0);
    422 	}
    423 
    424 	for (i = 0, va = lva; i < npgs; i++, va += PAGE_SIZE)
    425 		pmap_kenter_pa(va, VM_PAGE_TO_PHYS(m->m_ext.ext_pgs[i]),
    426 		    VM_PROT_READ);
    427 	pmap_update(pmap_kernel());
    428 
    429 	lva += (vaddr_t) iov->iov_base & PAGE_MASK;
    430 
    431 	MEXTADD(m, (caddr_t) lva, space, M_MBUF, soloanfree, so);
    432 	m->m_flags |= M_EXT_PAGES | M_EXT_ROMAP;
    433 
    434 	uio->uio_resid -= space;
    435 	/* uio_offset not updated, not set/used for write(2) */
    436 	uio->uio_iov->iov_base = (caddr_t) uio->uio_iov->iov_base + space;
    437 	uio->uio_iov->iov_len -= space;
    438 	if (uio->uio_iov->iov_len == 0) {
    439 		uio->uio_iov++;
    440 		uio->uio_iovcnt--;
    441 	}
    442 
    443 	return (space);
    444 }
    445 
    446 /*
    447  * Socket operation routines.
    448  * These routines are called by the routines in
    449  * sys_socket.c or from a system process, and
    450  * implement the semantics of socket operations by
    451  * switching out to the protocol specific routines.
    452  */
    453 /*ARGSUSED*/
    454 int
    455 socreate(int dom, struct socket **aso, int type, int proto)
    456 {
    457 	struct proc	*p;
    458 	const struct protosw	*prp;
    459 	struct socket	*so;
    460 	int		error, s;
    461 
    462 	p = curproc;		/* XXX */
    463 	if (proto)
    464 		prp = pffindproto(dom, proto, type);
    465 	else
    466 		prp = pffindtype(dom, type);
    467 	if (prp == 0 || prp->pr_usrreq == 0)
    468 		return (EPROTONOSUPPORT);
    469 	if (prp->pr_type != type)
    470 		return (EPROTOTYPE);
    471 	s = splsoftnet();
    472 	so = pool_get(&socket_pool, PR_WAITOK);
    473 	memset((caddr_t)so, 0, sizeof(*so));
    474 	TAILQ_INIT(&so->so_q0);
    475 	TAILQ_INIT(&so->so_q);
    476 	so->so_type = type;
    477 	so->so_proto = prp;
    478 	so->so_send = sosend;
    479 	so->so_receive = soreceive;
    480 #ifdef MBUFTRACE
    481 	so->so_rcv.sb_mowner = &prp->pr_domain->dom_mowner;
    482 	so->so_snd.sb_mowner = &prp->pr_domain->dom_mowner;
    483 	so->so_mowner = &prp->pr_domain->dom_mowner;
    484 #endif
    485 	if (p != 0)
    486 		so->so_uid = p->p_ucred->cr_uid;
    487 	else
    488 		so->so_uid = UID_MAX;
    489 	error = (*prp->pr_usrreq)(so, PRU_ATTACH, (struct mbuf *)0,
    490 	    (struct mbuf *)(long)proto, (struct mbuf *)0, p);
    491 	if (error) {
    492 		so->so_state |= SS_NOFDREF;
    493 		sofree(so);
    494 		splx(s);
    495 		return (error);
    496 	}
    497 	splx(s);
    498 	*aso = so;
    499 	return (0);
    500 }
    501 
    502 int
    503 sobind(struct socket *so, struct mbuf *nam, struct proc *p)
    504 {
    505 	int	s, error;
    506 
    507 	s = splsoftnet();
    508 	error = (*so->so_proto->pr_usrreq)(so, PRU_BIND, (struct mbuf *)0,
    509 	    nam, (struct mbuf *)0, p);
    510 	splx(s);
    511 	return (error);
    512 }
    513 
    514 int
    515 solisten(struct socket *so, int backlog)
    516 {
    517 	int	s, error;
    518 
    519 	s = splsoftnet();
    520 	error = (*so->so_proto->pr_usrreq)(so, PRU_LISTEN, (struct mbuf *)0,
    521 	    (struct mbuf *)0, (struct mbuf *)0, (struct proc *)0);
    522 	if (error) {
    523 		splx(s);
    524 		return (error);
    525 	}
    526 	if (TAILQ_EMPTY(&so->so_q))
    527 		so->so_options |= SO_ACCEPTCONN;
    528 	if (backlog < 0)
    529 		backlog = 0;
    530 	so->so_qlimit = min(backlog, somaxconn);
    531 	splx(s);
    532 	return (0);
    533 }
    534 
    535 void
    536 sofree(struct socket *so)
    537 {
    538 
    539 	if (so->so_pcb || (so->so_state & SS_NOFDREF) == 0)
    540 		return;
    541 	if (so->so_head) {
    542 		/*
    543 		 * We must not decommission a socket that's on the accept(2)
    544 		 * queue.  If we do, then accept(2) may hang after select(2)
    545 		 * indicated that the listening socket was ready.
    546 		 */
    547 		if (!soqremque(so, 0))
    548 			return;
    549 	}
    550 	if (so->so_rcv.sb_hiwat)
    551 		(void)chgsbsize(so->so_uid, &so->so_rcv.sb_hiwat, 0,
    552 		    RLIM_INFINITY);
    553 	if (so->so_snd.sb_hiwat)
    554 		(void)chgsbsize(so->so_uid, &so->so_snd.sb_hiwat, 0,
    555 		    RLIM_INFINITY);
    556 	sbrelease(&so->so_snd, so);
    557 	sorflush(so);
    558 	pool_put(&socket_pool, so);
    559 }
    560 
    561 /*
    562  * Close a socket on last file table reference removal.
    563  * Initiate disconnect if connected.
    564  * Free socket when disconnect complete.
    565  */
    566 int
    567 soclose(struct socket *so)
    568 {
    569 	struct socket	*so2;
    570 	int		s, error;
    571 
    572 	error = 0;
    573 	s = splsoftnet();		/* conservative */
    574 	if (so->so_options & SO_ACCEPTCONN) {
    575 		while ((so2 = TAILQ_FIRST(&so->so_q0)) != 0) {
    576 			(void) soqremque(so2, 0);
    577 			(void) soabort(so2);
    578 		}
    579 		while ((so2 = TAILQ_FIRST(&so->so_q)) != 0) {
    580 			(void) soqremque(so2, 1);
    581 			(void) soabort(so2);
    582 		}
    583 	}
    584 	if (so->so_pcb == 0)
    585 		goto discard;
    586 	if (so->so_state & SS_ISCONNECTED) {
    587 		if ((so->so_state & SS_ISDISCONNECTING) == 0) {
    588 			error = sodisconnect(so);
    589 			if (error)
    590 				goto drop;
    591 		}
    592 		if (so->so_options & SO_LINGER) {
    593 			if ((so->so_state & SS_ISDISCONNECTING) &&
    594 			    (so->so_state & SS_NBIO))
    595 				goto drop;
    596 			while (so->so_state & SS_ISCONNECTED) {
    597 				error = tsleep((caddr_t)&so->so_timeo,
    598 					       PSOCK | PCATCH, netcls,
    599 					       so->so_linger * hz);
    600 				if (error)
    601 					break;
    602 			}
    603 		}
    604 	}
    605  drop:
    606 	if (so->so_pcb) {
    607 		int error2 = (*so->so_proto->pr_usrreq)(so, PRU_DETACH,
    608 		    (struct mbuf *)0, (struct mbuf *)0, (struct mbuf *)0,
    609 		    (struct proc *)0);
    610 		if (error == 0)
    611 			error = error2;
    612 	}
    613  discard:
    614 	if (so->so_state & SS_NOFDREF)
    615 		panic("soclose: NOFDREF");
    616 	so->so_state |= SS_NOFDREF;
    617 	sofree(so);
    618 	splx(s);
    619 	return (error);
    620 }
    621 
    622 /*
    623  * Must be called at splsoftnet...
    624  */
    625 int
    626 soabort(struct socket *so)
    627 {
    628 
    629 	return (*so->so_proto->pr_usrreq)(so, PRU_ABORT, (struct mbuf *)0,
    630 	    (struct mbuf *)0, (struct mbuf *)0, (struct proc *)0);
    631 }
    632 
    633 int
    634 soaccept(struct socket *so, struct mbuf *nam)
    635 {
    636 	int	s, error;
    637 
    638 	error = 0;
    639 	s = splsoftnet();
    640 	if ((so->so_state & SS_NOFDREF) == 0)
    641 		panic("soaccept: !NOFDREF");
    642 	so->so_state &= ~SS_NOFDREF;
    643 	if ((so->so_state & SS_ISDISCONNECTED) == 0 ||
    644 	    (so->so_proto->pr_flags & PR_ABRTACPTDIS) == 0)
    645 		error = (*so->so_proto->pr_usrreq)(so, PRU_ACCEPT,
    646 		    (struct mbuf *)0, nam, (struct mbuf *)0, (struct proc *)0);
    647 	else
    648 		error = ECONNABORTED;
    649 
    650 	splx(s);
    651 	return (error);
    652 }
    653 
    654 int
    655 soconnect(struct socket *so, struct mbuf *nam)
    656 {
    657 	struct proc	*p;
    658 	int		s, error;
    659 
    660 	p = curproc;		/* XXX */
    661 	if (so->so_options & SO_ACCEPTCONN)
    662 		return (EOPNOTSUPP);
    663 	s = splsoftnet();
    664 	/*
    665 	 * If protocol is connection-based, can only connect once.
    666 	 * Otherwise, if connected, try to disconnect first.
    667 	 * This allows user to disconnect by connecting to, e.g.,
    668 	 * a null address.
    669 	 */
    670 	if (so->so_state & (SS_ISCONNECTED|SS_ISCONNECTING) &&
    671 	    ((so->so_proto->pr_flags & PR_CONNREQUIRED) ||
    672 	    (error = sodisconnect(so))))
    673 		error = EISCONN;
    674 	else
    675 		error = (*so->so_proto->pr_usrreq)(so, PRU_CONNECT,
    676 		    (struct mbuf *)0, nam, (struct mbuf *)0, p);
    677 	splx(s);
    678 	return (error);
    679 }
    680 
    681 int
    682 soconnect2(struct socket *so1, struct socket *so2)
    683 {
    684 	int	s, error;
    685 
    686 	s = splsoftnet();
    687 	error = (*so1->so_proto->pr_usrreq)(so1, PRU_CONNECT2,
    688 	    (struct mbuf *)0, (struct mbuf *)so2, (struct mbuf *)0,
    689 	    (struct proc *)0);
    690 	splx(s);
    691 	return (error);
    692 }
    693 
    694 int
    695 sodisconnect(struct socket *so)
    696 {
    697 	int	s, error;
    698 
    699 	s = splsoftnet();
    700 	if ((so->so_state & SS_ISCONNECTED) == 0) {
    701 		error = ENOTCONN;
    702 		goto bad;
    703 	}
    704 	if (so->so_state & SS_ISDISCONNECTING) {
    705 		error = EALREADY;
    706 		goto bad;
    707 	}
    708 	error = (*so->so_proto->pr_usrreq)(so, PRU_DISCONNECT,
    709 	    (struct mbuf *)0, (struct mbuf *)0, (struct mbuf *)0,
    710 	    (struct proc *)0);
    711  bad:
    712 	splx(s);
    713 	sodopendfree(so);
    714 	return (error);
    715 }
    716 
    717 #define	SBLOCKWAIT(f)	(((f) & MSG_DONTWAIT) ? M_NOWAIT : M_WAITOK)
    718 /*
    719  * Send on a socket.
    720  * If send must go all at once and message is larger than
    721  * send buffering, then hard error.
    722  * Lock against other senders.
    723  * If must go all at once and not enough room now, then
    724  * inform user that this would block and do nothing.
    725  * Otherwise, if nonblocking, send as much as possible.
    726  * The data to be sent is described by "uio" if nonzero,
    727  * otherwise by the mbuf chain "top" (which must be null
    728  * if uio is not).  Data provided in mbuf chain must be small
    729  * enough to send all at once.
    730  *
    731  * Returns nonzero on error, timeout or signal; callers
    732  * must check for short counts if EINTR/ERESTART are returned.
    733  * Data and control buffers are freed on return.
    734  */
    735 int
    736 sosend(struct socket *so, struct mbuf *addr, struct uio *uio, struct mbuf *top,
    737 	struct mbuf *control, int flags)
    738 {
    739 	struct proc	*p;
    740 	struct mbuf	**mp, *m;
    741 	long		space, len, resid, clen, mlen;
    742 	int		error, s, dontroute, atomic;
    743 
    744 	sodopendfree(so);
    745 
    746 	p = curproc;		/* XXX */
    747 	clen = 0;
    748 	atomic = sosendallatonce(so) || top;
    749 	if (uio)
    750 		resid = uio->uio_resid;
    751 	else
    752 		resid = top->m_pkthdr.len;
    753 	/*
    754 	 * In theory resid should be unsigned.
    755 	 * However, space must be signed, as it might be less than 0
    756 	 * if we over-committed, and we must use a signed comparison
    757 	 * of space and resid.  On the other hand, a negative resid
    758 	 * causes us to loop sending 0-length segments to the protocol.
    759 	 */
    760 	if (resid < 0) {
    761 		error = EINVAL;
    762 		goto out;
    763 	}
    764 	dontroute =
    765 	    (flags & MSG_DONTROUTE) && (so->so_options & SO_DONTROUTE) == 0 &&
    766 	    (so->so_proto->pr_flags & PR_ATOMIC);
    767 	p->p_stats->p_ru.ru_msgsnd++;
    768 	if (control)
    769 		clen = control->m_len;
    770 #define	snderr(errno)	{ error = errno; splx(s); goto release; }
    771 
    772  restart:
    773 	if ((error = sblock(&so->so_snd, SBLOCKWAIT(flags))) != 0)
    774 		goto out;
    775 	do {
    776 		s = splsoftnet();
    777 		if (so->so_state & SS_CANTSENDMORE)
    778 			snderr(EPIPE);
    779 		if (so->so_error) {
    780 			error = so->so_error;
    781 			so->so_error = 0;
    782 			splx(s);
    783 			goto release;
    784 		}
    785 		if ((so->so_state & SS_ISCONNECTED) == 0) {
    786 			if (so->so_proto->pr_flags & PR_CONNREQUIRED) {
    787 				if ((so->so_state & SS_ISCONFIRMING) == 0 &&
    788 				    !(resid == 0 && clen != 0))
    789 					snderr(ENOTCONN);
    790 			} else if (addr == 0)
    791 				snderr(EDESTADDRREQ);
    792 		}
    793 		space = sbspace(&so->so_snd);
    794 		if (flags & MSG_OOB)
    795 			space += 1024;
    796 		if ((atomic && resid > so->so_snd.sb_hiwat) ||
    797 		    clen > so->so_snd.sb_hiwat)
    798 			snderr(EMSGSIZE);
    799 		if (space < resid + clen &&
    800 		    (atomic || space < so->so_snd.sb_lowat || space < clen)) {
    801 			if (so->so_state & SS_NBIO)
    802 				snderr(EWOULDBLOCK);
    803 			sbunlock(&so->so_snd);
    804 			error = sbwait(&so->so_snd);
    805 			splx(s);
    806 			if (error)
    807 				goto out;
    808 			goto restart;
    809 		}
    810 		splx(s);
    811 		mp = &top;
    812 		space -= clen;
    813 		do {
    814 			if (uio == NULL) {
    815 				/*
    816 				 * Data is prepackaged in "top".
    817 				 */
    818 				resid = 0;
    819 				if (flags & MSG_EOR)
    820 					top->m_flags |= M_EOR;
    821 			} else do {
    822 				if (top == 0) {
    823 					m = m_gethdr(M_WAIT, MT_DATA);
    824 					mlen = MHLEN;
    825 					m->m_pkthdr.len = 0;
    826 					m->m_pkthdr.rcvif = (struct ifnet *)0;
    827 				} else {
    828 					m = m_get(M_WAIT, MT_DATA);
    829 					mlen = MLEN;
    830 				}
    831 				MCLAIM(m, so->so_snd.sb_mowner);
    832 				if (use_sosend_loan &&
    833 				    uio->uio_iov->iov_len >= SOCK_LOAN_THRESH &&
    834 				    space >= SOCK_LOAN_THRESH &&
    835 				    (len = sosend_loan(so, uio, m,
    836 						       space)) != 0) {
    837 					SOSEND_COUNTER_INCR(&sosend_loan_big);
    838 					space -= len;
    839 					goto have_data;
    840 				}
    841 				if (resid >= MINCLSIZE && space >= MCLBYTES) {
    842 					SOSEND_COUNTER_INCR(&sosend_copy_big);
    843 					m_clget(m, M_WAIT);
    844 					if ((m->m_flags & M_EXT) == 0)
    845 						goto nopages;
    846 					mlen = MCLBYTES;
    847 					if (atomic && top == 0) {
    848 						len = lmin(MCLBYTES - max_hdr,
    849 						    resid);
    850 						m->m_data += max_hdr;
    851 					} else
    852 						len = lmin(MCLBYTES, resid);
    853 					space -= len;
    854 				} else {
    855  nopages:
    856 					SOSEND_COUNTER_INCR(&sosend_copy_small);
    857 					len = lmin(lmin(mlen, resid), space);
    858 					space -= len;
    859 					/*
    860 					 * For datagram protocols, leave room
    861 					 * for protocol headers in first mbuf.
    862 					 */
    863 					if (atomic && top == 0 && len < mlen)
    864 						MH_ALIGN(m, len);
    865 				}
    866 				error = uiomove(mtod(m, caddr_t), (int)len,
    867 				    uio);
    868  have_data:
    869 				resid = uio->uio_resid;
    870 				m->m_len = len;
    871 				*mp = m;
    872 				top->m_pkthdr.len += len;
    873 				if (error)
    874 					goto release;
    875 				mp = &m->m_next;
    876 				if (resid <= 0) {
    877 					if (flags & MSG_EOR)
    878 						top->m_flags |= M_EOR;
    879 					break;
    880 				}
    881 			} while (space > 0 && atomic);
    882 
    883 			s = splsoftnet();
    884 
    885 			if (so->so_state & SS_CANTSENDMORE)
    886 				snderr(EPIPE);
    887 
    888 			if (dontroute)
    889 				so->so_options |= SO_DONTROUTE;
    890 			if (resid > 0)
    891 				so->so_state |= SS_MORETOCOME;
    892 			error = (*so->so_proto->pr_usrreq)(so,
    893 			    (flags & MSG_OOB) ? PRU_SENDOOB : PRU_SEND,
    894 			    top, addr, control, p);
    895 			if (dontroute)
    896 				so->so_options &= ~SO_DONTROUTE;
    897 			if (resid > 0)
    898 				so->so_state &= ~SS_MORETOCOME;
    899 			splx(s);
    900 
    901 			clen = 0;
    902 			control = 0;
    903 			top = 0;
    904 			mp = &top;
    905 			if (error)
    906 				goto release;
    907 		} while (resid && space > 0);
    908 	} while (resid);
    909 
    910  release:
    911 	sbunlock(&so->so_snd);
    912  out:
    913 	if (top)
    914 		m_freem(top);
    915 	if (control)
    916 		m_freem(control);
    917 	return (error);
    918 }
    919 
    920 /*
    921  * Implement receive operations on a socket.
    922  * We depend on the way that records are added to the sockbuf
    923  * by sbappend*.  In particular, each record (mbufs linked through m_next)
    924  * must begin with an address if the protocol so specifies,
    925  * followed by an optional mbuf or mbufs containing ancillary data,
    926  * and then zero or more mbufs of data.
    927  * In order to avoid blocking network interrupts for the entire time here,
    928  * we splx() while doing the actual copy to user space.
    929  * Although the sockbuf is locked, new data may still be appended,
    930  * and thus we must maintain consistency of the sockbuf during that time.
    931  *
    932  * The caller may receive the data as a single mbuf chain by supplying
    933  * an mbuf **mp0 for use in returning the chain.  The uio is then used
    934  * only for the count in uio_resid.
    935  */
    936 int
    937 soreceive(struct socket *so, struct mbuf **paddr, struct uio *uio,
    938 	struct mbuf **mp0, struct mbuf **controlp, int *flagsp)
    939 {
    940 	struct mbuf	*m, **mp;
    941 	int		flags, len, error, s, offset, moff, type, orig_resid;
    942 	const struct protosw	*pr;
    943 	struct mbuf	*nextrecord;
    944 	int		mbuf_removed = 0;
    945 
    946 	pr = so->so_proto;
    947 	mp = mp0;
    948 	type = 0;
    949 	orig_resid = uio->uio_resid;
    950 	if (paddr)
    951 		*paddr = 0;
    952 	if (controlp)
    953 		*controlp = 0;
    954 	if (flagsp)
    955 		flags = *flagsp &~ MSG_EOR;
    956 	else
    957 		flags = 0;
    958 
    959 	if ((flags & MSG_DONTWAIT) == 0)
    960 		sodopendfree(so);
    961 
    962 	if (flags & MSG_OOB) {
    963 		m = m_get(M_WAIT, MT_DATA);
    964 		error = (*pr->pr_usrreq)(so, PRU_RCVOOB, m,
    965 		    (struct mbuf *)(long)(flags & MSG_PEEK), (struct mbuf *)0,
    966 		    (struct proc *)0);
    967 		if (error)
    968 			goto bad;
    969 		do {
    970 			error = uiomove(mtod(m, caddr_t),
    971 			    (int) min(uio->uio_resid, m->m_len), uio);
    972 			m = m_free(m);
    973 		} while (uio->uio_resid && error == 0 && m);
    974  bad:
    975 		if (m)
    976 			m_freem(m);
    977 		return (error);
    978 	}
    979 	if (mp)
    980 		*mp = (struct mbuf *)0;
    981 	if (so->so_state & SS_ISCONFIRMING && uio->uio_resid)
    982 		(*pr->pr_usrreq)(so, PRU_RCVD, (struct mbuf *)0,
    983 		    (struct mbuf *)0, (struct mbuf *)0, (struct proc *)0);
    984 
    985  restart:
    986 	if ((error = sblock(&so->so_rcv, SBLOCKWAIT(flags))) != 0)
    987 		return (error);
    988 	s = splsoftnet();
    989 
    990 	m = so->so_rcv.sb_mb;
    991 	/*
    992 	 * If we have less data than requested, block awaiting more
    993 	 * (subject to any timeout) if:
    994 	 *   1. the current count is less than the low water mark,
    995 	 *   2. MSG_WAITALL is set, and it is possible to do the entire
    996 	 *	receive operation at once if we block (resid <= hiwat), or
    997 	 *   3. MSG_DONTWAIT is not set.
    998 	 * If MSG_WAITALL is set but resid is larger than the receive buffer,
    999 	 * we have to do the receive in sections, and thus risk returning
   1000 	 * a short count if a timeout or signal occurs after we start.
   1001 	 */
   1002 	if (m == 0 || (((flags & MSG_DONTWAIT) == 0 &&
   1003 	    so->so_rcv.sb_cc < uio->uio_resid) &&
   1004 	    (so->so_rcv.sb_cc < so->so_rcv.sb_lowat ||
   1005 	    ((flags & MSG_WAITALL) && uio->uio_resid <= so->so_rcv.sb_hiwat)) &&
   1006 	    m->m_nextpkt == 0 && (pr->pr_flags & PR_ATOMIC) == 0)) {
   1007 #ifdef DIAGNOSTIC
   1008 		if (m == 0 && so->so_rcv.sb_cc)
   1009 			panic("receive 1");
   1010 #endif
   1011 		if (so->so_error) {
   1012 			if (m)
   1013 				goto dontblock;
   1014 			error = so->so_error;
   1015 			if ((flags & MSG_PEEK) == 0)
   1016 				so->so_error = 0;
   1017 			goto release;
   1018 		}
   1019 		if (so->so_state & SS_CANTRCVMORE) {
   1020 			if (m)
   1021 				goto dontblock;
   1022 			else
   1023 				goto release;
   1024 		}
   1025 		for (; m; m = m->m_next)
   1026 			if (m->m_type == MT_OOBDATA  || (m->m_flags & M_EOR)) {
   1027 				m = so->so_rcv.sb_mb;
   1028 				goto dontblock;
   1029 			}
   1030 		if ((so->so_state & (SS_ISCONNECTED|SS_ISCONNECTING)) == 0 &&
   1031 		    (so->so_proto->pr_flags & PR_CONNREQUIRED)) {
   1032 			error = ENOTCONN;
   1033 			goto release;
   1034 		}
   1035 		if (uio->uio_resid == 0)
   1036 			goto release;
   1037 		if ((so->so_state & SS_NBIO) || (flags & MSG_DONTWAIT)) {
   1038 			error = EWOULDBLOCK;
   1039 			goto release;
   1040 		}
   1041 		SBLASTRECORDCHK(&so->so_rcv, "soreceive sbwait 1");
   1042 		SBLASTMBUFCHK(&so->so_rcv, "soreceive sbwait 1");
   1043 		sbunlock(&so->so_rcv);
   1044 		error = sbwait(&so->so_rcv);
   1045 		splx(s);
   1046 		if (error)
   1047 			return (error);
   1048 		goto restart;
   1049 	}
   1050  dontblock:
   1051 	/*
   1052 	 * On entry here, m points to the first record of the socket buffer.
   1053 	 * While we process the initial mbufs containing address and control
   1054 	 * info, we save a copy of m->m_nextpkt into nextrecord.
   1055 	 */
   1056 #ifdef notyet /* XXXX */
   1057 	if (uio->uio_procp)
   1058 		uio->uio_procp->p_stats->p_ru.ru_msgrcv++;
   1059 #endif
   1060 	KASSERT(m == so->so_rcv.sb_mb);
   1061 	SBLASTRECORDCHK(&so->so_rcv, "soreceive 1");
   1062 	SBLASTMBUFCHK(&so->so_rcv, "soreceive 1");
   1063 	nextrecord = m->m_nextpkt;
   1064 	if (pr->pr_flags & PR_ADDR) {
   1065 #ifdef DIAGNOSTIC
   1066 		if (m->m_type != MT_SONAME)
   1067 			panic("receive 1a");
   1068 #endif
   1069 		orig_resid = 0;
   1070 		if (flags & MSG_PEEK) {
   1071 			if (paddr)
   1072 				*paddr = m_copy(m, 0, m->m_len);
   1073 			m = m->m_next;
   1074 		} else {
   1075 			sbfree(&so->so_rcv, m);
   1076 			mbuf_removed = 1;
   1077 			if (paddr) {
   1078 				*paddr = m;
   1079 				so->so_rcv.sb_mb = m->m_next;
   1080 				m->m_next = 0;
   1081 				m = so->so_rcv.sb_mb;
   1082 			} else {
   1083 				MFREE(m, so->so_rcv.sb_mb);
   1084 				m = so->so_rcv.sb_mb;
   1085 			}
   1086 		}
   1087 	}
   1088 	while (m && m->m_type == MT_CONTROL && error == 0) {
   1089 		if (flags & MSG_PEEK) {
   1090 			if (controlp)
   1091 				*controlp = m_copy(m, 0, m->m_len);
   1092 			m = m->m_next;
   1093 		} else {
   1094 			sbfree(&so->so_rcv, m);
   1095 			mbuf_removed = 1;
   1096 			if (controlp) {
   1097 				if (pr->pr_domain->dom_externalize &&
   1098 				    mtod(m, struct cmsghdr *)->cmsg_type ==
   1099 				    SCM_RIGHTS)
   1100 					error = (*pr->pr_domain->dom_externalize)(m);
   1101 				*controlp = m;
   1102 				so->so_rcv.sb_mb = m->m_next;
   1103 				m->m_next = 0;
   1104 				m = so->so_rcv.sb_mb;
   1105 			} else {
   1106 				MFREE(m, so->so_rcv.sb_mb);
   1107 				m = so->so_rcv.sb_mb;
   1108 			}
   1109 		}
   1110 		if (controlp) {
   1111 			orig_resid = 0;
   1112 			controlp = &(*controlp)->m_next;
   1113 		}
   1114 	}
   1115 
   1116 	/*
   1117 	 * If m is non-NULL, we have some data to read.  From now on,
   1118 	 * make sure to keep sb_lastrecord consistent when working on
   1119 	 * the last packet on the chain (nextrecord == NULL) and we
   1120 	 * change m->m_nextpkt.
   1121 	 */
   1122 	if (m) {
   1123 		if ((flags & MSG_PEEK) == 0) {
   1124 			m->m_nextpkt = nextrecord;
   1125 			/*
   1126 			 * If nextrecord == NULL (this is a single chain),
   1127 			 * then sb_lastrecord may not be valid here if m
   1128 			 * was changed earlier.
   1129 			 */
   1130 			if (nextrecord == NULL) {
   1131 				KASSERT(so->so_rcv.sb_mb == m);
   1132 				so->so_rcv.sb_lastrecord = m;
   1133 			}
   1134 		}
   1135 		type = m->m_type;
   1136 		if (type == MT_OOBDATA)
   1137 			flags |= MSG_OOB;
   1138 	} else {
   1139 		if ((flags & MSG_PEEK) == 0) {
   1140 			KASSERT(so->so_rcv.sb_mb == m);
   1141 			so->so_rcv.sb_mb = nextrecord;
   1142 			SB_EMPTY_FIXUP(&so->so_rcv);
   1143 		}
   1144 	}
   1145 	SBLASTRECORDCHK(&so->so_rcv, "soreceive 2");
   1146 	SBLASTMBUFCHK(&so->so_rcv, "soreceive 2");
   1147 
   1148 	moff = 0;
   1149 	offset = 0;
   1150 	while (m && uio->uio_resid > 0 && error == 0) {
   1151 		if (m->m_type == MT_OOBDATA) {
   1152 			if (type != MT_OOBDATA)
   1153 				break;
   1154 		} else if (type == MT_OOBDATA)
   1155 			break;
   1156 #ifdef DIAGNOSTIC
   1157 		else if (m->m_type != MT_DATA && m->m_type != MT_HEADER)
   1158 			panic("receive 3");
   1159 #endif
   1160 		so->so_state &= ~SS_RCVATMARK;
   1161 		len = uio->uio_resid;
   1162 		if (so->so_oobmark && len > so->so_oobmark - offset)
   1163 			len = so->so_oobmark - offset;
   1164 		if (len > m->m_len - moff)
   1165 			len = m->m_len - moff;
   1166 		/*
   1167 		 * If mp is set, just pass back the mbufs.
   1168 		 * Otherwise copy them out via the uio, then free.
   1169 		 * Sockbuf must be consistent here (points to current mbuf,
   1170 		 * it points to next record) when we drop priority;
   1171 		 * we must note any additions to the sockbuf when we
   1172 		 * block interrupts again.
   1173 		 */
   1174 		if (mp == 0) {
   1175 			SBLASTRECORDCHK(&so->so_rcv, "soreceive uiomove");
   1176 			SBLASTMBUFCHK(&so->so_rcv, "soreceive uiomove");
   1177 			splx(s);
   1178 			error = uiomove(mtod(m, caddr_t) + moff, (int)len, uio);
   1179 			s = splsoftnet();
   1180 			if (error) {
   1181 				/*
   1182 				 * If any part of the record has been removed
   1183 				 * (such as the MT_SONAME mbuf, which will
   1184 				 * happen when PR_ADDR, and thus also
   1185 				 * PR_ATOMIC, is set), then drop the entire
   1186 				 * record to maintain the atomicity of the
   1187 				 * receive operation.
   1188 				 *
   1189 				 * This avoids a later panic("receive 1a")
   1190 				 * when compiled with DIAGNOSTIC.
   1191 				 */
   1192 				if (m && mbuf_removed
   1193 				    && (pr->pr_flags & PR_ATOMIC))
   1194 					(void) sbdroprecord(&so->so_rcv);
   1195 
   1196 				goto release;
   1197 			}
   1198 		} else
   1199 			uio->uio_resid -= len;
   1200 		if (len == m->m_len - moff) {
   1201 			if (m->m_flags & M_EOR)
   1202 				flags |= MSG_EOR;
   1203 			if (flags & MSG_PEEK) {
   1204 				m = m->m_next;
   1205 				moff = 0;
   1206 			} else {
   1207 				nextrecord = m->m_nextpkt;
   1208 				sbfree(&so->so_rcv, m);
   1209 				if (mp) {
   1210 					*mp = m;
   1211 					mp = &m->m_next;
   1212 					so->so_rcv.sb_mb = m = m->m_next;
   1213 					*mp = (struct mbuf *)0;
   1214 				} else {
   1215 					MFREE(m, so->so_rcv.sb_mb);
   1216 					m = so->so_rcv.sb_mb;
   1217 				}
   1218 				/*
   1219 				 * If m != NULL, we also know that
   1220 				 * so->so_rcv.sb_mb != NULL.
   1221 				 */
   1222 				KASSERT(so->so_rcv.sb_mb == m);
   1223 				if (m) {
   1224 					m->m_nextpkt = nextrecord;
   1225 					if (nextrecord == NULL)
   1226 						so->so_rcv.sb_lastrecord = m;
   1227 				} else {
   1228 					so->so_rcv.sb_mb = nextrecord;
   1229 					SB_EMPTY_FIXUP(&so->so_rcv);
   1230 				}
   1231 				SBLASTRECORDCHK(&so->so_rcv, "soreceive 3");
   1232 				SBLASTMBUFCHK(&so->so_rcv, "soreceive 3");
   1233 			}
   1234 		} else {
   1235 			if (flags & MSG_PEEK)
   1236 				moff += len;
   1237 			else {
   1238 				if (mp)
   1239 					*mp = m_copym(m, 0, len, M_WAIT);
   1240 				m->m_data += len;
   1241 				m->m_len -= len;
   1242 				so->so_rcv.sb_cc -= len;
   1243 			}
   1244 		}
   1245 		if (so->so_oobmark) {
   1246 			if ((flags & MSG_PEEK) == 0) {
   1247 				so->so_oobmark -= len;
   1248 				if (so->so_oobmark == 0) {
   1249 					so->so_state |= SS_RCVATMARK;
   1250 					break;
   1251 				}
   1252 			} else {
   1253 				offset += len;
   1254 				if (offset == so->so_oobmark)
   1255 					break;
   1256 			}
   1257 		}
   1258 		if (flags & MSG_EOR)
   1259 			break;
   1260 		/*
   1261 		 * If the MSG_WAITALL flag is set (for non-atomic socket),
   1262 		 * we must not quit until "uio->uio_resid == 0" or an error
   1263 		 * termination.  If a signal/timeout occurs, return
   1264 		 * with a short count but without error.
   1265 		 * Keep sockbuf locked against other readers.
   1266 		 */
   1267 		while (flags & MSG_WAITALL && m == 0 && uio->uio_resid > 0 &&
   1268 		    !sosendallatonce(so) && !nextrecord) {
   1269 			if (so->so_error || so->so_state & SS_CANTRCVMORE)
   1270 				break;
   1271 			/*
   1272 			 * If we are peeking and the socket receive buffer is
   1273 			 * full, stop since we can't get more data to peek at.
   1274 			 */
   1275 			if ((flags & MSG_PEEK) && sbspace(&so->so_rcv) <= 0)
   1276 				break;
   1277 			/*
   1278 			 * If we've drained the socket buffer, tell the
   1279 			 * protocol in case it needs to do something to
   1280 			 * get it filled again.
   1281 			 */
   1282 			if ((pr->pr_flags & PR_WANTRCVD) && so->so_pcb)
   1283 				(*pr->pr_usrreq)(so, PRU_RCVD,
   1284 				    (struct mbuf *)0,
   1285 				    (struct mbuf *)(long)flags,
   1286 				    (struct mbuf *)0,
   1287 				    (struct proc *)0);
   1288 			SBLASTRECORDCHK(&so->so_rcv, "soreceive sbwait 2");
   1289 			SBLASTMBUFCHK(&so->so_rcv, "soreceive sbwait 2");
   1290 			error = sbwait(&so->so_rcv);
   1291 			if (error) {
   1292 				sbunlock(&so->so_rcv);
   1293 				splx(s);
   1294 				return (0);
   1295 			}
   1296 			if ((m = so->so_rcv.sb_mb) != NULL)
   1297 				nextrecord = m->m_nextpkt;
   1298 		}
   1299 	}
   1300 
   1301 	if (m && pr->pr_flags & PR_ATOMIC) {
   1302 		flags |= MSG_TRUNC;
   1303 		if ((flags & MSG_PEEK) == 0)
   1304 			(void) sbdroprecord(&so->so_rcv);
   1305 	}
   1306 	if ((flags & MSG_PEEK) == 0) {
   1307 		if (m == 0) {
   1308 			/*
   1309 			 * First part is an inline SB_EMPTY_FIXUP().  Second
   1310 			 * part makes sure sb_lastrecord is up-to-date if
   1311 			 * there is still data in the socket buffer.
   1312 			 */
   1313 			so->so_rcv.sb_mb = nextrecord;
   1314 			if (so->so_rcv.sb_mb == NULL) {
   1315 				so->so_rcv.sb_mbtail = NULL;
   1316 				so->so_rcv.sb_lastrecord = NULL;
   1317 			} else if (nextrecord->m_nextpkt == NULL)
   1318 				so->so_rcv.sb_lastrecord = nextrecord;
   1319 		}
   1320 		SBLASTRECORDCHK(&so->so_rcv, "soreceive 4");
   1321 		SBLASTMBUFCHK(&so->so_rcv, "soreceive 4");
   1322 		if (pr->pr_flags & PR_WANTRCVD && so->so_pcb)
   1323 			(*pr->pr_usrreq)(so, PRU_RCVD, (struct mbuf *)0,
   1324 			    (struct mbuf *)(long)flags, (struct mbuf *)0,
   1325 			    (struct proc *)0);
   1326 	}
   1327 	if (orig_resid == uio->uio_resid && orig_resid &&
   1328 	    (flags & MSG_EOR) == 0 && (so->so_state & SS_CANTRCVMORE) == 0) {
   1329 		sbunlock(&so->so_rcv);
   1330 		splx(s);
   1331 		goto restart;
   1332 	}
   1333 
   1334 	if (flagsp)
   1335 		*flagsp |= flags;
   1336  release:
   1337 	sbunlock(&so->so_rcv);
   1338 	splx(s);
   1339 	return (error);
   1340 }
   1341 
   1342 int
   1343 soshutdown(struct socket *so, int how)
   1344 {
   1345 	const struct protosw	*pr;
   1346 
   1347 	pr = so->so_proto;
   1348 	if (!(how == SHUT_RD || how == SHUT_WR || how == SHUT_RDWR))
   1349 		return (EINVAL);
   1350 
   1351 	if (how == SHUT_RD || how == SHUT_RDWR)
   1352 		sorflush(so);
   1353 	if (how == SHUT_WR || how == SHUT_RDWR)
   1354 		return (*pr->pr_usrreq)(so, PRU_SHUTDOWN, (struct mbuf *)0,
   1355 		    (struct mbuf *)0, (struct mbuf *)0, (struct proc *)0);
   1356 	return (0);
   1357 }
   1358 
   1359 void
   1360 sorflush(struct socket *so)
   1361 {
   1362 	struct sockbuf	*sb, asb;
   1363 	const struct protosw	*pr;
   1364 	int		s;
   1365 
   1366 	sb = &so->so_rcv;
   1367 	pr = so->so_proto;
   1368 	sb->sb_flags |= SB_NOINTR;
   1369 	(void) sblock(sb, M_WAITOK);
   1370 	s = splnet();
   1371 	socantrcvmore(so);
   1372 	sbunlock(sb);
   1373 	asb = *sb;
   1374 	/*
   1375 	 * Clear most of the sockbuf structure, but leave some of the
   1376 	 * fields valid.
   1377 	 */
   1378 	memset(&sb->sb_startzero, 0,
   1379 	    sizeof(*sb) - offsetof(struct sockbuf, sb_startzero));
   1380 	splx(s);
   1381 	if (pr->pr_flags & PR_RIGHTS && pr->pr_domain->dom_dispose)
   1382 		(*pr->pr_domain->dom_dispose)(asb.sb_mb);
   1383 	sbrelease(&asb, so);
   1384 }
   1385 
   1386 int
   1387 sosetopt(struct socket *so, int level, int optname, struct mbuf *m0)
   1388 {
   1389 	int		error;
   1390 	struct mbuf	*m;
   1391 
   1392 	error = 0;
   1393 	m = m0;
   1394 	if (level != SOL_SOCKET) {
   1395 		if (so->so_proto && so->so_proto->pr_ctloutput)
   1396 			return ((*so->so_proto->pr_ctloutput)
   1397 				  (PRCO_SETOPT, so, level, optname, &m0));
   1398 		error = ENOPROTOOPT;
   1399 	} else {
   1400 		switch (optname) {
   1401 
   1402 		case SO_LINGER:
   1403 			if (m == NULL || m->m_len != sizeof(struct linger)) {
   1404 				error = EINVAL;
   1405 				goto bad;
   1406 			}
   1407 			so->so_linger = mtod(m, struct linger *)->l_linger;
   1408 			/* fall thru... */
   1409 
   1410 		case SO_DEBUG:
   1411 		case SO_KEEPALIVE:
   1412 		case SO_DONTROUTE:
   1413 		case SO_USELOOPBACK:
   1414 		case SO_BROADCAST:
   1415 		case SO_REUSEADDR:
   1416 		case SO_REUSEPORT:
   1417 		case SO_OOBINLINE:
   1418 		case SO_TIMESTAMP:
   1419 			if (m == NULL || m->m_len < sizeof(int)) {
   1420 				error = EINVAL;
   1421 				goto bad;
   1422 			}
   1423 			if (*mtod(m, int *))
   1424 				so->so_options |= optname;
   1425 			else
   1426 				so->so_options &= ~optname;
   1427 			break;
   1428 
   1429 		case SO_SNDBUF:
   1430 		case SO_RCVBUF:
   1431 		case SO_SNDLOWAT:
   1432 		case SO_RCVLOWAT:
   1433 		    {
   1434 			int optval;
   1435 
   1436 			if (m == NULL || m->m_len < sizeof(int)) {
   1437 				error = EINVAL;
   1438 				goto bad;
   1439 			}
   1440 
   1441 			/*
   1442 			 * Values < 1 make no sense for any of these
   1443 			 * options, so disallow them.
   1444 			 */
   1445 			optval = *mtod(m, int *);
   1446 			if (optval < 1) {
   1447 				error = EINVAL;
   1448 				goto bad;
   1449 			}
   1450 
   1451 			switch (optname) {
   1452 
   1453 			case SO_SNDBUF:
   1454 			case SO_RCVBUF:
   1455 				if (sbreserve(optname == SO_SNDBUF ?
   1456 				    &so->so_snd : &so->so_rcv,
   1457 				    (u_long) optval, so) == 0) {
   1458 					error = ENOBUFS;
   1459 					goto bad;
   1460 				}
   1461 				break;
   1462 
   1463 			/*
   1464 			 * Make sure the low-water is never greater than
   1465 			 * the high-water.
   1466 			 */
   1467 			case SO_SNDLOWAT:
   1468 				so->so_snd.sb_lowat =
   1469 				    (optval > so->so_snd.sb_hiwat) ?
   1470 				    so->so_snd.sb_hiwat : optval;
   1471 				break;
   1472 			case SO_RCVLOWAT:
   1473 				so->so_rcv.sb_lowat =
   1474 				    (optval > so->so_rcv.sb_hiwat) ?
   1475 				    so->so_rcv.sb_hiwat : optval;
   1476 				break;
   1477 			}
   1478 			break;
   1479 		    }
   1480 
   1481 		case SO_SNDTIMEO:
   1482 		case SO_RCVTIMEO:
   1483 		    {
   1484 			struct timeval *tv;
   1485 			short val;
   1486 
   1487 			if (m == NULL || m->m_len < sizeof(*tv)) {
   1488 				error = EINVAL;
   1489 				goto bad;
   1490 			}
   1491 			tv = mtod(m, struct timeval *);
   1492 			if (tv->tv_sec > (SHRT_MAX - tv->tv_usec / tick) / hz) {
   1493 				error = EDOM;
   1494 				goto bad;
   1495 			}
   1496 			val = tv->tv_sec * hz + tv->tv_usec / tick;
   1497 			if (val == 0 && tv->tv_usec != 0)
   1498 				val = 1;
   1499 
   1500 			switch (optname) {
   1501 
   1502 			case SO_SNDTIMEO:
   1503 				so->so_snd.sb_timeo = val;
   1504 				break;
   1505 			case SO_RCVTIMEO:
   1506 				so->so_rcv.sb_timeo = val;
   1507 				break;
   1508 			}
   1509 			break;
   1510 		    }
   1511 
   1512 		default:
   1513 			error = ENOPROTOOPT;
   1514 			break;
   1515 		}
   1516 		if (error == 0 && so->so_proto && so->so_proto->pr_ctloutput) {
   1517 			(void) ((*so->so_proto->pr_ctloutput)
   1518 				  (PRCO_SETOPT, so, level, optname, &m0));
   1519 			m = NULL;	/* freed by protocol */
   1520 		}
   1521 	}
   1522  bad:
   1523 	if (m)
   1524 		(void) m_free(m);
   1525 	return (error);
   1526 }
   1527 
   1528 int
   1529 sogetopt(struct socket *so, int level, int optname, struct mbuf **mp)
   1530 {
   1531 	struct mbuf	*m;
   1532 
   1533 	if (level != SOL_SOCKET) {
   1534 		if (so->so_proto && so->so_proto->pr_ctloutput) {
   1535 			return ((*so->so_proto->pr_ctloutput)
   1536 				  (PRCO_GETOPT, so, level, optname, mp));
   1537 		} else
   1538 			return (ENOPROTOOPT);
   1539 	} else {
   1540 		m = m_get(M_WAIT, MT_SOOPTS);
   1541 		m->m_len = sizeof(int);
   1542 
   1543 		switch (optname) {
   1544 
   1545 		case SO_LINGER:
   1546 			m->m_len = sizeof(struct linger);
   1547 			mtod(m, struct linger *)->l_onoff =
   1548 				so->so_options & SO_LINGER;
   1549 			mtod(m, struct linger *)->l_linger = so->so_linger;
   1550 			break;
   1551 
   1552 		case SO_USELOOPBACK:
   1553 		case SO_DONTROUTE:
   1554 		case SO_DEBUG:
   1555 		case SO_KEEPALIVE:
   1556 		case SO_REUSEADDR:
   1557 		case SO_REUSEPORT:
   1558 		case SO_BROADCAST:
   1559 		case SO_OOBINLINE:
   1560 		case SO_TIMESTAMP:
   1561 			*mtod(m, int *) = so->so_options & optname;
   1562 			break;
   1563 
   1564 		case SO_TYPE:
   1565 			*mtod(m, int *) = so->so_type;
   1566 			break;
   1567 
   1568 		case SO_ERROR:
   1569 			*mtod(m, int *) = so->so_error;
   1570 			so->so_error = 0;
   1571 			break;
   1572 
   1573 		case SO_SNDBUF:
   1574 			*mtod(m, int *) = so->so_snd.sb_hiwat;
   1575 			break;
   1576 
   1577 		case SO_RCVBUF:
   1578 			*mtod(m, int *) = so->so_rcv.sb_hiwat;
   1579 			break;
   1580 
   1581 		case SO_SNDLOWAT:
   1582 			*mtod(m, int *) = so->so_snd.sb_lowat;
   1583 			break;
   1584 
   1585 		case SO_RCVLOWAT:
   1586 			*mtod(m, int *) = so->so_rcv.sb_lowat;
   1587 			break;
   1588 
   1589 		case SO_SNDTIMEO:
   1590 		case SO_RCVTIMEO:
   1591 		    {
   1592 			int val = (optname == SO_SNDTIMEO ?
   1593 			     so->so_snd.sb_timeo : so->so_rcv.sb_timeo);
   1594 
   1595 			m->m_len = sizeof(struct timeval);
   1596 			mtod(m, struct timeval *)->tv_sec = val / hz;
   1597 			mtod(m, struct timeval *)->tv_usec =
   1598 			    (val % hz) * tick;
   1599 			break;
   1600 		    }
   1601 
   1602 		default:
   1603 			(void)m_free(m);
   1604 			return (ENOPROTOOPT);
   1605 		}
   1606 		*mp = m;
   1607 		return (0);
   1608 	}
   1609 }
   1610 
   1611 void
   1612 sohasoutofband(struct socket *so)
   1613 {
   1614 	fownsignal(so->so_pgid, SIGURG, POLL_PRI, POLLPRI|POLLRDBAND, so);
   1615 	selwakeup(&so->so_rcv.sb_sel);
   1616 }
   1617 
   1618 static void
   1619 filt_sordetach(struct knote *kn)
   1620 {
   1621 	struct socket	*so;
   1622 
   1623 	so = (struct socket *)kn->kn_fp->f_data;
   1624 	SLIST_REMOVE(&so->so_rcv.sb_sel.sel_klist, kn, knote, kn_selnext);
   1625 	if (SLIST_EMPTY(&so->so_rcv.sb_sel.sel_klist))
   1626 		so->so_rcv.sb_flags &= ~SB_KNOTE;
   1627 }
   1628 
   1629 /*ARGSUSED*/
   1630 static int
   1631 filt_soread(struct knote *kn, long hint)
   1632 {
   1633 	struct socket	*so;
   1634 
   1635 	so = (struct socket *)kn->kn_fp->f_data;
   1636 	kn->kn_data = so->so_rcv.sb_cc;
   1637 	if (so->so_state & SS_CANTRCVMORE) {
   1638 		kn->kn_flags |= EV_EOF;
   1639 		kn->kn_fflags = so->so_error;
   1640 		return (1);
   1641 	}
   1642 	if (so->so_error)	/* temporary udp error */
   1643 		return (1);
   1644 	if (kn->kn_sfflags & NOTE_LOWAT)
   1645 		return (kn->kn_data >= kn->kn_sdata);
   1646 	return (kn->kn_data >= so->so_rcv.sb_lowat);
   1647 }
   1648 
   1649 static void
   1650 filt_sowdetach(struct knote *kn)
   1651 {
   1652 	struct socket	*so;
   1653 
   1654 	so = (struct socket *)kn->kn_fp->f_data;
   1655 	SLIST_REMOVE(&so->so_snd.sb_sel.sel_klist, kn, knote, kn_selnext);
   1656 	if (SLIST_EMPTY(&so->so_snd.sb_sel.sel_klist))
   1657 		so->so_snd.sb_flags &= ~SB_KNOTE;
   1658 }
   1659 
   1660 /*ARGSUSED*/
   1661 static int
   1662 filt_sowrite(struct knote *kn, long hint)
   1663 {
   1664 	struct socket	*so;
   1665 
   1666 	so = (struct socket *)kn->kn_fp->f_data;
   1667 	kn->kn_data = sbspace(&so->so_snd);
   1668 	if (so->so_state & SS_CANTSENDMORE) {
   1669 		kn->kn_flags |= EV_EOF;
   1670 		kn->kn_fflags = so->so_error;
   1671 		return (1);
   1672 	}
   1673 	if (so->so_error)	/* temporary udp error */
   1674 		return (1);
   1675 	if (((so->so_state & SS_ISCONNECTED) == 0) &&
   1676 	    (so->so_proto->pr_flags & PR_CONNREQUIRED))
   1677 		return (0);
   1678 	if (kn->kn_sfflags & NOTE_LOWAT)
   1679 		return (kn->kn_data >= kn->kn_sdata);
   1680 	return (kn->kn_data >= so->so_snd.sb_lowat);
   1681 }
   1682 
   1683 /*ARGSUSED*/
   1684 static int
   1685 filt_solisten(struct knote *kn, long hint)
   1686 {
   1687 	struct socket	*so;
   1688 
   1689 	so = (struct socket *)kn->kn_fp->f_data;
   1690 
   1691 	/*
   1692 	 * Set kn_data to number of incoming connections, not
   1693 	 * counting partial (incomplete) connections.
   1694 	 */
   1695 	kn->kn_data = so->so_qlen;
   1696 	return (kn->kn_data > 0);
   1697 }
   1698 
   1699 static const struct filterops solisten_filtops =
   1700 	{ 1, NULL, filt_sordetach, filt_solisten };
   1701 static const struct filterops soread_filtops =
   1702 	{ 1, NULL, filt_sordetach, filt_soread };
   1703 static const struct filterops sowrite_filtops =
   1704 	{ 1, NULL, filt_sowdetach, filt_sowrite };
   1705 
   1706 int
   1707 soo_kqfilter(struct file *fp, struct knote *kn)
   1708 {
   1709 	struct socket	*so;
   1710 	struct sockbuf	*sb;
   1711 
   1712 	so = (struct socket *)kn->kn_fp->f_data;
   1713 	switch (kn->kn_filter) {
   1714 	case EVFILT_READ:
   1715 		if (so->so_options & SO_ACCEPTCONN)
   1716 			kn->kn_fop = &solisten_filtops;
   1717 		else
   1718 			kn->kn_fop = &soread_filtops;
   1719 		sb = &so->so_rcv;
   1720 		break;
   1721 	case EVFILT_WRITE:
   1722 		kn->kn_fop = &sowrite_filtops;
   1723 		sb = &so->so_snd;
   1724 		break;
   1725 	default:
   1726 		return (1);
   1727 	}
   1728 	SLIST_INSERT_HEAD(&sb->sb_sel.sel_klist, kn, kn_selnext);
   1729 	sb->sb_flags |= SB_KNOTE;
   1730 	return (0);
   1731 }
   1732 
   1733 #include <sys/sysctl.h>
   1734 
   1735 static int sysctl_kern_somaxkva(SYSCTLFN_PROTO);
   1736 
   1737 /*
   1738  * sysctl helper routine for kern.somaxkva.  ensures that the given
   1739  * value is not too small.
   1740  * (XXX should we maybe make sure it's not too large as well?)
   1741  */
   1742 static int
   1743 sysctl_kern_somaxkva(SYSCTLFN_ARGS)
   1744 {
   1745 	int error, new_somaxkva;
   1746 	struct sysctlnode node;
   1747 	int s;
   1748 
   1749 	new_somaxkva = somaxkva;
   1750 	node = *rnode;
   1751 	node.sysctl_data = &new_somaxkva;
   1752 	error = sysctl_lookup(SYSCTLFN_CALL(&node));
   1753 	if (error || newp == NULL)
   1754 		return (error);
   1755 
   1756 	if (new_somaxkva < (16 * 1024 * 1024)) /* sanity */
   1757 		return (EINVAL);
   1758 
   1759 	s = splvm();
   1760 	simple_lock(&so_pendfree_slock);
   1761 	somaxkva = new_somaxkva;
   1762 	wakeup(&socurkva);
   1763 	simple_unlock(&so_pendfree_slock);
   1764 	splx(s);
   1765 
   1766 	return (error);
   1767 }
   1768 
   1769 SYSCTL_SETUP(sysctl_kern_somaxkva_setup, "sysctl kern.somaxkva setup")
   1770 {
   1771 
   1772 	sysctl_createv(clog, 0, NULL, NULL,
   1773 		       CTLFLAG_PERMANENT,
   1774 		       CTLTYPE_NODE, "kern", NULL,
   1775 		       NULL, 0, NULL, 0,
   1776 		       CTL_KERN, CTL_EOL);
   1777 
   1778 	sysctl_createv(clog, 0, NULL, NULL,
   1779 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   1780 		       CTLTYPE_INT, "somaxkva", NULL,
   1781 		       sysctl_kern_somaxkva, 0, NULL, 0,
   1782 		       CTL_KERN, KERN_SOMAXKVA, CTL_EOL);
   1783 }
   1784