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