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