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