xref: /netbsd-src/sys/kern/uipc_socket.c (revision e5548b402ae4c44fb816de42c7bba9581ce23ef5)
1 /*	$NetBSD: uipc_socket.c,v 1.114 2005/12/11 12:24:30 christos 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.114 2005/12/11 12:24:30 christos 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 	struct proc	*p;
457 	int		error, s;
458 
459 	p = l->l_proc;
460 	if (proto)
461 		prp = pffindproto(dom, proto, type);
462 	else
463 		prp = pffindtype(dom, type);
464 	if (prp == 0 || prp->pr_usrreq == 0)
465 		return (EPROTONOSUPPORT);
466 	if (prp->pr_type != type)
467 		return (EPROTOTYPE);
468 	s = splsoftnet();
469 	so = pool_get(&socket_pool, PR_WAITOK);
470 	memset((caddr_t)so, 0, sizeof(*so));
471 	TAILQ_INIT(&so->so_q0);
472 	TAILQ_INIT(&so->so_q);
473 	so->so_type = type;
474 	so->so_proto = prp;
475 	so->so_send = sosend;
476 	so->so_receive = soreceive;
477 #ifdef MBUFTRACE
478 	so->so_rcv.sb_mowner = &prp->pr_domain->dom_mowner;
479 	so->so_snd.sb_mowner = &prp->pr_domain->dom_mowner;
480 	so->so_mowner = &prp->pr_domain->dom_mowner;
481 #endif
482 	if (p != 0)
483 		so->so_uidinfo = uid_find(p->p_ucred->cr_uid);
484 	else
485 		so->so_uidinfo = uid_find(0);
486 	error = (*prp->pr_usrreq)(so, PRU_ATTACH, (struct mbuf *)0,
487 	    (struct mbuf *)(long)proto, (struct mbuf *)0, l);
488 	if (error) {
489 		so->so_state |= SS_NOFDREF;
490 		sofree(so);
491 		splx(s);
492 		return (error);
493 	}
494 	splx(s);
495 	*aso = so;
496 	return (0);
497 }
498 
499 int
500 sobind(struct socket *so, struct mbuf *nam, struct lwp *l)
501 {
502 	int	s, error;
503 
504 	s = splsoftnet();
505 	error = (*so->so_proto->pr_usrreq)(so, PRU_BIND, (struct mbuf *)0,
506 	    nam, (struct mbuf *)0, l);
507 	splx(s);
508 	return (error);
509 }
510 
511 int
512 solisten(struct socket *so, int backlog)
513 {
514 	int	s, error;
515 
516 	s = splsoftnet();
517 	error = (*so->so_proto->pr_usrreq)(so, PRU_LISTEN, (struct mbuf *)0,
518 	    (struct mbuf *)0, (struct mbuf *)0, (struct lwp *)0);
519 	if (error) {
520 		splx(s);
521 		return (error);
522 	}
523 	if (TAILQ_EMPTY(&so->so_q))
524 		so->so_options |= SO_ACCEPTCONN;
525 	if (backlog < 0)
526 		backlog = 0;
527 	so->so_qlimit = min(backlog, somaxconn);
528 	splx(s);
529 	return (0);
530 }
531 
532 void
533 sofree(struct socket *so)
534 {
535 
536 	if (so->so_pcb || (so->so_state & SS_NOFDREF) == 0)
537 		return;
538 	if (so->so_head) {
539 		/*
540 		 * We must not decommission a socket that's on the accept(2)
541 		 * queue.  If we do, then accept(2) may hang after select(2)
542 		 * indicated that the listening socket was ready.
543 		 */
544 		if (!soqremque(so, 0))
545 			return;
546 	}
547 	if (so->so_rcv.sb_hiwat)
548 		(void)chgsbsize(so->so_uidinfo, &so->so_rcv.sb_hiwat, 0,
549 		    RLIM_INFINITY);
550 	if (so->so_snd.sb_hiwat)
551 		(void)chgsbsize(so->so_uidinfo, &so->so_snd.sb_hiwat, 0,
552 		    RLIM_INFINITY);
553 	sbrelease(&so->so_snd, so);
554 	sorflush(so);
555 	pool_put(&socket_pool, so);
556 }
557 
558 /*
559  * Close a socket on last file table reference removal.
560  * Initiate disconnect if connected.
561  * Free socket when disconnect complete.
562  */
563 int
564 soclose(struct socket *so)
565 {
566 	struct socket	*so2;
567 	int		s, error;
568 
569 	error = 0;
570 	s = splsoftnet();		/* conservative */
571 	if (so->so_options & SO_ACCEPTCONN) {
572 		while ((so2 = TAILQ_FIRST(&so->so_q0)) != 0) {
573 			(void) soqremque(so2, 0);
574 			(void) soabort(so2);
575 		}
576 		while ((so2 = TAILQ_FIRST(&so->so_q)) != 0) {
577 			(void) soqremque(so2, 1);
578 			(void) soabort(so2);
579 		}
580 	}
581 	if (so->so_pcb == 0)
582 		goto discard;
583 	if (so->so_state & SS_ISCONNECTED) {
584 		if ((so->so_state & SS_ISDISCONNECTING) == 0) {
585 			error = sodisconnect(so);
586 			if (error)
587 				goto drop;
588 		}
589 		if (so->so_options & SO_LINGER) {
590 			if ((so->so_state & SS_ISDISCONNECTING) &&
591 			    (so->so_state & SS_NBIO))
592 				goto drop;
593 			while (so->so_state & SS_ISCONNECTED) {
594 				error = tsleep((caddr_t)&so->so_timeo,
595 					       PSOCK | PCATCH, netcls,
596 					       so->so_linger * hz);
597 				if (error)
598 					break;
599 			}
600 		}
601 	}
602  drop:
603 	if (so->so_pcb) {
604 		int error2 = (*so->so_proto->pr_usrreq)(so, PRU_DETACH,
605 		    (struct mbuf *)0, (struct mbuf *)0, (struct mbuf *)0,
606 		    (struct lwp *)0);
607 		if (error == 0)
608 			error = error2;
609 	}
610  discard:
611 	if (so->so_state & SS_NOFDREF)
612 		panic("soclose: NOFDREF");
613 	so->so_state |= SS_NOFDREF;
614 	sofree(so);
615 	splx(s);
616 	return (error);
617 }
618 
619 /*
620  * Must be called at splsoftnet...
621  */
622 int
623 soabort(struct socket *so)
624 {
625 
626 	return (*so->so_proto->pr_usrreq)(so, PRU_ABORT, (struct mbuf *)0,
627 	    (struct mbuf *)0, (struct mbuf *)0, (struct lwp *)0);
628 }
629 
630 int
631 soaccept(struct socket *so, struct mbuf *nam)
632 {
633 	int	s, error;
634 
635 	error = 0;
636 	s = splsoftnet();
637 	if ((so->so_state & SS_NOFDREF) == 0)
638 		panic("soaccept: !NOFDREF");
639 	so->so_state &= ~SS_NOFDREF;
640 	if ((so->so_state & SS_ISDISCONNECTED) == 0 ||
641 	    (so->so_proto->pr_flags & PR_ABRTACPTDIS) == 0)
642 		error = (*so->so_proto->pr_usrreq)(so, PRU_ACCEPT,
643 		    (struct mbuf *)0, nam, (struct mbuf *)0, (struct lwp *)0);
644 	else
645 		error = ECONNABORTED;
646 
647 	splx(s);
648 	return (error);
649 }
650 
651 int
652 soconnect(struct socket *so, struct mbuf *nam, struct lwp *l)
653 {
654 	int		s, error;
655 
656 	if (so->so_options & SO_ACCEPTCONN)
657 		return (EOPNOTSUPP);
658 	s = splsoftnet();
659 	/*
660 	 * If protocol is connection-based, can only connect once.
661 	 * Otherwise, if connected, try to disconnect first.
662 	 * This allows user to disconnect by connecting to, e.g.,
663 	 * a null address.
664 	 */
665 	if (so->so_state & (SS_ISCONNECTED|SS_ISCONNECTING) &&
666 	    ((so->so_proto->pr_flags & PR_CONNREQUIRED) ||
667 	    (error = sodisconnect(so))))
668 		error = EISCONN;
669 	else
670 		error = (*so->so_proto->pr_usrreq)(so, PRU_CONNECT,
671 		    (struct mbuf *)0, nam, (struct mbuf *)0, l);
672 	splx(s);
673 	return (error);
674 }
675 
676 int
677 soconnect2(struct socket *so1, struct socket *so2)
678 {
679 	int	s, error;
680 
681 	s = splsoftnet();
682 	error = (*so1->so_proto->pr_usrreq)(so1, PRU_CONNECT2,
683 	    (struct mbuf *)0, (struct mbuf *)so2, (struct mbuf *)0,
684 	    (struct lwp *)0);
685 	splx(s);
686 	return (error);
687 }
688 
689 int
690 sodisconnect(struct socket *so)
691 {
692 	int	s, error;
693 
694 	s = splsoftnet();
695 	if ((so->so_state & SS_ISCONNECTED) == 0) {
696 		error = ENOTCONN;
697 		goto bad;
698 	}
699 	if (so->so_state & SS_ISDISCONNECTING) {
700 		error = EALREADY;
701 		goto bad;
702 	}
703 	error = (*so->so_proto->pr_usrreq)(so, PRU_DISCONNECT,
704 	    (struct mbuf *)0, (struct mbuf *)0, (struct mbuf *)0,
705 	    (struct lwp *)0);
706  bad:
707 	splx(s);
708 	sodopendfree(so);
709 	return (error);
710 }
711 
712 #define	SBLOCKWAIT(f)	(((f) & MSG_DONTWAIT) ? M_NOWAIT : M_WAITOK)
713 /*
714  * Send on a socket.
715  * If send must go all at once and message is larger than
716  * send buffering, then hard error.
717  * Lock against other senders.
718  * If must go all at once and not enough room now, then
719  * inform user that this would block and do nothing.
720  * Otherwise, if nonblocking, send as much as possible.
721  * The data to be sent is described by "uio" if nonzero,
722  * otherwise by the mbuf chain "top" (which must be null
723  * if uio is not).  Data provided in mbuf chain must be small
724  * enough to send all at once.
725  *
726  * Returns nonzero on error, timeout or signal; callers
727  * must check for short counts if EINTR/ERESTART are returned.
728  * Data and control buffers are freed on return.
729  */
730 int
731 sosend(struct socket *so, struct mbuf *addr, struct uio *uio, struct mbuf *top,
732 	struct mbuf *control, int flags, struct lwp *l)
733 {
734 	struct mbuf	**mp, *m;
735 	struct proc	*p;
736 	long		space, len, resid, clen, mlen;
737 	int		error, s, dontroute, atomic;
738 
739 	p = l->l_proc;
740 	sodopendfree(so);
741 
742 	clen = 0;
743 	atomic = sosendallatonce(so) || top;
744 	if (uio)
745 		resid = uio->uio_resid;
746 	else
747 		resid = top->m_pkthdr.len;
748 	/*
749 	 * In theory resid should be unsigned.
750 	 * However, space must be signed, as it might be less than 0
751 	 * if we over-committed, and we must use a signed comparison
752 	 * of space and resid.  On the other hand, a negative resid
753 	 * causes us to loop sending 0-length segments to the protocol.
754 	 */
755 	if (resid < 0) {
756 		error = EINVAL;
757 		goto out;
758 	}
759 	dontroute =
760 	    (flags & MSG_DONTROUTE) && (so->so_options & SO_DONTROUTE) == 0 &&
761 	    (so->so_proto->pr_flags & PR_ATOMIC);
762 	if (p)
763 		p->p_stats->p_ru.ru_msgsnd++;
764 	if (control)
765 		clen = control->m_len;
766 #define	snderr(errno)	{ error = errno; splx(s); goto release; }
767 
768  restart:
769 	if ((error = sblock(&so->so_snd, SBLOCKWAIT(flags))) != 0)
770 		goto out;
771 	do {
772 		s = splsoftnet();
773 		if (so->so_state & SS_CANTSENDMORE)
774 			snderr(EPIPE);
775 		if (so->so_error) {
776 			error = so->so_error;
777 			so->so_error = 0;
778 			splx(s);
779 			goto release;
780 		}
781 		if ((so->so_state & SS_ISCONNECTED) == 0) {
782 			if (so->so_proto->pr_flags & PR_CONNREQUIRED) {
783 				if ((so->so_state & SS_ISCONFIRMING) == 0 &&
784 				    !(resid == 0 && clen != 0))
785 					snderr(ENOTCONN);
786 			} else if (addr == 0)
787 				snderr(EDESTADDRREQ);
788 		}
789 		space = sbspace(&so->so_snd);
790 		if (flags & MSG_OOB)
791 			space += 1024;
792 		if ((atomic && resid > so->so_snd.sb_hiwat) ||
793 		    clen > so->so_snd.sb_hiwat)
794 			snderr(EMSGSIZE);
795 		if (space < resid + clen &&
796 		    (atomic || space < so->so_snd.sb_lowat || space < clen)) {
797 			if (so->so_state & SS_NBIO)
798 				snderr(EWOULDBLOCK);
799 			sbunlock(&so->so_snd);
800 			error = sbwait(&so->so_snd);
801 			splx(s);
802 			if (error)
803 				goto out;
804 			goto restart;
805 		}
806 		splx(s);
807 		mp = &top;
808 		space -= clen;
809 		do {
810 			if (uio == NULL) {
811 				/*
812 				 * Data is prepackaged in "top".
813 				 */
814 				resid = 0;
815 				if (flags & MSG_EOR)
816 					top->m_flags |= M_EOR;
817 			} else do {
818 				if (top == 0) {
819 					m = m_gethdr(M_WAIT, MT_DATA);
820 					mlen = MHLEN;
821 					m->m_pkthdr.len = 0;
822 					m->m_pkthdr.rcvif = (struct ifnet *)0;
823 				} else {
824 					m = m_get(M_WAIT, MT_DATA);
825 					mlen = MLEN;
826 				}
827 				MCLAIM(m, so->so_snd.sb_mowner);
828 				if (use_sosend_loan &&
829 				    uio->uio_iov->iov_len >= SOCK_LOAN_THRESH &&
830 				    space >= SOCK_LOAN_THRESH &&
831 				    (len = sosend_loan(so, uio, m,
832 						       space)) != 0) {
833 					SOSEND_COUNTER_INCR(&sosend_loan_big);
834 					space -= len;
835 					goto have_data;
836 				}
837 				if (resid >= MINCLSIZE && space >= MCLBYTES) {
838 					SOSEND_COUNTER_INCR(&sosend_copy_big);
839 					m_clget(m, M_WAIT);
840 					if ((m->m_flags & M_EXT) == 0)
841 						goto nopages;
842 					mlen = MCLBYTES;
843 					if (atomic && top == 0) {
844 						len = lmin(MCLBYTES - max_hdr,
845 						    resid);
846 						m->m_data += max_hdr;
847 					} else
848 						len = lmin(MCLBYTES, resid);
849 					space -= len;
850 				} else {
851  nopages:
852 					SOSEND_COUNTER_INCR(&sosend_copy_small);
853 					len = lmin(lmin(mlen, resid), space);
854 					space -= len;
855 					/*
856 					 * For datagram protocols, leave room
857 					 * for protocol headers in first mbuf.
858 					 */
859 					if (atomic && top == 0 && len < mlen)
860 						MH_ALIGN(m, len);
861 				}
862 				error = uiomove(mtod(m, caddr_t), (int)len,
863 				    uio);
864  have_data:
865 				resid = uio->uio_resid;
866 				m->m_len = len;
867 				*mp = m;
868 				top->m_pkthdr.len += len;
869 				if (error)
870 					goto release;
871 				mp = &m->m_next;
872 				if (resid <= 0) {
873 					if (flags & MSG_EOR)
874 						top->m_flags |= M_EOR;
875 					break;
876 				}
877 			} while (space > 0 && atomic);
878 
879 			s = splsoftnet();
880 
881 			if (so->so_state & SS_CANTSENDMORE)
882 				snderr(EPIPE);
883 
884 			if (dontroute)
885 				so->so_options |= SO_DONTROUTE;
886 			if (resid > 0)
887 				so->so_state |= SS_MORETOCOME;
888 			error = (*so->so_proto->pr_usrreq)(so,
889 			    (flags & MSG_OOB) ? PRU_SENDOOB : PRU_SEND,
890 			    top, addr, control, curlwp);	/* XXX */
891 			if (dontroute)
892 				so->so_options &= ~SO_DONTROUTE;
893 			if (resid > 0)
894 				so->so_state &= ~SS_MORETOCOME;
895 			splx(s);
896 
897 			clen = 0;
898 			control = 0;
899 			top = 0;
900 			mp = &top;
901 			if (error)
902 				goto release;
903 		} while (resid && space > 0);
904 	} while (resid);
905 
906  release:
907 	sbunlock(&so->so_snd);
908  out:
909 	if (top)
910 		m_freem(top);
911 	if (control)
912 		m_freem(control);
913 	return (error);
914 }
915 
916 /*
917  * Implement receive operations on a socket.
918  * We depend on the way that records are added to the sockbuf
919  * by sbappend*.  In particular, each record (mbufs linked through m_next)
920  * must begin with an address if the protocol so specifies,
921  * followed by an optional mbuf or mbufs containing ancillary data,
922  * and then zero or more mbufs of data.
923  * In order to avoid blocking network interrupts for the entire time here,
924  * we splx() while doing the actual copy to user space.
925  * Although the sockbuf is locked, new data may still be appended,
926  * and thus we must maintain consistency of the sockbuf during that time.
927  *
928  * The caller may receive the data as a single mbuf chain by supplying
929  * an mbuf **mp0 for use in returning the chain.  The uio is then used
930  * only for the count in uio_resid.
931  */
932 int
933 soreceive(struct socket *so, struct mbuf **paddr, struct uio *uio,
934 	struct mbuf **mp0, struct mbuf **controlp, int *flagsp)
935 {
936 	struct lwp *l;
937 	struct mbuf	*m, **mp;
938 	int		flags, len, error, s, offset, moff, type, orig_resid;
939 	const struct protosw	*pr;
940 	struct mbuf	*nextrecord;
941 	int		mbuf_removed = 0;
942 
943 	pr = so->so_proto;
944 	mp = mp0;
945 	type = 0;
946 	orig_resid = uio->uio_resid;
947 	l = uio->uio_lwp;
948 
949 	if (paddr)
950 		*paddr = 0;
951 	if (controlp)
952 		*controlp = 0;
953 	if (flagsp)
954 		flags = *flagsp &~ MSG_EOR;
955 	else
956 		flags = 0;
957 
958 	if ((flags & MSG_DONTWAIT) == 0)
959 		sodopendfree(so);
960 
961 	if (flags & MSG_OOB) {
962 		m = m_get(M_WAIT, MT_DATA);
963 		error = (*pr->pr_usrreq)(so, PRU_RCVOOB, m,
964 		    (struct mbuf *)(long)(flags & MSG_PEEK),
965 		    (struct mbuf *)0, l);
966 		if (error)
967 			goto bad;
968 		do {
969 			error = uiomove(mtod(m, caddr_t),
970 			    (int) min(uio->uio_resid, m->m_len), uio);
971 			m = m_free(m);
972 		} while (uio->uio_resid && error == 0 && m);
973  bad:
974 		if (m)
975 			m_freem(m);
976 		return (error);
977 	}
978 	if (mp)
979 		*mp = (struct mbuf *)0;
980 	if (so->so_state & SS_ISCONFIRMING && uio->uio_resid)
981 		(*pr->pr_usrreq)(so, PRU_RCVD, (struct mbuf *)0,
982 		    (struct mbuf *)0, (struct mbuf *)0, l);
983 
984  restart:
985 	if ((error = sblock(&so->so_rcv, SBLOCKWAIT(flags))) != 0)
986 		return (error);
987 	s = splsoftnet();
988 
989 	m = so->so_rcv.sb_mb;
990 	/*
991 	 * If we have less data than requested, block awaiting more
992 	 * (subject to any timeout) if:
993 	 *   1. the current count is less than the low water mark,
994 	 *   2. MSG_WAITALL is set, and it is possible to do the entire
995 	 *	receive operation at once if we block (resid <= hiwat), or
996 	 *   3. MSG_DONTWAIT is not set.
997 	 * If MSG_WAITALL is set but resid is larger than the receive buffer,
998 	 * we have to do the receive in sections, and thus risk returning
999 	 * a short count if a timeout or signal occurs after we start.
1000 	 */
1001 	if (m == 0 || (((flags & MSG_DONTWAIT) == 0 &&
1002 	    so->so_rcv.sb_cc < uio->uio_resid) &&
1003 	    (so->so_rcv.sb_cc < so->so_rcv.sb_lowat ||
1004 	    ((flags & MSG_WAITALL) && uio->uio_resid <= so->so_rcv.sb_hiwat)) &&
1005 	    m->m_nextpkt == 0 && (pr->pr_flags & PR_ATOMIC) == 0)) {
1006 #ifdef DIAGNOSTIC
1007 		if (m == 0 && so->so_rcv.sb_cc)
1008 			panic("receive 1");
1009 #endif
1010 		if (so->so_error) {
1011 			if (m)
1012 				goto dontblock;
1013 			error = so->so_error;
1014 			if ((flags & MSG_PEEK) == 0)
1015 				so->so_error = 0;
1016 			goto release;
1017 		}
1018 		if (so->so_state & SS_CANTRCVMORE) {
1019 			if (m)
1020 				goto dontblock;
1021 			else
1022 				goto release;
1023 		}
1024 		for (; m; m = m->m_next)
1025 			if (m->m_type == MT_OOBDATA  || (m->m_flags & M_EOR)) {
1026 				m = so->so_rcv.sb_mb;
1027 				goto dontblock;
1028 			}
1029 		if ((so->so_state & (SS_ISCONNECTED|SS_ISCONNECTING)) == 0 &&
1030 		    (so->so_proto->pr_flags & PR_CONNREQUIRED)) {
1031 			error = ENOTCONN;
1032 			goto release;
1033 		}
1034 		if (uio->uio_resid == 0)
1035 			goto release;
1036 		if ((so->so_state & SS_NBIO) || (flags & MSG_DONTWAIT)) {
1037 			error = EWOULDBLOCK;
1038 			goto release;
1039 		}
1040 		SBLASTRECORDCHK(&so->so_rcv, "soreceive sbwait 1");
1041 		SBLASTMBUFCHK(&so->so_rcv, "soreceive sbwait 1");
1042 		sbunlock(&so->so_rcv);
1043 		error = sbwait(&so->so_rcv);
1044 		splx(s);
1045 		if (error)
1046 			return (error);
1047 		goto restart;
1048 	}
1049  dontblock:
1050 	/*
1051 	 * On entry here, m points to the first record of the socket buffer.
1052 	 * While we process the initial mbufs containing address and control
1053 	 * info, we save a copy of m->m_nextpkt into nextrecord.
1054 	 */
1055 	if (l)
1056 		l->l_proc->p_stats->p_ru.ru_msgrcv++;
1057 	KASSERT(m == so->so_rcv.sb_mb);
1058 	SBLASTRECORDCHK(&so->so_rcv, "soreceive 1");
1059 	SBLASTMBUFCHK(&so->so_rcv, "soreceive 1");
1060 	nextrecord = m->m_nextpkt;
1061 	if (pr->pr_flags & PR_ADDR) {
1062 #ifdef DIAGNOSTIC
1063 		if (m->m_type != MT_SONAME)
1064 			panic("receive 1a");
1065 #endif
1066 		orig_resid = 0;
1067 		if (flags & MSG_PEEK) {
1068 			if (paddr)
1069 				*paddr = m_copy(m, 0, m->m_len);
1070 			m = m->m_next;
1071 		} else {
1072 			sbfree(&so->so_rcv, m);
1073 			mbuf_removed = 1;
1074 			if (paddr) {
1075 				*paddr = m;
1076 				so->so_rcv.sb_mb = m->m_next;
1077 				m->m_next = 0;
1078 				m = so->so_rcv.sb_mb;
1079 			} else {
1080 				MFREE(m, so->so_rcv.sb_mb);
1081 				m = so->so_rcv.sb_mb;
1082 			}
1083 		}
1084 	}
1085 	while (m && m->m_type == MT_CONTROL && error == 0) {
1086 		if (flags & MSG_PEEK) {
1087 			if (controlp)
1088 				*controlp = m_copy(m, 0, m->m_len);
1089 			m = m->m_next;
1090 		} else {
1091 			sbfree(&so->so_rcv, m);
1092 			mbuf_removed = 1;
1093 			if (controlp) {
1094 				struct domain *dom = pr->pr_domain;
1095 				if (dom->dom_externalize && l &&
1096 				    mtod(m, struct cmsghdr *)->cmsg_type ==
1097 				    SCM_RIGHTS)
1098 					error = (*dom->dom_externalize)(m, l);
1099 				*controlp = m;
1100 				so->so_rcv.sb_mb = m->m_next;
1101 				m->m_next = 0;
1102 				m = so->so_rcv.sb_mb;
1103 			} else {
1104 				/*
1105 				 * Dispose of any SCM_RIGHTS message that went
1106 				 * through the read path rather than recv.
1107 				 */
1108 				if (pr->pr_domain->dom_dispose &&
1109 				    mtod(m, struct cmsghdr *)->cmsg_type == SCM_RIGHTS)
1110 					(*pr->pr_domain->dom_dispose)(m);
1111 				MFREE(m, so->so_rcv.sb_mb);
1112 				m = so->so_rcv.sb_mb;
1113 			}
1114 		}
1115 		if (controlp) {
1116 			orig_resid = 0;
1117 			controlp = &(*controlp)->m_next;
1118 		}
1119 	}
1120 
1121 	/*
1122 	 * If m is non-NULL, we have some data to read.  From now on,
1123 	 * make sure to keep sb_lastrecord consistent when working on
1124 	 * the last packet on the chain (nextrecord == NULL) and we
1125 	 * change m->m_nextpkt.
1126 	 */
1127 	if (m) {
1128 		if ((flags & MSG_PEEK) == 0) {
1129 			m->m_nextpkt = nextrecord;
1130 			/*
1131 			 * If nextrecord == NULL (this is a single chain),
1132 			 * then sb_lastrecord may not be valid here if m
1133 			 * was changed earlier.
1134 			 */
1135 			if (nextrecord == NULL) {
1136 				KASSERT(so->so_rcv.sb_mb == m);
1137 				so->so_rcv.sb_lastrecord = m;
1138 			}
1139 		}
1140 		type = m->m_type;
1141 		if (type == MT_OOBDATA)
1142 			flags |= MSG_OOB;
1143 	} else {
1144 		if ((flags & MSG_PEEK) == 0) {
1145 			KASSERT(so->so_rcv.sb_mb == m);
1146 			so->so_rcv.sb_mb = nextrecord;
1147 			SB_EMPTY_FIXUP(&so->so_rcv);
1148 		}
1149 	}
1150 	SBLASTRECORDCHK(&so->so_rcv, "soreceive 2");
1151 	SBLASTMBUFCHK(&so->so_rcv, "soreceive 2");
1152 
1153 	moff = 0;
1154 	offset = 0;
1155 	while (m && uio->uio_resid > 0 && error == 0) {
1156 		if (m->m_type == MT_OOBDATA) {
1157 			if (type != MT_OOBDATA)
1158 				break;
1159 		} else if (type == MT_OOBDATA)
1160 			break;
1161 #ifdef DIAGNOSTIC
1162 		else if (m->m_type != MT_DATA && m->m_type != MT_HEADER)
1163 			panic("receive 3");
1164 #endif
1165 		so->so_state &= ~SS_RCVATMARK;
1166 		len = uio->uio_resid;
1167 		if (so->so_oobmark && len > so->so_oobmark - offset)
1168 			len = so->so_oobmark - offset;
1169 		if (len > m->m_len - moff)
1170 			len = m->m_len - moff;
1171 		/*
1172 		 * If mp is set, just pass back the mbufs.
1173 		 * Otherwise copy them out via the uio, then free.
1174 		 * Sockbuf must be consistent here (points to current mbuf,
1175 		 * it points to next record) when we drop priority;
1176 		 * we must note any additions to the sockbuf when we
1177 		 * block interrupts again.
1178 		 */
1179 		if (mp == 0) {
1180 			SBLASTRECORDCHK(&so->so_rcv, "soreceive uiomove");
1181 			SBLASTMBUFCHK(&so->so_rcv, "soreceive uiomove");
1182 			splx(s);
1183 			error = uiomove(mtod(m, caddr_t) + moff, (int)len, uio);
1184 			s = splsoftnet();
1185 			if (error) {
1186 				/*
1187 				 * If any part of the record has been removed
1188 				 * (such as the MT_SONAME mbuf, which will
1189 				 * happen when PR_ADDR, and thus also
1190 				 * PR_ATOMIC, is set), then drop the entire
1191 				 * record to maintain the atomicity of the
1192 				 * receive operation.
1193 				 *
1194 				 * This avoids a later panic("receive 1a")
1195 				 * when compiled with DIAGNOSTIC.
1196 				 */
1197 				if (m && mbuf_removed
1198 				    && (pr->pr_flags & PR_ATOMIC))
1199 					(void) sbdroprecord(&so->so_rcv);
1200 
1201 				goto release;
1202 			}
1203 		} else
1204 			uio->uio_resid -= len;
1205 		if (len == m->m_len - moff) {
1206 			if (m->m_flags & M_EOR)
1207 				flags |= MSG_EOR;
1208 			if (flags & MSG_PEEK) {
1209 				m = m->m_next;
1210 				moff = 0;
1211 			} else {
1212 				nextrecord = m->m_nextpkt;
1213 				sbfree(&so->so_rcv, m);
1214 				if (mp) {
1215 					*mp = m;
1216 					mp = &m->m_next;
1217 					so->so_rcv.sb_mb = m = m->m_next;
1218 					*mp = (struct mbuf *)0;
1219 				} else {
1220 					MFREE(m, so->so_rcv.sb_mb);
1221 					m = so->so_rcv.sb_mb;
1222 				}
1223 				/*
1224 				 * If m != NULL, we also know that
1225 				 * so->so_rcv.sb_mb != NULL.
1226 				 */
1227 				KASSERT(so->so_rcv.sb_mb == m);
1228 				if (m) {
1229 					m->m_nextpkt = nextrecord;
1230 					if (nextrecord == NULL)
1231 						so->so_rcv.sb_lastrecord = m;
1232 				} else {
1233 					so->so_rcv.sb_mb = nextrecord;
1234 					SB_EMPTY_FIXUP(&so->so_rcv);
1235 				}
1236 				SBLASTRECORDCHK(&so->so_rcv, "soreceive 3");
1237 				SBLASTMBUFCHK(&so->so_rcv, "soreceive 3");
1238 			}
1239 		} else {
1240 			if (flags & MSG_PEEK)
1241 				moff += len;
1242 			else {
1243 				if (mp)
1244 					*mp = m_copym(m, 0, len, M_WAIT);
1245 				m->m_data += len;
1246 				m->m_len -= len;
1247 				so->so_rcv.sb_cc -= len;
1248 			}
1249 		}
1250 		if (so->so_oobmark) {
1251 			if ((flags & MSG_PEEK) == 0) {
1252 				so->so_oobmark -= len;
1253 				if (so->so_oobmark == 0) {
1254 					so->so_state |= SS_RCVATMARK;
1255 					break;
1256 				}
1257 			} else {
1258 				offset += len;
1259 				if (offset == so->so_oobmark)
1260 					break;
1261 			}
1262 		}
1263 		if (flags & MSG_EOR)
1264 			break;
1265 		/*
1266 		 * If the MSG_WAITALL flag is set (for non-atomic socket),
1267 		 * we must not quit until "uio->uio_resid == 0" or an error
1268 		 * termination.  If a signal/timeout occurs, return
1269 		 * with a short count but without error.
1270 		 * Keep sockbuf locked against other readers.
1271 		 */
1272 		while (flags & MSG_WAITALL && m == 0 && uio->uio_resid > 0 &&
1273 		    !sosendallatonce(so) && !nextrecord) {
1274 			if (so->so_error || so->so_state & SS_CANTRCVMORE)
1275 				break;
1276 			/*
1277 			 * If we are peeking and the socket receive buffer is
1278 			 * full, stop since we can't get more data to peek at.
1279 			 */
1280 			if ((flags & MSG_PEEK) && sbspace(&so->so_rcv) <= 0)
1281 				break;
1282 			/*
1283 			 * If we've drained the socket buffer, tell the
1284 			 * protocol in case it needs to do something to
1285 			 * get it filled again.
1286 			 */
1287 			if ((pr->pr_flags & PR_WANTRCVD) && so->so_pcb)
1288 				(*pr->pr_usrreq)(so, PRU_RCVD,
1289 				    (struct mbuf *)0,
1290 				    (struct mbuf *)(long)flags,
1291 				    (struct mbuf *)0, l);
1292 			SBLASTRECORDCHK(&so->so_rcv, "soreceive sbwait 2");
1293 			SBLASTMBUFCHK(&so->so_rcv, "soreceive sbwait 2");
1294 			error = sbwait(&so->so_rcv);
1295 			if (error) {
1296 				sbunlock(&so->so_rcv);
1297 				splx(s);
1298 				return (0);
1299 			}
1300 			if ((m = so->so_rcv.sb_mb) != NULL)
1301 				nextrecord = m->m_nextpkt;
1302 		}
1303 	}
1304 
1305 	if (m && pr->pr_flags & PR_ATOMIC) {
1306 		flags |= MSG_TRUNC;
1307 		if ((flags & MSG_PEEK) == 0)
1308 			(void) sbdroprecord(&so->so_rcv);
1309 	}
1310 	if ((flags & MSG_PEEK) == 0) {
1311 		if (m == 0) {
1312 			/*
1313 			 * First part is an inline SB_EMPTY_FIXUP().  Second
1314 			 * part makes sure sb_lastrecord is up-to-date if
1315 			 * there is still data in the socket buffer.
1316 			 */
1317 			so->so_rcv.sb_mb = nextrecord;
1318 			if (so->so_rcv.sb_mb == NULL) {
1319 				so->so_rcv.sb_mbtail = NULL;
1320 				so->so_rcv.sb_lastrecord = NULL;
1321 			} else if (nextrecord->m_nextpkt == NULL)
1322 				so->so_rcv.sb_lastrecord = nextrecord;
1323 		}
1324 		SBLASTRECORDCHK(&so->so_rcv, "soreceive 4");
1325 		SBLASTMBUFCHK(&so->so_rcv, "soreceive 4");
1326 		if (pr->pr_flags & PR_WANTRCVD && so->so_pcb)
1327 			(*pr->pr_usrreq)(so, PRU_RCVD, (struct mbuf *)0,
1328 			    (struct mbuf *)(long)flags, (struct mbuf *)0, l);
1329 	}
1330 	if (orig_resid == uio->uio_resid && orig_resid &&
1331 	    (flags & MSG_EOR) == 0 && (so->so_state & SS_CANTRCVMORE) == 0) {
1332 		sbunlock(&so->so_rcv);
1333 		splx(s);
1334 		goto restart;
1335 	}
1336 
1337 	if (flagsp)
1338 		*flagsp |= flags;
1339  release:
1340 	sbunlock(&so->so_rcv);
1341 	splx(s);
1342 	return (error);
1343 }
1344 
1345 int
1346 soshutdown(struct socket *so, int how)
1347 {
1348 	const struct protosw	*pr;
1349 
1350 	pr = so->so_proto;
1351 	if (!(how == SHUT_RD || how == SHUT_WR || how == SHUT_RDWR))
1352 		return (EINVAL);
1353 
1354 	if (how == SHUT_RD || how == SHUT_RDWR)
1355 		sorflush(so);
1356 	if (how == SHUT_WR || how == SHUT_RDWR)
1357 		return (*pr->pr_usrreq)(so, PRU_SHUTDOWN, (struct mbuf *)0,
1358 		    (struct mbuf *)0, (struct mbuf *)0, (struct lwp *)0);
1359 	return (0);
1360 }
1361 
1362 void
1363 sorflush(struct socket *so)
1364 {
1365 	struct sockbuf	*sb, asb;
1366 	const struct protosw	*pr;
1367 	int		s;
1368 
1369 	sb = &so->so_rcv;
1370 	pr = so->so_proto;
1371 	sb->sb_flags |= SB_NOINTR;
1372 	(void) sblock(sb, M_WAITOK);
1373 	s = splnet();
1374 	socantrcvmore(so);
1375 	sbunlock(sb);
1376 	asb = *sb;
1377 	/*
1378 	 * Clear most of the sockbuf structure, but leave some of the
1379 	 * fields valid.
1380 	 */
1381 	memset(&sb->sb_startzero, 0,
1382 	    sizeof(*sb) - offsetof(struct sockbuf, sb_startzero));
1383 	splx(s);
1384 	if (pr->pr_flags & PR_RIGHTS && pr->pr_domain->dom_dispose)
1385 		(*pr->pr_domain->dom_dispose)(asb.sb_mb);
1386 	sbrelease(&asb, so);
1387 }
1388 
1389 int
1390 sosetopt(struct socket *so, int level, int optname, struct mbuf *m0)
1391 {
1392 	int		error;
1393 	struct mbuf	*m;
1394 
1395 	error = 0;
1396 	m = m0;
1397 	if (level != SOL_SOCKET) {
1398 		if (so->so_proto && so->so_proto->pr_ctloutput)
1399 			return ((*so->so_proto->pr_ctloutput)
1400 				  (PRCO_SETOPT, so, level, optname, &m0));
1401 		error = ENOPROTOOPT;
1402 	} else {
1403 		switch (optname) {
1404 
1405 		case SO_LINGER:
1406 			if (m == NULL || m->m_len != sizeof(struct linger)) {
1407 				error = EINVAL;
1408 				goto bad;
1409 			}
1410 			if (mtod(m, struct linger *)->l_linger < 0 ||
1411 			    mtod(m, struct linger *)->l_linger > (INT_MAX / hz)) {
1412 				error = EDOM;
1413 				goto bad;
1414 			}
1415 			so->so_linger = mtod(m, struct linger *)->l_linger;
1416 			/* fall thru... */
1417 
1418 		case SO_DEBUG:
1419 		case SO_KEEPALIVE:
1420 		case SO_DONTROUTE:
1421 		case SO_USELOOPBACK:
1422 		case SO_BROADCAST:
1423 		case SO_REUSEADDR:
1424 		case SO_REUSEPORT:
1425 		case SO_OOBINLINE:
1426 		case SO_TIMESTAMP:
1427 			if (m == NULL || m->m_len < sizeof(int)) {
1428 				error = EINVAL;
1429 				goto bad;
1430 			}
1431 			if (*mtod(m, int *))
1432 				so->so_options |= optname;
1433 			else
1434 				so->so_options &= ~optname;
1435 			break;
1436 
1437 		case SO_SNDBUF:
1438 		case SO_RCVBUF:
1439 		case SO_SNDLOWAT:
1440 		case SO_RCVLOWAT:
1441 		    {
1442 			int optval;
1443 
1444 			if (m == NULL || m->m_len < sizeof(int)) {
1445 				error = EINVAL;
1446 				goto bad;
1447 			}
1448 
1449 			/*
1450 			 * Values < 1 make no sense for any of these
1451 			 * options, so disallow them.
1452 			 */
1453 			optval = *mtod(m, int *);
1454 			if (optval < 1) {
1455 				error = EINVAL;
1456 				goto bad;
1457 			}
1458 
1459 			switch (optname) {
1460 
1461 			case SO_SNDBUF:
1462 			case SO_RCVBUF:
1463 				if (sbreserve(optname == SO_SNDBUF ?
1464 				    &so->so_snd : &so->so_rcv,
1465 				    (u_long) optval, so) == 0) {
1466 					error = ENOBUFS;
1467 					goto bad;
1468 				}
1469 				break;
1470 
1471 			/*
1472 			 * Make sure the low-water is never greater than
1473 			 * the high-water.
1474 			 */
1475 			case SO_SNDLOWAT:
1476 				so->so_snd.sb_lowat =
1477 				    (optval > so->so_snd.sb_hiwat) ?
1478 				    so->so_snd.sb_hiwat : optval;
1479 				break;
1480 			case SO_RCVLOWAT:
1481 				so->so_rcv.sb_lowat =
1482 				    (optval > so->so_rcv.sb_hiwat) ?
1483 				    so->so_rcv.sb_hiwat : optval;
1484 				break;
1485 			}
1486 			break;
1487 		    }
1488 
1489 		case SO_SNDTIMEO:
1490 		case SO_RCVTIMEO:
1491 		    {
1492 			struct timeval *tv;
1493 			int val;
1494 
1495 			if (m == NULL || m->m_len < sizeof(*tv)) {
1496 				error = EINVAL;
1497 				goto bad;
1498 			}
1499 			tv = mtod(m, struct timeval *);
1500 			if (tv->tv_sec > (INT_MAX - tv->tv_usec / tick) / hz) {
1501 				error = EDOM;
1502 				goto bad;
1503 			}
1504 			val = tv->tv_sec * hz + tv->tv_usec / tick;
1505 			if (val == 0 && tv->tv_usec != 0)
1506 				val = 1;
1507 
1508 			switch (optname) {
1509 
1510 			case SO_SNDTIMEO:
1511 				so->so_snd.sb_timeo = val;
1512 				break;
1513 			case SO_RCVTIMEO:
1514 				so->so_rcv.sb_timeo = val;
1515 				break;
1516 			}
1517 			break;
1518 		    }
1519 
1520 		default:
1521 			error = ENOPROTOOPT;
1522 			break;
1523 		}
1524 		if (error == 0 && so->so_proto && so->so_proto->pr_ctloutput) {
1525 			(void) ((*so->so_proto->pr_ctloutput)
1526 				  (PRCO_SETOPT, so, level, optname, &m0));
1527 			m = NULL;	/* freed by protocol */
1528 		}
1529 	}
1530  bad:
1531 	if (m)
1532 		(void) m_free(m);
1533 	return (error);
1534 }
1535 
1536 int
1537 sogetopt(struct socket *so, int level, int optname, struct mbuf **mp)
1538 {
1539 	struct mbuf	*m;
1540 
1541 	if (level != SOL_SOCKET) {
1542 		if (so->so_proto && so->so_proto->pr_ctloutput) {
1543 			return ((*so->so_proto->pr_ctloutput)
1544 				  (PRCO_GETOPT, so, level, optname, mp));
1545 		} else
1546 			return (ENOPROTOOPT);
1547 	} else {
1548 		m = m_get(M_WAIT, MT_SOOPTS);
1549 		m->m_len = sizeof(int);
1550 
1551 		switch (optname) {
1552 
1553 		case SO_LINGER:
1554 			m->m_len = sizeof(struct linger);
1555 			mtod(m, struct linger *)->l_onoff =
1556 				so->so_options & SO_LINGER;
1557 			mtod(m, struct linger *)->l_linger = so->so_linger;
1558 			break;
1559 
1560 		case SO_USELOOPBACK:
1561 		case SO_DONTROUTE:
1562 		case SO_DEBUG:
1563 		case SO_KEEPALIVE:
1564 		case SO_REUSEADDR:
1565 		case SO_REUSEPORT:
1566 		case SO_BROADCAST:
1567 		case SO_OOBINLINE:
1568 		case SO_TIMESTAMP:
1569 			*mtod(m, int *) = so->so_options & optname;
1570 			break;
1571 
1572 		case SO_TYPE:
1573 			*mtod(m, int *) = so->so_type;
1574 			break;
1575 
1576 		case SO_ERROR:
1577 			*mtod(m, int *) = so->so_error;
1578 			so->so_error = 0;
1579 			break;
1580 
1581 		case SO_SNDBUF:
1582 			*mtod(m, int *) = so->so_snd.sb_hiwat;
1583 			break;
1584 
1585 		case SO_RCVBUF:
1586 			*mtod(m, int *) = so->so_rcv.sb_hiwat;
1587 			break;
1588 
1589 		case SO_SNDLOWAT:
1590 			*mtod(m, int *) = so->so_snd.sb_lowat;
1591 			break;
1592 
1593 		case SO_RCVLOWAT:
1594 			*mtod(m, int *) = so->so_rcv.sb_lowat;
1595 			break;
1596 
1597 		case SO_SNDTIMEO:
1598 		case SO_RCVTIMEO:
1599 		    {
1600 			int val = (optname == SO_SNDTIMEO ?
1601 			     so->so_snd.sb_timeo : so->so_rcv.sb_timeo);
1602 
1603 			m->m_len = sizeof(struct timeval);
1604 			mtod(m, struct timeval *)->tv_sec = val / hz;
1605 			mtod(m, struct timeval *)->tv_usec =
1606 			    (val % hz) * tick;
1607 			break;
1608 		    }
1609 
1610 		case SO_OVERFLOWED:
1611 			*mtod(m, int *) = so->so_rcv.sb_overflowed;
1612 			break;
1613 
1614 		default:
1615 			(void)m_free(m);
1616 			return (ENOPROTOOPT);
1617 		}
1618 		*mp = m;
1619 		return (0);
1620 	}
1621 }
1622 
1623 void
1624 sohasoutofband(struct socket *so)
1625 {
1626 	fownsignal(so->so_pgid, SIGURG, POLL_PRI, POLLPRI|POLLRDBAND, so);
1627 	selwakeup(&so->so_rcv.sb_sel);
1628 }
1629 
1630 static void
1631 filt_sordetach(struct knote *kn)
1632 {
1633 	struct socket	*so;
1634 
1635 	so = (struct socket *)kn->kn_fp->f_data;
1636 	SLIST_REMOVE(&so->so_rcv.sb_sel.sel_klist, kn, knote, kn_selnext);
1637 	if (SLIST_EMPTY(&so->so_rcv.sb_sel.sel_klist))
1638 		so->so_rcv.sb_flags &= ~SB_KNOTE;
1639 }
1640 
1641 /*ARGSUSED*/
1642 static int
1643 filt_soread(struct knote *kn, long hint)
1644 {
1645 	struct socket	*so;
1646 
1647 	so = (struct socket *)kn->kn_fp->f_data;
1648 	kn->kn_data = so->so_rcv.sb_cc;
1649 	if (so->so_state & SS_CANTRCVMORE) {
1650 		kn->kn_flags |= EV_EOF;
1651 		kn->kn_fflags = so->so_error;
1652 		return (1);
1653 	}
1654 	if (so->so_error)	/* temporary udp error */
1655 		return (1);
1656 	if (kn->kn_sfflags & NOTE_LOWAT)
1657 		return (kn->kn_data >= kn->kn_sdata);
1658 	return (kn->kn_data >= so->so_rcv.sb_lowat);
1659 }
1660 
1661 static void
1662 filt_sowdetach(struct knote *kn)
1663 {
1664 	struct socket	*so;
1665 
1666 	so = (struct socket *)kn->kn_fp->f_data;
1667 	SLIST_REMOVE(&so->so_snd.sb_sel.sel_klist, kn, knote, kn_selnext);
1668 	if (SLIST_EMPTY(&so->so_snd.sb_sel.sel_klist))
1669 		so->so_snd.sb_flags &= ~SB_KNOTE;
1670 }
1671 
1672 /*ARGSUSED*/
1673 static int
1674 filt_sowrite(struct knote *kn, long hint)
1675 {
1676 	struct socket	*so;
1677 
1678 	so = (struct socket *)kn->kn_fp->f_data;
1679 	kn->kn_data = sbspace(&so->so_snd);
1680 	if (so->so_state & SS_CANTSENDMORE) {
1681 		kn->kn_flags |= EV_EOF;
1682 		kn->kn_fflags = so->so_error;
1683 		return (1);
1684 	}
1685 	if (so->so_error)	/* temporary udp error */
1686 		return (1);
1687 	if (((so->so_state & SS_ISCONNECTED) == 0) &&
1688 	    (so->so_proto->pr_flags & PR_CONNREQUIRED))
1689 		return (0);
1690 	if (kn->kn_sfflags & NOTE_LOWAT)
1691 		return (kn->kn_data >= kn->kn_sdata);
1692 	return (kn->kn_data >= so->so_snd.sb_lowat);
1693 }
1694 
1695 /*ARGSUSED*/
1696 static int
1697 filt_solisten(struct knote *kn, long hint)
1698 {
1699 	struct socket	*so;
1700 
1701 	so = (struct socket *)kn->kn_fp->f_data;
1702 
1703 	/*
1704 	 * Set kn_data to number of incoming connections, not
1705 	 * counting partial (incomplete) connections.
1706 	 */
1707 	kn->kn_data = so->so_qlen;
1708 	return (kn->kn_data > 0);
1709 }
1710 
1711 static const struct filterops solisten_filtops =
1712 	{ 1, NULL, filt_sordetach, filt_solisten };
1713 static const struct filterops soread_filtops =
1714 	{ 1, NULL, filt_sordetach, filt_soread };
1715 static const struct filterops sowrite_filtops =
1716 	{ 1, NULL, filt_sowdetach, filt_sowrite };
1717 
1718 int
1719 soo_kqfilter(struct file *fp, struct knote *kn)
1720 {
1721 	struct socket	*so;
1722 	struct sockbuf	*sb;
1723 
1724 	so = (struct socket *)kn->kn_fp->f_data;
1725 	switch (kn->kn_filter) {
1726 	case EVFILT_READ:
1727 		if (so->so_options & SO_ACCEPTCONN)
1728 			kn->kn_fop = &solisten_filtops;
1729 		else
1730 			kn->kn_fop = &soread_filtops;
1731 		sb = &so->so_rcv;
1732 		break;
1733 	case EVFILT_WRITE:
1734 		kn->kn_fop = &sowrite_filtops;
1735 		sb = &so->so_snd;
1736 		break;
1737 	default:
1738 		return (1);
1739 	}
1740 	SLIST_INSERT_HEAD(&sb->sb_sel.sel_klist, kn, kn_selnext);
1741 	sb->sb_flags |= SB_KNOTE;
1742 	return (0);
1743 }
1744 
1745 #include <sys/sysctl.h>
1746 
1747 static int sysctl_kern_somaxkva(SYSCTLFN_PROTO);
1748 
1749 /*
1750  * sysctl helper routine for kern.somaxkva.  ensures that the given
1751  * value is not too small.
1752  * (XXX should we maybe make sure it's not too large as well?)
1753  */
1754 static int
1755 sysctl_kern_somaxkva(SYSCTLFN_ARGS)
1756 {
1757 	int error, new_somaxkva;
1758 	struct sysctlnode node;
1759 	int s;
1760 
1761 	new_somaxkva = somaxkva;
1762 	node = *rnode;
1763 	node.sysctl_data = &new_somaxkva;
1764 	error = sysctl_lookup(SYSCTLFN_CALL(&node));
1765 	if (error || newp == NULL)
1766 		return (error);
1767 
1768 	if (new_somaxkva < (16 * 1024 * 1024)) /* sanity */
1769 		return (EINVAL);
1770 
1771 	s = splvm();
1772 	simple_lock(&so_pendfree_slock);
1773 	somaxkva = new_somaxkva;
1774 	wakeup(&socurkva);
1775 	simple_unlock(&so_pendfree_slock);
1776 	splx(s);
1777 
1778 	return (error);
1779 }
1780 
1781 SYSCTL_SETUP(sysctl_kern_somaxkva_setup, "sysctl kern.somaxkva setup")
1782 {
1783 
1784 	sysctl_createv(clog, 0, NULL, NULL,
1785 		       CTLFLAG_PERMANENT,
1786 		       CTLTYPE_NODE, "kern", NULL,
1787 		       NULL, 0, NULL, 0,
1788 		       CTL_KERN, CTL_EOL);
1789 
1790 	sysctl_createv(clog, 0, NULL, NULL,
1791 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
1792 		       CTLTYPE_INT, "somaxkva",
1793 		       SYSCTL_DESCR("Maximum amount of kernel memory to be "
1794 				    "used for socket buffers"),
1795 		       sysctl_kern_somaxkva, 0, NULL, 0,
1796 		       CTL_KERN, KERN_SOMAXKVA, CTL_EOL);
1797 }
1798