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