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