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