xref: /netbsd-src/sys/kern/uipc_socket.c (revision da9817918ec7e88db2912a2882967c7570a83f47)
1 /*	$NetBSD: uipc_socket.c,v 1.189 2009/04/30 20:41:33 ad Exp $	*/
2 
3 /*-
4  * Copyright (c) 2002, 2007, 2008, 2009 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, and by Andrew Doran.
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  *
19  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
20  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
21  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
22  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
23  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
24  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
25  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
26  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
27  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
28  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
29  * POSSIBILITY OF SUCH DAMAGE.
30  */
31 
32 /*
33  * Copyright (c) 2004 The FreeBSD Foundation
34  * Copyright (c) 2004 Robert Watson
35  * Copyright (c) 1982, 1986, 1988, 1990, 1993
36  *	The Regents of the University of California.  All rights reserved.
37  *
38  * Redistribution and use in source and binary forms, with or without
39  * modification, are permitted provided that the following conditions
40  * are met:
41  * 1. Redistributions of source code must retain the above copyright
42  *    notice, this list of conditions and the following disclaimer.
43  * 2. Redistributions in binary form must reproduce the above copyright
44  *    notice, this list of conditions and the following disclaimer in the
45  *    documentation and/or other materials provided with the distribution.
46  * 3. Neither the name of the University nor the names of its contributors
47  *    may be used to endorse or promote products derived from this software
48  *    without specific prior written permission.
49  *
50  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
51  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
52  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
53  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
54  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
55  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
56  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
57  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
58  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
59  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
60  * SUCH DAMAGE.
61  *
62  *	@(#)uipc_socket.c	8.6 (Berkeley) 5/2/95
63  */
64 
65 #include <sys/cdefs.h>
66 __KERNEL_RCSID(0, "$NetBSD: uipc_socket.c,v 1.189 2009/04/30 20:41:33 ad Exp $");
67 
68 #include "opt_compat_netbsd.h"
69 #include "opt_sock_counters.h"
70 #include "opt_sosend_loan.h"
71 #include "opt_mbuftrace.h"
72 #include "opt_somaxkva.h"
73 #include "opt_multiprocessor.h"	/* XXX */
74 
75 #include <sys/param.h>
76 #include <sys/systm.h>
77 #include <sys/proc.h>
78 #include <sys/file.h>
79 #include <sys/filedesc.h>
80 #include <sys/kmem.h>
81 #include <sys/mbuf.h>
82 #include <sys/domain.h>
83 #include <sys/kernel.h>
84 #include <sys/protosw.h>
85 #include <sys/socket.h>
86 #include <sys/socketvar.h>
87 #include <sys/signalvar.h>
88 #include <sys/resourcevar.h>
89 #include <sys/uidinfo.h>
90 #include <sys/event.h>
91 #include <sys/poll.h>
92 #include <sys/kauth.h>
93 #include <sys/mutex.h>
94 #include <sys/condvar.h>
95 
96 #ifdef COMPAT_50
97 #include <compat/sys/time.h>
98 #include <compat/sys/socket.h>
99 #endif
100 
101 #include <uvm/uvm.h>
102 
103 MALLOC_DEFINE(M_SOOPTS, "soopts", "socket options");
104 MALLOC_DEFINE(M_SONAME, "soname", "socket name");
105 
106 extern const struct fileops socketops;
107 
108 extern int	somaxconn;			/* patchable (XXX sysctl) */
109 int		somaxconn = SOMAXCONN;
110 kmutex_t	*softnet_lock;
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 #if defined(SOSEND_NO_LOAN) || defined(MULTIPROCESSOR)
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 void sysctl_kern_somaxkva_setup(void);
160 static struct sysctllog *socket_sysctllog;
161 
162 static vsize_t
163 sokvareserve(struct socket *so, vsize_t len)
164 {
165 	int error;
166 
167 	mutex_enter(&so_pendfree_lock);
168 	while (socurkva + len > somaxkva) {
169 		size_t freed;
170 
171 		/*
172 		 * try to do pendfree.
173 		 */
174 
175 		freed = sodopendfreel();
176 
177 		/*
178 		 * if some kva was freed, try again.
179 		 */
180 
181 		if (freed)
182 			continue;
183 
184 		SOSEND_COUNTER_INCR(&sosend_kvalimit);
185 		error = cv_wait_sig(&socurkva_cv, &so_pendfree_lock);
186 		if (error) {
187 			len = 0;
188 			break;
189 		}
190 	}
191 	socurkva += len;
192 	mutex_exit(&so_pendfree_lock);
193 	return len;
194 }
195 
196 static void
197 sokvaunreserve(vsize_t len)
198 {
199 
200 	mutex_enter(&so_pendfree_lock);
201 	socurkva -= len;
202 	cv_broadcast(&socurkva_cv);
203 	mutex_exit(&so_pendfree_lock);
204 }
205 
206 /*
207  * sokvaalloc: allocate kva for loan.
208  */
209 
210 vaddr_t
211 sokvaalloc(vsize_t len, struct socket *so)
212 {
213 	vaddr_t lva;
214 
215 	/*
216 	 * reserve kva.
217 	 */
218 
219 	if (sokvareserve(so, len) == 0)
220 		return 0;
221 
222 	/*
223 	 * allocate kva.
224 	 */
225 
226 	lva = uvm_km_alloc(kernel_map, len, 0, UVM_KMF_VAONLY | UVM_KMF_WAITVA);
227 	if (lva == 0) {
228 		sokvaunreserve(len);
229 		return (0);
230 	}
231 
232 	return lva;
233 }
234 
235 /*
236  * sokvafree: free kva for loan.
237  */
238 
239 void
240 sokvafree(vaddr_t sva, vsize_t len)
241 {
242 
243 	/*
244 	 * free kva.
245 	 */
246 
247 	uvm_km_free(kernel_map, sva, len, UVM_KMF_VAONLY);
248 
249 	/*
250 	 * unreserve kva.
251 	 */
252 
253 	sokvaunreserve(len);
254 }
255 
256 static void
257 sodoloanfree(struct vm_page **pgs, void *buf, size_t size)
258 {
259 	vaddr_t sva, eva;
260 	vsize_t len;
261 	int npgs;
262 
263 	KASSERT(pgs != NULL);
264 
265 	eva = round_page((vaddr_t) buf + size);
266 	sva = trunc_page((vaddr_t) buf);
267 	len = eva - sva;
268 	npgs = len >> PAGE_SHIFT;
269 
270 	pmap_kremove(sva, len);
271 	pmap_update(pmap_kernel());
272 	uvm_unloan(pgs, npgs, UVM_LOAN_TOPAGE);
273 	sokvafree(sva, len);
274 }
275 
276 static size_t
277 sodopendfree(void)
278 {
279 	size_t rv;
280 
281 	if (__predict_true(so_pendfree == NULL))
282 		return 0;
283 
284 	mutex_enter(&so_pendfree_lock);
285 	rv = sodopendfreel();
286 	mutex_exit(&so_pendfree_lock);
287 
288 	return rv;
289 }
290 
291 /*
292  * sodopendfreel: free mbufs on "pendfree" list.
293  * unlock and relock so_pendfree_lock when freeing mbufs.
294  *
295  * => called with so_pendfree_lock held.
296  */
297 
298 static size_t
299 sodopendfreel(void)
300 {
301 	struct mbuf *m, *next;
302 	size_t rv = 0;
303 
304 	KASSERT(mutex_owned(&so_pendfree_lock));
305 
306 	while (so_pendfree != NULL) {
307 		m = so_pendfree;
308 		so_pendfree = NULL;
309 		mutex_exit(&so_pendfree_lock);
310 
311 		for (; m != NULL; m = next) {
312 			next = m->m_next;
313 			KASSERT((~m->m_flags & (M_EXT|M_EXT_PAGES)) == 0);
314 			KASSERT(m->m_ext.ext_refcnt == 0);
315 
316 			rv += m->m_ext.ext_size;
317 			sodoloanfree(m->m_ext.ext_pgs, m->m_ext.ext_buf,
318 			    m->m_ext.ext_size);
319 			pool_cache_put(mb_cache, m);
320 		}
321 
322 		mutex_enter(&so_pendfree_lock);
323 	}
324 
325 	return (rv);
326 }
327 
328 void
329 soloanfree(struct mbuf *m, void *buf, size_t size, void *arg)
330 {
331 
332 	KASSERT(m != NULL);
333 
334 	/*
335 	 * postpone freeing mbuf.
336 	 *
337 	 * we can't do it in interrupt context
338 	 * because we need to put kva back to kernel_map.
339 	 */
340 
341 	mutex_enter(&so_pendfree_lock);
342 	m->m_next = so_pendfree;
343 	so_pendfree = m;
344 	cv_broadcast(&socurkva_cv);
345 	mutex_exit(&so_pendfree_lock);
346 }
347 
348 static long
349 sosend_loan(struct socket *so, struct uio *uio, struct mbuf *m, long space)
350 {
351 	struct iovec *iov = uio->uio_iov;
352 	vaddr_t sva, eva;
353 	vsize_t len;
354 	vaddr_t lva;
355 	int npgs, error;
356 	vaddr_t va;
357 	int i;
358 
359 	if (VMSPACE_IS_KERNEL_P(uio->uio_vmspace))
360 		return (0);
361 
362 	if (iov->iov_len < (size_t) space)
363 		space = iov->iov_len;
364 	if (space > SOCK_LOAN_CHUNK)
365 		space = SOCK_LOAN_CHUNK;
366 
367 	eva = round_page((vaddr_t) iov->iov_base + space);
368 	sva = trunc_page((vaddr_t) iov->iov_base);
369 	len = eva - sva;
370 	npgs = len >> PAGE_SHIFT;
371 
372 	KASSERT(npgs <= M_EXT_MAXPAGES);
373 
374 	lva = sokvaalloc(len, so);
375 	if (lva == 0)
376 		return 0;
377 
378 	error = uvm_loan(&uio->uio_vmspace->vm_map, sva, len,
379 	    m->m_ext.ext_pgs, UVM_LOAN_TOPAGE);
380 	if (error) {
381 		sokvafree(lva, len);
382 		return (0);
383 	}
384 
385 	for (i = 0, va = lva; i < npgs; i++, va += PAGE_SIZE)
386 		pmap_kenter_pa(va, VM_PAGE_TO_PHYS(m->m_ext.ext_pgs[i]),
387 		    VM_PROT_READ);
388 	pmap_update(pmap_kernel());
389 
390 	lva += (vaddr_t) iov->iov_base & PAGE_MASK;
391 
392 	MEXTADD(m, (void *) lva, space, M_MBUF, soloanfree, so);
393 	m->m_flags |= M_EXT_PAGES | M_EXT_ROMAP;
394 
395 	uio->uio_resid -= space;
396 	/* uio_offset not updated, not set/used for write(2) */
397 	uio->uio_iov->iov_base = (char *)uio->uio_iov->iov_base + space;
398 	uio->uio_iov->iov_len -= space;
399 	if (uio->uio_iov->iov_len == 0) {
400 		uio->uio_iov++;
401 		uio->uio_iovcnt--;
402 	}
403 
404 	return (space);
405 }
406 
407 static int
408 sokva_reclaim_callback(struct callback_entry *ce, void *obj, void *arg)
409 {
410 
411 	KASSERT(ce == &sokva_reclaimerentry);
412 	KASSERT(obj == NULL);
413 
414 	sodopendfree();
415 	if (!vm_map_starved_p(kernel_map)) {
416 		return CALLBACK_CHAIN_ABORT;
417 	}
418 	return CALLBACK_CHAIN_CONTINUE;
419 }
420 
421 struct mbuf *
422 getsombuf(struct socket *so, int type)
423 {
424 	struct mbuf *m;
425 
426 	m = m_get(M_WAIT, type);
427 	MCLAIM(m, so->so_mowner);
428 	return m;
429 }
430 
431 void
432 soinit(void)
433 {
434 
435 	sysctl_kern_somaxkva_setup();
436 
437 	mutex_init(&so_pendfree_lock, MUTEX_DEFAULT, IPL_VM);
438 	softnet_lock = mutex_obj_alloc(MUTEX_DEFAULT, IPL_NONE);
439 	cv_init(&socurkva_cv, "sokva");
440 	soinit2();
441 
442 	/* Set the initial adjusted socket buffer size. */
443 	if (sb_max_set(sb_max))
444 		panic("bad initial sb_max value: %lu", sb_max);
445 
446 	callback_register(&vm_map_to_kernel(kernel_map)->vmk_reclaim_callback,
447 	    &sokva_reclaimerentry, NULL, sokva_reclaim_callback);
448 }
449 
450 /*
451  * Socket operation routines.
452  * These routines are called by the routines in
453  * sys_socket.c or from a system process, and
454  * implement the semantics of socket operations by
455  * switching out to the protocol specific routines.
456  */
457 /*ARGSUSED*/
458 int
459 socreate(int dom, struct socket **aso, int type, int proto, struct lwp *l,
460 	 struct socket *lockso)
461 {
462 	const struct protosw	*prp;
463 	struct socket	*so;
464 	uid_t		uid;
465 	int		error;
466 	kmutex_t	*lock;
467 
468 	error = kauth_authorize_network(l->l_cred, KAUTH_NETWORK_SOCKET,
469 	    KAUTH_REQ_NETWORK_SOCKET_OPEN, KAUTH_ARG(dom), KAUTH_ARG(type),
470 	    KAUTH_ARG(proto));
471 	if (error != 0)
472 		return error;
473 
474 	if (proto)
475 		prp = pffindproto(dom, proto, type);
476 	else
477 		prp = pffindtype(dom, type);
478 	if (prp == NULL) {
479 		/* no support for domain */
480 		if (pffinddomain(dom) == 0)
481 			return EAFNOSUPPORT;
482 		/* no support for socket type */
483 		if (proto == 0 && type != 0)
484 			return EPROTOTYPE;
485 		return EPROTONOSUPPORT;
486 	}
487 	if (prp->pr_usrreq == NULL)
488 		return EPROTONOSUPPORT;
489 	if (prp->pr_type != type)
490 		return EPROTOTYPE;
491 
492 	so = soget(true);
493 	so->so_type = type;
494 	so->so_proto = prp;
495 	so->so_send = sosend;
496 	so->so_receive = soreceive;
497 #ifdef MBUFTRACE
498 	so->so_rcv.sb_mowner = &prp->pr_domain->dom_mowner;
499 	so->so_snd.sb_mowner = &prp->pr_domain->dom_mowner;
500 	so->so_mowner = &prp->pr_domain->dom_mowner;
501 #endif
502 	uid = kauth_cred_geteuid(l->l_cred);
503 	so->so_uidinfo = uid_find(uid);
504 	so->so_egid = kauth_cred_getegid(l->l_cred);
505 	so->so_cpid = l->l_proc->p_pid;
506 	if (lockso != NULL) {
507 		/* Caller wants us to share a lock. */
508 		lock = lockso->so_lock;
509 		so->so_lock = lock;
510 		mutex_obj_hold(lock);
511 		mutex_enter(lock);
512 	} else {
513 		/* Lock assigned and taken during PRU_ATTACH. */
514 	}
515 	error = (*prp->pr_usrreq)(so, PRU_ATTACH, NULL,
516 	    (struct mbuf *)(long)proto, NULL, l);
517 	KASSERT(solocked(so));
518 	if (error != 0) {
519 		so->so_state |= SS_NOFDREF;
520 		sofree(so);
521 		return error;
522 	}
523 	sounlock(so);
524 	*aso = so;
525 	return 0;
526 }
527 
528 /* On success, write file descriptor to fdout and return zero.  On
529  * failure, return non-zero; *fdout will be undefined.
530  */
531 int
532 fsocreate(int domain, struct socket **sop, int type, int protocol,
533     struct lwp *l, int *fdout)
534 {
535 	struct socket	*so;
536 	struct file	*fp;
537 	int		fd, error;
538 
539 	if ((error = fd_allocfile(&fp, &fd)) != 0)
540 		return (error);
541 	fp->f_flag = FREAD|FWRITE;
542 	fp->f_type = DTYPE_SOCKET;
543 	fp->f_ops = &socketops;
544 	error = socreate(domain, &so, type, protocol, l, NULL);
545 	if (error != 0) {
546 		fd_abort(curproc, fp, fd);
547 	} else {
548 		if (sop != NULL)
549 			*sop = so;
550 		fp->f_data = so;
551 		fd_affix(curproc, fp, fd);
552 		*fdout = fd;
553 	}
554 	return error;
555 }
556 
557 int
558 sobind(struct socket *so, struct mbuf *nam, struct lwp *l)
559 {
560 	int	error;
561 
562 	solock(so);
563 	error = (*so->so_proto->pr_usrreq)(so, PRU_BIND, NULL, nam, NULL, l);
564 	sounlock(so);
565 	return error;
566 }
567 
568 int
569 solisten(struct socket *so, int backlog, struct lwp *l)
570 {
571 	int	error;
572 
573 	solock(so);
574 	if ((so->so_state & (SS_ISCONNECTED | SS_ISCONNECTING |
575 	    SS_ISDISCONNECTING)) != 0) {
576 	    	sounlock(so);
577 		return (EOPNOTSUPP);
578 	}
579 	error = (*so->so_proto->pr_usrreq)(so, PRU_LISTEN, NULL,
580 	    NULL, NULL, l);
581 	if (error != 0) {
582 		sounlock(so);
583 		return error;
584 	}
585 	if (TAILQ_EMPTY(&so->so_q))
586 		so->so_options |= SO_ACCEPTCONN;
587 	if (backlog < 0)
588 		backlog = 0;
589 	so->so_qlimit = min(backlog, somaxconn);
590 	sounlock(so);
591 	return 0;
592 }
593 
594 void
595 sofree(struct socket *so)
596 {
597 	u_int refs;
598 
599 	KASSERT(solocked(so));
600 
601 	if (so->so_pcb || (so->so_state & SS_NOFDREF) == 0) {
602 		sounlock(so);
603 		return;
604 	}
605 	if (so->so_head) {
606 		/*
607 		 * We must not decommission a socket that's on the accept(2)
608 		 * queue.  If we do, then accept(2) may hang after select(2)
609 		 * indicated that the listening socket was ready.
610 		 */
611 		if (!soqremque(so, 0)) {
612 			sounlock(so);
613 			return;
614 		}
615 	}
616 	if (so->so_rcv.sb_hiwat)
617 		(void)chgsbsize(so->so_uidinfo, &so->so_rcv.sb_hiwat, 0,
618 		    RLIM_INFINITY);
619 	if (so->so_snd.sb_hiwat)
620 		(void)chgsbsize(so->so_uidinfo, &so->so_snd.sb_hiwat, 0,
621 		    RLIM_INFINITY);
622 	sbrelease(&so->so_snd, so);
623 	KASSERT(!cv_has_waiters(&so->so_cv));
624 	KASSERT(!cv_has_waiters(&so->so_rcv.sb_cv));
625 	KASSERT(!cv_has_waiters(&so->so_snd.sb_cv));
626 	sorflush(so);
627 	refs = so->so_aborting;	/* XXX */
628 	/* Remove acccept filter if one is present. */
629 	if (so->so_accf != NULL)
630 		(void)accept_filt_clear(so);
631 	sounlock(so);
632 	if (refs == 0)		/* XXX */
633 		soput(so);
634 }
635 
636 /*
637  * Close a socket on last file table reference removal.
638  * Initiate disconnect if connected.
639  * Free socket when disconnect complete.
640  */
641 int
642 soclose(struct socket *so)
643 {
644 	struct socket	*so2;
645 	int		error;
646 	int		error2;
647 
648 	error = 0;
649 	solock(so);
650 	if (so->so_options & SO_ACCEPTCONN) {
651 		for (;;) {
652 			if ((so2 = TAILQ_FIRST(&so->so_q0)) != 0) {
653 				KASSERT(solocked2(so, so2));
654 				(void) soqremque(so2, 0);
655 				/* soabort drops the lock. */
656 				(void) soabort(so2);
657 				solock(so);
658 				continue;
659 			}
660 			if ((so2 = TAILQ_FIRST(&so->so_q)) != 0) {
661 				KASSERT(solocked2(so, so2));
662 				(void) soqremque(so2, 1);
663 				/* soabort drops the lock. */
664 				(void) soabort(so2);
665 				solock(so);
666 				continue;
667 			}
668 			break;
669 		}
670 	}
671 	if (so->so_pcb == 0)
672 		goto discard;
673 	if (so->so_state & SS_ISCONNECTED) {
674 		if ((so->so_state & SS_ISDISCONNECTING) == 0) {
675 			error = sodisconnect(so);
676 			if (error)
677 				goto drop;
678 		}
679 		if (so->so_options & SO_LINGER) {
680 			if ((so->so_state & SS_ISDISCONNECTING) && so->so_nbio)
681 				goto drop;
682 			while (so->so_state & SS_ISCONNECTED) {
683 				error = sowait(so, true, so->so_linger * hz);
684 				if (error)
685 					break;
686 			}
687 		}
688 	}
689  drop:
690 	if (so->so_pcb) {
691 		error2 = (*so->so_proto->pr_usrreq)(so, PRU_DETACH,
692 		    NULL, NULL, NULL, NULL);
693 		if (error == 0)
694 			error = error2;
695 	}
696  discard:
697 	if (so->so_state & SS_NOFDREF)
698 		panic("soclose: NOFDREF");
699 	so->so_state |= SS_NOFDREF;
700 	sofree(so);
701 	return (error);
702 }
703 
704 /*
705  * Must be called with the socket locked..  Will return with it unlocked.
706  */
707 int
708 soabort(struct socket *so)
709 {
710 	u_int refs;
711 	int error;
712 
713 	KASSERT(solocked(so));
714 	KASSERT(so->so_head == NULL);
715 
716 	so->so_aborting++;		/* XXX */
717 	error = (*so->so_proto->pr_usrreq)(so, PRU_ABORT, NULL,
718 	    NULL, NULL, NULL);
719 	refs = --so->so_aborting;	/* XXX */
720 	if (error || (refs == 0)) {
721 		sofree(so);
722 	} else {
723 		sounlock(so);
724 	}
725 	return error;
726 }
727 
728 int
729 soaccept(struct socket *so, struct mbuf *nam)
730 {
731 	int	error;
732 
733 	KASSERT(solocked(so));
734 
735 	error = 0;
736 	if ((so->so_state & SS_NOFDREF) == 0)
737 		panic("soaccept: !NOFDREF");
738 	so->so_state &= ~SS_NOFDREF;
739 	if ((so->so_state & SS_ISDISCONNECTED) == 0 ||
740 	    (so->so_proto->pr_flags & PR_ABRTACPTDIS) == 0)
741 		error = (*so->so_proto->pr_usrreq)(so, PRU_ACCEPT,
742 		    NULL, nam, NULL, NULL);
743 	else
744 		error = ECONNABORTED;
745 
746 	return (error);
747 }
748 
749 int
750 soconnect(struct socket *so, struct mbuf *nam, struct lwp *l)
751 {
752 	int		error;
753 
754 	KASSERT(solocked(so));
755 
756 	if (so->so_options & SO_ACCEPTCONN)
757 		return (EOPNOTSUPP);
758 	/*
759 	 * If protocol is connection-based, can only connect once.
760 	 * Otherwise, if connected, try to disconnect first.
761 	 * This allows user to disconnect by connecting to, e.g.,
762 	 * a null address.
763 	 */
764 	if (so->so_state & (SS_ISCONNECTED|SS_ISCONNECTING) &&
765 	    ((so->so_proto->pr_flags & PR_CONNREQUIRED) ||
766 	    (error = sodisconnect(so))))
767 		error = EISCONN;
768 	else
769 		error = (*so->so_proto->pr_usrreq)(so, PRU_CONNECT,
770 		    NULL, nam, NULL, l);
771 	return (error);
772 }
773 
774 int
775 soconnect2(struct socket *so1, struct socket *so2)
776 {
777 	int	error;
778 
779 	KASSERT(solocked2(so1, so2));
780 
781 	error = (*so1->so_proto->pr_usrreq)(so1, PRU_CONNECT2,
782 	    NULL, (struct mbuf *)so2, NULL, NULL);
783 	return (error);
784 }
785 
786 int
787 sodisconnect(struct socket *so)
788 {
789 	int	error;
790 
791 	KASSERT(solocked(so));
792 
793 	if ((so->so_state & SS_ISCONNECTED) == 0) {
794 		error = ENOTCONN;
795 	} else if (so->so_state & SS_ISDISCONNECTING) {
796 		error = EALREADY;
797 	} else {
798 		error = (*so->so_proto->pr_usrreq)(so, PRU_DISCONNECT,
799 		    NULL, NULL, NULL, NULL);
800 	}
801 	sodopendfree();
802 	return (error);
803 }
804 
805 #define	SBLOCKWAIT(f)	(((f) & MSG_DONTWAIT) ? M_NOWAIT : M_WAITOK)
806 /*
807  * Send on a socket.
808  * If send must go all at once and message is larger than
809  * send buffering, then hard error.
810  * Lock against other senders.
811  * If must go all at once and not enough room now, then
812  * inform user that this would block and do nothing.
813  * Otherwise, if nonblocking, send as much as possible.
814  * The data to be sent is described by "uio" if nonzero,
815  * otherwise by the mbuf chain "top" (which must be null
816  * if uio is not).  Data provided in mbuf chain must be small
817  * enough to send all at once.
818  *
819  * Returns nonzero on error, timeout or signal; callers
820  * must check for short counts if EINTR/ERESTART are returned.
821  * Data and control buffers are freed on return.
822  */
823 int
824 sosend(struct socket *so, struct mbuf *addr, struct uio *uio, struct mbuf *top,
825 	struct mbuf *control, int flags, struct lwp *l)
826 {
827 	struct mbuf	**mp, *m;
828 	struct proc	*p;
829 	long		space, len, resid, clen, mlen;
830 	int		error, s, dontroute, atomic;
831 
832 	p = l->l_proc;
833 	sodopendfree();
834 	clen = 0;
835 
836 	/*
837 	 * solock() provides atomicity of access.  splsoftnet() prevents
838 	 * protocol processing soft interrupts from interrupting us and
839 	 * blocking (expensive).
840 	 */
841 	s = splsoftnet();
842 	solock(so);
843 	atomic = sosendallatonce(so) || top;
844 	if (uio)
845 		resid = uio->uio_resid;
846 	else
847 		resid = top->m_pkthdr.len;
848 	/*
849 	 * In theory resid should be unsigned.
850 	 * However, space must be signed, as it might be less than 0
851 	 * if we over-committed, and we must use a signed comparison
852 	 * of space and resid.  On the other hand, a negative resid
853 	 * causes us to loop sending 0-length segments to the protocol.
854 	 */
855 	if (resid < 0) {
856 		error = EINVAL;
857 		goto out;
858 	}
859 	dontroute =
860 	    (flags & MSG_DONTROUTE) && (so->so_options & SO_DONTROUTE) == 0 &&
861 	    (so->so_proto->pr_flags & PR_ATOMIC);
862 	l->l_ru.ru_msgsnd++;
863 	if (control)
864 		clen = control->m_len;
865  restart:
866 	if ((error = sblock(&so->so_snd, SBLOCKWAIT(flags))) != 0)
867 		goto out;
868 	do {
869 		if (so->so_state & SS_CANTSENDMORE) {
870 			error = EPIPE;
871 			goto release;
872 		}
873 		if (so->so_error) {
874 			error = so->so_error;
875 			so->so_error = 0;
876 			goto release;
877 		}
878 		if ((so->so_state & SS_ISCONNECTED) == 0) {
879 			if (so->so_proto->pr_flags & PR_CONNREQUIRED) {
880 				if ((so->so_state & SS_ISCONFIRMING) == 0 &&
881 				    !(resid == 0 && clen != 0)) {
882 					error = ENOTCONN;
883 					goto release;
884 				}
885 			} else if (addr == 0) {
886 				error = EDESTADDRREQ;
887 				goto release;
888 			}
889 		}
890 		space = sbspace(&so->so_snd);
891 		if (flags & MSG_OOB)
892 			space += 1024;
893 		if ((atomic && resid > so->so_snd.sb_hiwat) ||
894 		    clen > so->so_snd.sb_hiwat) {
895 			error = EMSGSIZE;
896 			goto release;
897 		}
898 		if (space < resid + clen &&
899 		    (atomic || space < so->so_snd.sb_lowat || space < clen)) {
900 			if (so->so_nbio) {
901 				error = EWOULDBLOCK;
902 				goto release;
903 			}
904 			sbunlock(&so->so_snd);
905 			error = sbwait(&so->so_snd);
906 			if (error)
907 				goto out;
908 			goto restart;
909 		}
910 		mp = &top;
911 		space -= clen;
912 		do {
913 			if (uio == NULL) {
914 				/*
915 				 * Data is prepackaged in "top".
916 				 */
917 				resid = 0;
918 				if (flags & MSG_EOR)
919 					top->m_flags |= M_EOR;
920 			} else do {
921 				sounlock(so);
922 				splx(s);
923 				if (top == NULL) {
924 					m = m_gethdr(M_WAIT, MT_DATA);
925 					mlen = MHLEN;
926 					m->m_pkthdr.len = 0;
927 					m->m_pkthdr.rcvif = NULL;
928 				} else {
929 					m = m_get(M_WAIT, MT_DATA);
930 					mlen = MLEN;
931 				}
932 				MCLAIM(m, so->so_snd.sb_mowner);
933 				if (sock_loan_thresh >= 0 &&
934 				    uio->uio_iov->iov_len >= sock_loan_thresh &&
935 				    space >= sock_loan_thresh &&
936 				    (len = sosend_loan(so, uio, m,
937 						       space)) != 0) {
938 					SOSEND_COUNTER_INCR(&sosend_loan_big);
939 					space -= len;
940 					goto have_data;
941 				}
942 				if (resid >= MINCLSIZE && space >= MCLBYTES) {
943 					SOSEND_COUNTER_INCR(&sosend_copy_big);
944 					m_clget(m, M_WAIT);
945 					if ((m->m_flags & M_EXT) == 0)
946 						goto nopages;
947 					mlen = MCLBYTES;
948 					if (atomic && top == 0) {
949 						len = lmin(MCLBYTES - max_hdr,
950 						    resid);
951 						m->m_data += max_hdr;
952 					} else
953 						len = lmin(MCLBYTES, resid);
954 					space -= len;
955 				} else {
956  nopages:
957 					SOSEND_COUNTER_INCR(&sosend_copy_small);
958 					len = lmin(lmin(mlen, resid), space);
959 					space -= len;
960 					/*
961 					 * For datagram protocols, leave room
962 					 * for protocol headers in first mbuf.
963 					 */
964 					if (atomic && top == 0 && len < mlen)
965 						MH_ALIGN(m, len);
966 				}
967 				error = uiomove(mtod(m, void *), (int)len, uio);
968  have_data:
969 				resid = uio->uio_resid;
970 				m->m_len = len;
971 				*mp = m;
972 				top->m_pkthdr.len += len;
973 				s = splsoftnet();
974 				solock(so);
975 				if (error != 0)
976 					goto release;
977 				mp = &m->m_next;
978 				if (resid <= 0) {
979 					if (flags & MSG_EOR)
980 						top->m_flags |= M_EOR;
981 					break;
982 				}
983 			} while (space > 0 && atomic);
984 
985 			if (so->so_state & SS_CANTSENDMORE) {
986 				error = EPIPE;
987 				goto release;
988 			}
989 			if (dontroute)
990 				so->so_options |= SO_DONTROUTE;
991 			if (resid > 0)
992 				so->so_state |= SS_MORETOCOME;
993 			error = (*so->so_proto->pr_usrreq)(so,
994 			    (flags & MSG_OOB) ? PRU_SENDOOB : PRU_SEND,
995 			    top, addr, control, curlwp);
996 			if (dontroute)
997 				so->so_options &= ~SO_DONTROUTE;
998 			if (resid > 0)
999 				so->so_state &= ~SS_MORETOCOME;
1000 			clen = 0;
1001 			control = NULL;
1002 			top = NULL;
1003 			mp = &top;
1004 			if (error != 0)
1005 				goto release;
1006 		} while (resid && space > 0);
1007 	} while (resid);
1008 
1009  release:
1010 	sbunlock(&so->so_snd);
1011  out:
1012 	sounlock(so);
1013 	splx(s);
1014 	if (top)
1015 		m_freem(top);
1016 	if (control)
1017 		m_freem(control);
1018 	return (error);
1019 }
1020 
1021 /*
1022  * Following replacement or removal of the first mbuf on the first
1023  * mbuf chain of a socket buffer, push necessary state changes back
1024  * into the socket buffer so that other consumers see the values
1025  * consistently.  'nextrecord' is the callers locally stored value of
1026  * the original value of sb->sb_mb->m_nextpkt which must be restored
1027  * when the lead mbuf changes.  NOTE: 'nextrecord' may be NULL.
1028  */
1029 static void
1030 sbsync(struct sockbuf *sb, struct mbuf *nextrecord)
1031 {
1032 
1033 	KASSERT(solocked(sb->sb_so));
1034 
1035 	/*
1036 	 * First, update for the new value of nextrecord.  If necessary,
1037 	 * make it the first record.
1038 	 */
1039 	if (sb->sb_mb != NULL)
1040 		sb->sb_mb->m_nextpkt = nextrecord;
1041 	else
1042 		sb->sb_mb = nextrecord;
1043 
1044         /*
1045          * Now update any dependent socket buffer fields to reflect
1046          * the new state.  This is an inline of SB_EMPTY_FIXUP, with
1047          * the addition of a second clause that takes care of the
1048          * case where sb_mb has been updated, but remains the last
1049          * record.
1050          */
1051         if (sb->sb_mb == NULL) {
1052                 sb->sb_mbtail = NULL;
1053                 sb->sb_lastrecord = NULL;
1054         } else if (sb->sb_mb->m_nextpkt == NULL)
1055                 sb->sb_lastrecord = sb->sb_mb;
1056 }
1057 
1058 /*
1059  * Implement receive operations on a socket.
1060  * We depend on the way that records are added to the sockbuf
1061  * by sbappend*.  In particular, each record (mbufs linked through m_next)
1062  * must begin with an address if the protocol so specifies,
1063  * followed by an optional mbuf or mbufs containing ancillary data,
1064  * and then zero or more mbufs of data.
1065  * In order to avoid blocking network interrupts for the entire time here,
1066  * we splx() while doing the actual copy to user space.
1067  * Although the sockbuf is locked, new data may still be appended,
1068  * and thus we must maintain consistency of the sockbuf during that time.
1069  *
1070  * The caller may receive the data as a single mbuf chain by supplying
1071  * an mbuf **mp0 for use in returning the chain.  The uio is then used
1072  * only for the count in uio_resid.
1073  */
1074 int
1075 soreceive(struct socket *so, struct mbuf **paddr, struct uio *uio,
1076 	struct mbuf **mp0, struct mbuf **controlp, int *flagsp)
1077 {
1078 	struct lwp *l = curlwp;
1079 	struct mbuf	*m, **mp, *mt;
1080 	int atomic, flags, len, error, s, offset, moff, type, orig_resid;
1081 	const struct protosw	*pr;
1082 	struct mbuf	*nextrecord;
1083 	int		mbuf_removed = 0;
1084 	const struct domain *dom;
1085 
1086 	pr = so->so_proto;
1087 	atomic = pr->pr_flags & PR_ATOMIC;
1088 	dom = pr->pr_domain;
1089 	mp = mp0;
1090 	type = 0;
1091 	orig_resid = uio->uio_resid;
1092 
1093 	if (paddr != NULL)
1094 		*paddr = NULL;
1095 	if (controlp != NULL)
1096 		*controlp = NULL;
1097 	if (flagsp != NULL)
1098 		flags = *flagsp &~ MSG_EOR;
1099 	else
1100 		flags = 0;
1101 
1102 	if ((flags & MSG_DONTWAIT) == 0)
1103 		sodopendfree();
1104 
1105 	if (flags & MSG_OOB) {
1106 		m = m_get(M_WAIT, MT_DATA);
1107 		solock(so);
1108 		error = (*pr->pr_usrreq)(so, PRU_RCVOOB, m,
1109 		    (struct mbuf *)(long)(flags & MSG_PEEK), NULL, l);
1110 		sounlock(so);
1111 		if (error)
1112 			goto bad;
1113 		do {
1114 			error = uiomove(mtod(m, void *),
1115 			    (int) min(uio->uio_resid, m->m_len), uio);
1116 			m = m_free(m);
1117 		} while (uio->uio_resid > 0 && error == 0 && m);
1118  bad:
1119 		if (m != NULL)
1120 			m_freem(m);
1121 		return error;
1122 	}
1123 	if (mp != NULL)
1124 		*mp = NULL;
1125 
1126 	/*
1127 	 * solock() provides atomicity of access.  splsoftnet() prevents
1128 	 * protocol processing soft interrupts from interrupting us and
1129 	 * blocking (expensive).
1130 	 */
1131 	s = splsoftnet();
1132 	solock(so);
1133 	if (so->so_state & SS_ISCONFIRMING && uio->uio_resid)
1134 		(*pr->pr_usrreq)(so, PRU_RCVD, NULL, NULL, NULL, l);
1135 
1136  restart:
1137 	if ((error = sblock(&so->so_rcv, SBLOCKWAIT(flags))) != 0) {
1138 		sounlock(so);
1139 		splx(s);
1140 		return error;
1141 	}
1142 
1143 	m = so->so_rcv.sb_mb;
1144 	/*
1145 	 * If we have less data than requested, block awaiting more
1146 	 * (subject to any timeout) if:
1147 	 *   1. the current count is less than the low water mark,
1148 	 *   2. MSG_WAITALL is set, and it is possible to do the entire
1149 	 *	receive operation at once if we block (resid <= hiwat), or
1150 	 *   3. MSG_DONTWAIT is not set.
1151 	 * If MSG_WAITALL is set but resid is larger than the receive buffer,
1152 	 * we have to do the receive in sections, and thus risk returning
1153 	 * a short count if a timeout or signal occurs after we start.
1154 	 */
1155 	if (m == NULL ||
1156 	    ((flags & MSG_DONTWAIT) == 0 &&
1157 	     so->so_rcv.sb_cc < uio->uio_resid &&
1158 	     (so->so_rcv.sb_cc < so->so_rcv.sb_lowat ||
1159 	      ((flags & MSG_WAITALL) &&
1160 	       uio->uio_resid <= so->so_rcv.sb_hiwat)) &&
1161 	     m->m_nextpkt == NULL && !atomic)) {
1162 #ifdef DIAGNOSTIC
1163 		if (m == NULL && so->so_rcv.sb_cc)
1164 			panic("receive 1");
1165 #endif
1166 		if (so->so_error) {
1167 			if (m != NULL)
1168 				goto dontblock;
1169 			error = so->so_error;
1170 			if ((flags & MSG_PEEK) == 0)
1171 				so->so_error = 0;
1172 			goto release;
1173 		}
1174 		if (so->so_state & SS_CANTRCVMORE) {
1175 			if (m != NULL)
1176 				goto dontblock;
1177 			else
1178 				goto release;
1179 		}
1180 		for (; m != NULL; m = m->m_next)
1181 			if (m->m_type == MT_OOBDATA  || (m->m_flags & M_EOR)) {
1182 				m = so->so_rcv.sb_mb;
1183 				goto dontblock;
1184 			}
1185 		if ((so->so_state & (SS_ISCONNECTED|SS_ISCONNECTING)) == 0 &&
1186 		    (so->so_proto->pr_flags & PR_CONNREQUIRED)) {
1187 			error = ENOTCONN;
1188 			goto release;
1189 		}
1190 		if (uio->uio_resid == 0)
1191 			goto release;
1192 		if (so->so_nbio || (flags & MSG_DONTWAIT)) {
1193 			error = EWOULDBLOCK;
1194 			goto release;
1195 		}
1196 		SBLASTRECORDCHK(&so->so_rcv, "soreceive sbwait 1");
1197 		SBLASTMBUFCHK(&so->so_rcv, "soreceive sbwait 1");
1198 		sbunlock(&so->so_rcv);
1199 		error = sbwait(&so->so_rcv);
1200 		if (error != 0) {
1201 			sounlock(so);
1202 			splx(s);
1203 			return error;
1204 		}
1205 		goto restart;
1206 	}
1207  dontblock:
1208 	/*
1209 	 * On entry here, m points to the first record of the socket buffer.
1210 	 * From this point onward, we maintain 'nextrecord' as a cache of the
1211 	 * pointer to the next record in the socket buffer.  We must keep the
1212 	 * various socket buffer pointers and local stack versions of the
1213 	 * pointers in sync, pushing out modifications before dropping the
1214 	 * socket lock, and re-reading them when picking it up.
1215 	 *
1216 	 * Otherwise, we will race with the network stack appending new data
1217 	 * or records onto the socket buffer by using inconsistent/stale
1218 	 * versions of the field, possibly resulting in socket buffer
1219 	 * corruption.
1220 	 *
1221 	 * By holding the high-level sblock(), we prevent simultaneous
1222 	 * readers from pulling off the front of the socket buffer.
1223 	 */
1224 	if (l != NULL)
1225 		l->l_ru.ru_msgrcv++;
1226 	KASSERT(m == so->so_rcv.sb_mb);
1227 	SBLASTRECORDCHK(&so->so_rcv, "soreceive 1");
1228 	SBLASTMBUFCHK(&so->so_rcv, "soreceive 1");
1229 	nextrecord = m->m_nextpkt;
1230 	if (pr->pr_flags & PR_ADDR) {
1231 #ifdef DIAGNOSTIC
1232 		if (m->m_type != MT_SONAME)
1233 			panic("receive 1a");
1234 #endif
1235 		orig_resid = 0;
1236 		if (flags & MSG_PEEK) {
1237 			if (paddr)
1238 				*paddr = m_copy(m, 0, m->m_len);
1239 			m = m->m_next;
1240 		} else {
1241 			sbfree(&so->so_rcv, m);
1242 			mbuf_removed = 1;
1243 			if (paddr != NULL) {
1244 				*paddr = m;
1245 				so->so_rcv.sb_mb = m->m_next;
1246 				m->m_next = NULL;
1247 				m = so->so_rcv.sb_mb;
1248 			} else {
1249 				MFREE(m, so->so_rcv.sb_mb);
1250 				m = so->so_rcv.sb_mb;
1251 			}
1252 			sbsync(&so->so_rcv, nextrecord);
1253 		}
1254 	}
1255 
1256 	/*
1257 	 * Process one or more MT_CONTROL mbufs present before any data mbufs
1258 	 * in the first mbuf chain on the socket buffer.  If MSG_PEEK, we
1259 	 * just copy the data; if !MSG_PEEK, we call into the protocol to
1260 	 * perform externalization (or freeing if controlp == NULL).
1261 	 */
1262 	if (__predict_false(m != NULL && m->m_type == MT_CONTROL)) {
1263 		struct mbuf *cm = NULL, *cmn;
1264 		struct mbuf **cme = &cm;
1265 
1266 		do {
1267 			if (flags & MSG_PEEK) {
1268 				if (controlp != NULL) {
1269 					*controlp = m_copy(m, 0, m->m_len);
1270 					controlp = &(*controlp)->m_next;
1271 				}
1272 				m = m->m_next;
1273 			} else {
1274 				sbfree(&so->so_rcv, m);
1275 				so->so_rcv.sb_mb = m->m_next;
1276 				m->m_next = NULL;
1277 				*cme = m;
1278 				cme = &(*cme)->m_next;
1279 				m = so->so_rcv.sb_mb;
1280 			}
1281 		} while (m != NULL && m->m_type == MT_CONTROL);
1282 		if ((flags & MSG_PEEK) == 0)
1283 			sbsync(&so->so_rcv, nextrecord);
1284 		for (; cm != NULL; cm = cmn) {
1285 			cmn = cm->m_next;
1286 			cm->m_next = NULL;
1287 			type = mtod(cm, struct cmsghdr *)->cmsg_type;
1288 			if (controlp != NULL) {
1289 				if (dom->dom_externalize != NULL &&
1290 				    type == SCM_RIGHTS) {
1291 					sounlock(so);
1292 					splx(s);
1293 					error = (*dom->dom_externalize)(cm, l);
1294 					s = splsoftnet();
1295 					solock(so);
1296 				}
1297 				*controlp = cm;
1298 				while (*controlp != NULL)
1299 					controlp = &(*controlp)->m_next;
1300 			} else {
1301 				/*
1302 				 * Dispose of any SCM_RIGHTS message that went
1303 				 * through the read path rather than recv.
1304 				 */
1305 				if (dom->dom_dispose != NULL &&
1306 				    type == SCM_RIGHTS) {
1307 				    	sounlock(so);
1308 					(*dom->dom_dispose)(cm);
1309 					solock(so);
1310 				}
1311 				m_freem(cm);
1312 			}
1313 		}
1314 		if (m != NULL)
1315 			nextrecord = so->so_rcv.sb_mb->m_nextpkt;
1316 		else
1317 			nextrecord = so->so_rcv.sb_mb;
1318 		orig_resid = 0;
1319 	}
1320 
1321 	/* If m is non-NULL, we have some data to read. */
1322 	if (__predict_true(m != NULL)) {
1323 		type = m->m_type;
1324 		if (type == MT_OOBDATA)
1325 			flags |= MSG_OOB;
1326 	}
1327 	SBLASTRECORDCHK(&so->so_rcv, "soreceive 2");
1328 	SBLASTMBUFCHK(&so->so_rcv, "soreceive 2");
1329 
1330 	moff = 0;
1331 	offset = 0;
1332 	while (m != NULL && uio->uio_resid > 0 && error == 0) {
1333 		if (m->m_type == MT_OOBDATA) {
1334 			if (type != MT_OOBDATA)
1335 				break;
1336 		} else if (type == MT_OOBDATA)
1337 			break;
1338 #ifdef DIAGNOSTIC
1339 		else if (m->m_type != MT_DATA && m->m_type != MT_HEADER)
1340 			panic("receive 3");
1341 #endif
1342 		so->so_state &= ~SS_RCVATMARK;
1343 		len = uio->uio_resid;
1344 		if (so->so_oobmark && len > so->so_oobmark - offset)
1345 			len = so->so_oobmark - offset;
1346 		if (len > m->m_len - moff)
1347 			len = m->m_len - moff;
1348 		/*
1349 		 * If mp is set, just pass back the mbufs.
1350 		 * Otherwise copy them out via the uio, then free.
1351 		 * Sockbuf must be consistent here (points to current mbuf,
1352 		 * it points to next record) when we drop priority;
1353 		 * we must note any additions to the sockbuf when we
1354 		 * block interrupts again.
1355 		 */
1356 		if (mp == NULL) {
1357 			SBLASTRECORDCHK(&so->so_rcv, "soreceive uiomove");
1358 			SBLASTMBUFCHK(&so->so_rcv, "soreceive uiomove");
1359 			sounlock(so);
1360 			splx(s);
1361 			error = uiomove(mtod(m, char *) + moff, (int)len, uio);
1362 			s = splsoftnet();
1363 			solock(so);
1364 			if (error != 0) {
1365 				/*
1366 				 * If any part of the record has been removed
1367 				 * (such as the MT_SONAME mbuf, which will
1368 				 * happen when PR_ADDR, and thus also
1369 				 * PR_ATOMIC, is set), then drop the entire
1370 				 * record to maintain the atomicity of the
1371 				 * receive operation.
1372 				 *
1373 				 * This avoids a later panic("receive 1a")
1374 				 * when compiled with DIAGNOSTIC.
1375 				 */
1376 				if (m && mbuf_removed && atomic)
1377 					(void) sbdroprecord(&so->so_rcv);
1378 
1379 				goto release;
1380 			}
1381 		} else
1382 			uio->uio_resid -= len;
1383 		if (len == m->m_len - moff) {
1384 			if (m->m_flags & M_EOR)
1385 				flags |= MSG_EOR;
1386 			if (flags & MSG_PEEK) {
1387 				m = m->m_next;
1388 				moff = 0;
1389 			} else {
1390 				nextrecord = m->m_nextpkt;
1391 				sbfree(&so->so_rcv, m);
1392 				if (mp) {
1393 					*mp = m;
1394 					mp = &m->m_next;
1395 					so->so_rcv.sb_mb = m = m->m_next;
1396 					*mp = NULL;
1397 				} else {
1398 					MFREE(m, so->so_rcv.sb_mb);
1399 					m = so->so_rcv.sb_mb;
1400 				}
1401 				/*
1402 				 * If m != NULL, we also know that
1403 				 * so->so_rcv.sb_mb != NULL.
1404 				 */
1405 				KASSERT(so->so_rcv.sb_mb == m);
1406 				if (m) {
1407 					m->m_nextpkt = nextrecord;
1408 					if (nextrecord == NULL)
1409 						so->so_rcv.sb_lastrecord = m;
1410 				} else {
1411 					so->so_rcv.sb_mb = nextrecord;
1412 					SB_EMPTY_FIXUP(&so->so_rcv);
1413 				}
1414 				SBLASTRECORDCHK(&so->so_rcv, "soreceive 3");
1415 				SBLASTMBUFCHK(&so->so_rcv, "soreceive 3");
1416 			}
1417 		} else if (flags & MSG_PEEK)
1418 			moff += len;
1419 		else {
1420 			if (mp != NULL) {
1421 				mt = m_copym(m, 0, len, M_NOWAIT);
1422 				if (__predict_false(mt == NULL)) {
1423 					sounlock(so);
1424 					mt = m_copym(m, 0, len, M_WAIT);
1425 					solock(so);
1426 				}
1427 				*mp = mt;
1428 			}
1429 			m->m_data += len;
1430 			m->m_len -= len;
1431 			so->so_rcv.sb_cc -= len;
1432 		}
1433 		if (so->so_oobmark) {
1434 			if ((flags & MSG_PEEK) == 0) {
1435 				so->so_oobmark -= len;
1436 				if (so->so_oobmark == 0) {
1437 					so->so_state |= SS_RCVATMARK;
1438 					break;
1439 				}
1440 			} else {
1441 				offset += len;
1442 				if (offset == so->so_oobmark)
1443 					break;
1444 			}
1445 		}
1446 		if (flags & MSG_EOR)
1447 			break;
1448 		/*
1449 		 * If the MSG_WAITALL flag is set (for non-atomic socket),
1450 		 * we must not quit until "uio->uio_resid == 0" or an error
1451 		 * termination.  If a signal/timeout occurs, return
1452 		 * with a short count but without error.
1453 		 * Keep sockbuf locked against other readers.
1454 		 */
1455 		while (flags & MSG_WAITALL && m == NULL && uio->uio_resid > 0 &&
1456 		    !sosendallatonce(so) && !nextrecord) {
1457 			if (so->so_error || so->so_state & SS_CANTRCVMORE)
1458 				break;
1459 			/*
1460 			 * If we are peeking and the socket receive buffer is
1461 			 * full, stop since we can't get more data to peek at.
1462 			 */
1463 			if ((flags & MSG_PEEK) && sbspace(&so->so_rcv) <= 0)
1464 				break;
1465 			/*
1466 			 * If we've drained the socket buffer, tell the
1467 			 * protocol in case it needs to do something to
1468 			 * get it filled again.
1469 			 */
1470 			if ((pr->pr_flags & PR_WANTRCVD) && so->so_pcb)
1471 				(*pr->pr_usrreq)(so, PRU_RCVD,
1472 				    NULL, (struct mbuf *)(long)flags, NULL, l);
1473 			SBLASTRECORDCHK(&so->so_rcv, "soreceive sbwait 2");
1474 			SBLASTMBUFCHK(&so->so_rcv, "soreceive sbwait 2");
1475 			error = sbwait(&so->so_rcv);
1476 			if (error != 0) {
1477 				sbunlock(&so->so_rcv);
1478 				sounlock(so);
1479 				splx(s);
1480 				return 0;
1481 			}
1482 			if ((m = so->so_rcv.sb_mb) != NULL)
1483 				nextrecord = m->m_nextpkt;
1484 		}
1485 	}
1486 
1487 	if (m && atomic) {
1488 		flags |= MSG_TRUNC;
1489 		if ((flags & MSG_PEEK) == 0)
1490 			(void) sbdroprecord(&so->so_rcv);
1491 	}
1492 	if ((flags & MSG_PEEK) == 0) {
1493 		if (m == NULL) {
1494 			/*
1495 			 * First part is an inline SB_EMPTY_FIXUP().  Second
1496 			 * part makes sure sb_lastrecord is up-to-date if
1497 			 * there is still data in the socket buffer.
1498 			 */
1499 			so->so_rcv.sb_mb = nextrecord;
1500 			if (so->so_rcv.sb_mb == NULL) {
1501 				so->so_rcv.sb_mbtail = NULL;
1502 				so->so_rcv.sb_lastrecord = NULL;
1503 			} else if (nextrecord->m_nextpkt == NULL)
1504 				so->so_rcv.sb_lastrecord = nextrecord;
1505 		}
1506 		SBLASTRECORDCHK(&so->so_rcv, "soreceive 4");
1507 		SBLASTMBUFCHK(&so->so_rcv, "soreceive 4");
1508 		if (pr->pr_flags & PR_WANTRCVD && so->so_pcb)
1509 			(*pr->pr_usrreq)(so, PRU_RCVD, NULL,
1510 			    (struct mbuf *)(long)flags, NULL, l);
1511 	}
1512 	if (orig_resid == uio->uio_resid && orig_resid &&
1513 	    (flags & MSG_EOR) == 0 && (so->so_state & SS_CANTRCVMORE) == 0) {
1514 		sbunlock(&so->so_rcv);
1515 		goto restart;
1516 	}
1517 
1518 	if (flagsp != NULL)
1519 		*flagsp |= flags;
1520  release:
1521 	sbunlock(&so->so_rcv);
1522 	sounlock(so);
1523 	splx(s);
1524 	return error;
1525 }
1526 
1527 int
1528 soshutdown(struct socket *so, int how)
1529 {
1530 	const struct protosw	*pr;
1531 	int	error;
1532 
1533 	KASSERT(solocked(so));
1534 
1535 	pr = so->so_proto;
1536 	if (!(how == SHUT_RD || how == SHUT_WR || how == SHUT_RDWR))
1537 		return (EINVAL);
1538 
1539 	if (how == SHUT_RD || how == SHUT_RDWR) {
1540 		sorflush(so);
1541 		error = 0;
1542 	}
1543 	if (how == SHUT_WR || how == SHUT_RDWR)
1544 		error = (*pr->pr_usrreq)(so, PRU_SHUTDOWN, NULL,
1545 		    NULL, NULL, NULL);
1546 
1547 	return error;
1548 }
1549 
1550 int
1551 sodrain(struct socket *so)
1552 {
1553 	int error;
1554 
1555 	solock(so);
1556 	so->so_state |= SS_ISDRAINING;
1557 	cv_broadcast(&so->so_cv);
1558 	error = soshutdown(so, SHUT_RDWR);
1559 	sounlock(so);
1560 
1561 	return error;
1562 }
1563 
1564 void
1565 sorflush(struct socket *so)
1566 {
1567 	struct sockbuf	*sb, asb;
1568 	const struct protosw	*pr;
1569 
1570 	KASSERT(solocked(so));
1571 
1572 	sb = &so->so_rcv;
1573 	pr = so->so_proto;
1574 	socantrcvmore(so);
1575 	sb->sb_flags |= SB_NOINTR;
1576 	(void )sblock(sb, M_WAITOK);
1577 	sbunlock(sb);
1578 	asb = *sb;
1579 	/*
1580 	 * Clear most of the sockbuf structure, but leave some of the
1581 	 * fields valid.
1582 	 */
1583 	memset(&sb->sb_startzero, 0,
1584 	    sizeof(*sb) - offsetof(struct sockbuf, sb_startzero));
1585 	if (pr->pr_flags & PR_RIGHTS && pr->pr_domain->dom_dispose) {
1586 		sounlock(so);
1587 		(*pr->pr_domain->dom_dispose)(asb.sb_mb);
1588 		solock(so);
1589 	}
1590 	sbrelease(&asb, so);
1591 }
1592 
1593 /*
1594  * internal set SOL_SOCKET options
1595  */
1596 static int
1597 sosetopt1(struct socket *so, const struct sockopt *sopt)
1598 {
1599 	int error = EINVAL, optval, opt;
1600 	struct linger l;
1601 	struct timeval tv;
1602 
1603 	switch ((opt = sopt->sopt_name)) {
1604 
1605 	case SO_ACCEPTFILTER:
1606 		error = accept_filt_setopt(so, sopt);
1607 		KASSERT(solocked(so));
1608 		break;
1609 
1610   	case SO_LINGER:
1611  		error = sockopt_get(sopt, &l, sizeof(l));
1612 		solock(so);
1613  		if (error)
1614  			break;
1615  		if (l.l_linger < 0 || l.l_linger > USHRT_MAX ||
1616  		    l.l_linger > (INT_MAX / hz)) {
1617 			error = EDOM;
1618 			break;
1619 		}
1620  		so->so_linger = l.l_linger;
1621  		if (l.l_onoff)
1622  			so->so_options |= SO_LINGER;
1623  		else
1624  			so->so_options &= ~SO_LINGER;
1625    		break;
1626 
1627 	case SO_DEBUG:
1628 	case SO_KEEPALIVE:
1629 	case SO_DONTROUTE:
1630 	case SO_USELOOPBACK:
1631 	case SO_BROADCAST:
1632 	case SO_REUSEADDR:
1633 	case SO_REUSEPORT:
1634 	case SO_OOBINLINE:
1635 	case SO_TIMESTAMP:
1636 #ifdef SO_OTIMESTAMP
1637 	case SO_OTIMESTAMP:
1638 #endif
1639 		error = sockopt_getint(sopt, &optval);
1640 		solock(so);
1641 		if (error)
1642 			break;
1643 		if (optval)
1644 			so->so_options |= opt;
1645 		else
1646 			so->so_options &= ~opt;
1647 		break;
1648 
1649 	case SO_SNDBUF:
1650 	case SO_RCVBUF:
1651 	case SO_SNDLOWAT:
1652 	case SO_RCVLOWAT:
1653 		error = sockopt_getint(sopt, &optval);
1654 		solock(so);
1655 		if (error)
1656 			break;
1657 
1658 		/*
1659 		 * Values < 1 make no sense for any of these
1660 		 * options, so disallow them.
1661 		 */
1662 		if (optval < 1) {
1663 			error = EINVAL;
1664 			break;
1665 		}
1666 
1667 		switch (opt) {
1668 		case SO_SNDBUF:
1669 			if (sbreserve(&so->so_snd, (u_long)optval, so) == 0) {
1670 				error = ENOBUFS;
1671 				break;
1672 			}
1673 			so->so_snd.sb_flags &= ~SB_AUTOSIZE;
1674 			break;
1675 
1676 		case SO_RCVBUF:
1677 			if (sbreserve(&so->so_rcv, (u_long)optval, so) == 0) {
1678 				error = ENOBUFS;
1679 				break;
1680 			}
1681 			so->so_rcv.sb_flags &= ~SB_AUTOSIZE;
1682 			break;
1683 
1684 		/*
1685 		 * Make sure the low-water is never greater than
1686 		 * the high-water.
1687 		 */
1688 		case SO_SNDLOWAT:
1689 			if (optval > so->so_snd.sb_hiwat)
1690 				optval = so->so_snd.sb_hiwat;
1691 
1692 			so->so_snd.sb_lowat = optval;
1693 			break;
1694 
1695 		case SO_RCVLOWAT:
1696 			if (optval > so->so_rcv.sb_hiwat)
1697 				optval = so->so_rcv.sb_hiwat;
1698 
1699 			so->so_rcv.sb_lowat = optval;
1700 			break;
1701 		}
1702 		break;
1703 
1704 #ifdef COMPAT_50
1705 	case SO_OSNDTIMEO:
1706 	case SO_ORCVTIMEO: {
1707 		struct timeval50 otv;
1708 		error = sockopt_get(sopt, &otv, sizeof(otv));
1709 		if (error) {
1710 			solock(so);
1711 			break;
1712 		}
1713 		timeval50_to_timeval(&otv, &tv);
1714 		opt = opt == SO_OSNDTIMEO ? SO_SNDTIMEO : SO_RCVTIMEO;
1715 		error = 0;
1716 		/*FALLTHROUGH*/
1717 	}
1718 #endif /* COMPAT_50 */
1719 
1720 	case SO_SNDTIMEO:
1721 	case SO_RCVTIMEO:
1722 		if (error)
1723 			error = sockopt_get(sopt, &tv, sizeof(tv));
1724 		solock(so);
1725 		if (error)
1726 			break;
1727 
1728 		if (tv.tv_sec > (INT_MAX - tv.tv_usec / tick) / hz) {
1729 			error = EDOM;
1730 			break;
1731 		}
1732 
1733 		optval = tv.tv_sec * hz + tv.tv_usec / tick;
1734 		if (optval == 0 && tv.tv_usec != 0)
1735 			optval = 1;
1736 
1737 		switch (opt) {
1738 		case SO_SNDTIMEO:
1739 			so->so_snd.sb_timeo = optval;
1740 			break;
1741 		case SO_RCVTIMEO:
1742 			so->so_rcv.sb_timeo = optval;
1743 			break;
1744 		}
1745 		break;
1746 
1747 	default:
1748 		solock(so);
1749 		error = ENOPROTOOPT;
1750 		break;
1751 	}
1752 	KASSERT(solocked(so));
1753 	return error;
1754 }
1755 
1756 int
1757 sosetopt(struct socket *so, struct sockopt *sopt)
1758 {
1759 	int error, prerr;
1760 
1761 	if (sopt->sopt_level == SOL_SOCKET) {
1762 		error = sosetopt1(so, sopt);
1763 		KASSERT(solocked(so));
1764 	} else {
1765 		error = ENOPROTOOPT;
1766 		solock(so);
1767 	}
1768 
1769 	if ((error == 0 || error == ENOPROTOOPT) &&
1770 	    so->so_proto != NULL && so->so_proto->pr_ctloutput != NULL) {
1771 		/* give the protocol stack a shot */
1772 		prerr = (*so->so_proto->pr_ctloutput)(PRCO_SETOPT, so, sopt);
1773 		if (prerr == 0)
1774 			error = 0;
1775 		else if (prerr != ENOPROTOOPT)
1776 			error = prerr;
1777 	}
1778 	sounlock(so);
1779 	return error;
1780 }
1781 
1782 /*
1783  * so_setsockopt() is a wrapper providing a sockopt structure for sosetopt()
1784  */
1785 int
1786 so_setsockopt(struct lwp *l, struct socket *so, int level, int name,
1787     const void *val, size_t valsize)
1788 {
1789 	struct sockopt sopt;
1790 	int error;
1791 
1792 	KASSERT(valsize == 0 || val != NULL);
1793 
1794 	sockopt_init(&sopt, level, name, valsize);
1795 	sockopt_set(&sopt, val, valsize);
1796 
1797 	error = sosetopt(so, &sopt);
1798 
1799 	sockopt_destroy(&sopt);
1800 
1801 	return error;
1802 }
1803 
1804 /*
1805  * internal get SOL_SOCKET options
1806  */
1807 static int
1808 sogetopt1(struct socket *so, struct sockopt *sopt)
1809 {
1810 	int error, optval, opt;
1811 	struct linger l;
1812 	struct timeval tv;
1813 
1814 	switch ((opt = sopt->sopt_name)) {
1815 
1816 	case SO_ACCEPTFILTER:
1817 		error = accept_filt_getopt(so, sopt);
1818 		break;
1819 
1820 	case SO_LINGER:
1821 		l.l_onoff = (so->so_options & SO_LINGER) ? 1 : 0;
1822 		l.l_linger = so->so_linger;
1823 
1824 		error = sockopt_set(sopt, &l, sizeof(l));
1825 		break;
1826 
1827 	case SO_USELOOPBACK:
1828 	case SO_DONTROUTE:
1829 	case SO_DEBUG:
1830 	case SO_KEEPALIVE:
1831 	case SO_REUSEADDR:
1832 	case SO_REUSEPORT:
1833 	case SO_BROADCAST:
1834 	case SO_OOBINLINE:
1835 	case SO_TIMESTAMP:
1836 #ifdef SO_OTIMESTAMP
1837 	case SO_OTIMESTAMP:
1838 #endif
1839 		error = sockopt_setint(sopt, (so->so_options & opt) ? 1 : 0);
1840 		break;
1841 
1842 	case SO_TYPE:
1843 		error = sockopt_setint(sopt, so->so_type);
1844 		break;
1845 
1846 	case SO_ERROR:
1847 		error = sockopt_setint(sopt, so->so_error);
1848 		so->so_error = 0;
1849 		break;
1850 
1851 	case SO_SNDBUF:
1852 		error = sockopt_setint(sopt, so->so_snd.sb_hiwat);
1853 		break;
1854 
1855 	case SO_RCVBUF:
1856 		error = sockopt_setint(sopt, so->so_rcv.sb_hiwat);
1857 		break;
1858 
1859 	case SO_SNDLOWAT:
1860 		error = sockopt_setint(sopt, so->so_snd.sb_lowat);
1861 		break;
1862 
1863 	case SO_RCVLOWAT:
1864 		error = sockopt_setint(sopt, so->so_rcv.sb_lowat);
1865 		break;
1866 
1867 #ifdef COMPAT_50
1868 	case SO_OSNDTIMEO:
1869 	case SO_ORCVTIMEO: {
1870 		struct timeval50 otv;
1871 
1872 		optval = (opt == SO_OSNDTIMEO ?
1873 		     so->so_snd.sb_timeo : so->so_rcv.sb_timeo);
1874 
1875 		otv.tv_sec = optval / hz;
1876 		otv.tv_usec = (optval % hz) * tick;
1877 
1878 		error = sockopt_set(sopt, &otv, sizeof(otv));
1879 		break;
1880 	}
1881 #endif /* COMPAT_50 */
1882 
1883 	case SO_SNDTIMEO:
1884 	case SO_RCVTIMEO:
1885 		optval = (opt == SO_SNDTIMEO ?
1886 		     so->so_snd.sb_timeo : so->so_rcv.sb_timeo);
1887 
1888 		tv.tv_sec = optval / hz;
1889 		tv.tv_usec = (optval % hz) * tick;
1890 
1891 		error = sockopt_set(sopt, &tv, sizeof(tv));
1892 		break;
1893 
1894 	case SO_OVERFLOWED:
1895 		error = sockopt_setint(sopt, so->so_rcv.sb_overflowed);
1896 		break;
1897 
1898 	default:
1899 		error = ENOPROTOOPT;
1900 		break;
1901 	}
1902 
1903 	return (error);
1904 }
1905 
1906 int
1907 sogetopt(struct socket *so, struct sockopt *sopt)
1908 {
1909 	int		error;
1910 
1911 	solock(so);
1912 	if (sopt->sopt_level != SOL_SOCKET) {
1913 		if (so->so_proto && so->so_proto->pr_ctloutput) {
1914 			error = ((*so->so_proto->pr_ctloutput)
1915 			    (PRCO_GETOPT, so, sopt));
1916 		} else
1917 			error = (ENOPROTOOPT);
1918 	} else {
1919 		error = sogetopt1(so, sopt);
1920 	}
1921 	sounlock(so);
1922 	return (error);
1923 }
1924 
1925 /*
1926  * alloc sockopt data buffer buffer
1927  *	- will be released at destroy
1928  */
1929 static int
1930 sockopt_alloc(struct sockopt *sopt, size_t len, km_flag_t kmflag)
1931 {
1932 
1933 	KASSERT(sopt->sopt_size == 0);
1934 
1935 	if (len > sizeof(sopt->sopt_buf)) {
1936 		sopt->sopt_data = kmem_zalloc(len, kmflag);
1937 		if (sopt->sopt_data == NULL)
1938 			return ENOMEM;
1939 	} else
1940 		sopt->sopt_data = sopt->sopt_buf;
1941 
1942 	sopt->sopt_size = len;
1943 	return 0;
1944 }
1945 
1946 /*
1947  * initialise sockopt storage
1948  *	- MAY sleep during allocation
1949  */
1950 void
1951 sockopt_init(struct sockopt *sopt, int level, int name, size_t size)
1952 {
1953 
1954 	memset(sopt, 0, sizeof(*sopt));
1955 
1956 	sopt->sopt_level = level;
1957 	sopt->sopt_name = name;
1958 	(void)sockopt_alloc(sopt, size, KM_SLEEP);
1959 }
1960 
1961 /*
1962  * destroy sockopt storage
1963  *	- will release any held memory references
1964  */
1965 void
1966 sockopt_destroy(struct sockopt *sopt)
1967 {
1968 
1969 	if (sopt->sopt_data != sopt->sopt_buf)
1970 		kmem_free(sopt->sopt_data, sopt->sopt_size);
1971 
1972 	memset(sopt, 0, sizeof(*sopt));
1973 }
1974 
1975 /*
1976  * set sockopt value
1977  *	- value is copied into sockopt
1978  * 	- memory is allocated when necessary, will not sleep
1979  */
1980 int
1981 sockopt_set(struct sockopt *sopt, const void *buf, size_t len)
1982 {
1983 	int error;
1984 
1985 	if (sopt->sopt_size == 0) {
1986 		error = sockopt_alloc(sopt, len, KM_NOSLEEP);
1987 		if (error)
1988 			return error;
1989 	}
1990 
1991 	KASSERT(sopt->sopt_size == len);
1992 	memcpy(sopt->sopt_data, buf, len);
1993 	return 0;
1994 }
1995 
1996 /*
1997  * common case of set sockopt integer value
1998  */
1999 int
2000 sockopt_setint(struct sockopt *sopt, int val)
2001 {
2002 
2003 	return sockopt_set(sopt, &val, sizeof(int));
2004 }
2005 
2006 /*
2007  * get sockopt value
2008  *	- correct size must be given
2009  */
2010 int
2011 sockopt_get(const struct sockopt *sopt, void *buf, size_t len)
2012 {
2013 
2014 	if (sopt->sopt_size != len)
2015 		return EINVAL;
2016 
2017 	memcpy(buf, sopt->sopt_data, len);
2018 	return 0;
2019 }
2020 
2021 /*
2022  * common case of get sockopt integer value
2023  */
2024 int
2025 sockopt_getint(const struct sockopt *sopt, int *valp)
2026 {
2027 
2028 	return sockopt_get(sopt, valp, sizeof(int));
2029 }
2030 
2031 /*
2032  * set sockopt value from mbuf
2033  *	- ONLY for legacy code
2034  *	- mbuf is released by sockopt
2035  *	- will not sleep
2036  */
2037 int
2038 sockopt_setmbuf(struct sockopt *sopt, struct mbuf *m)
2039 {
2040 	size_t len;
2041 	int error;
2042 
2043 	len = m_length(m);
2044 
2045 	if (sopt->sopt_size == 0) {
2046 		error = sockopt_alloc(sopt, len, KM_NOSLEEP);
2047 		if (error)
2048 			return error;
2049 	}
2050 
2051 	KASSERT(sopt->sopt_size == len);
2052 	m_copydata(m, 0, len, sopt->sopt_data);
2053 	m_freem(m);
2054 
2055 	return 0;
2056 }
2057 
2058 /*
2059  * get sockopt value into mbuf
2060  *	- ONLY for legacy code
2061  *	- mbuf to be released by the caller
2062  *	- will not sleep
2063  */
2064 struct mbuf *
2065 sockopt_getmbuf(const struct sockopt *sopt)
2066 {
2067 	struct mbuf *m;
2068 
2069 	if (sopt->sopt_size > MCLBYTES)
2070 		return NULL;
2071 
2072 	m = m_get(M_DONTWAIT, MT_SOOPTS);
2073 	if (m == NULL)
2074 		return NULL;
2075 
2076 	if (sopt->sopt_size > MLEN) {
2077 		MCLGET(m, M_DONTWAIT);
2078 		if ((m->m_flags & M_EXT) == 0) {
2079 			m_free(m);
2080 			return NULL;
2081 		}
2082 	}
2083 
2084 	memcpy(mtod(m, void *), sopt->sopt_data, sopt->sopt_size);
2085 	m->m_len = sopt->sopt_size;
2086 
2087 	return m;
2088 }
2089 
2090 void
2091 sohasoutofband(struct socket *so)
2092 {
2093 
2094 	fownsignal(so->so_pgid, SIGURG, POLL_PRI, POLLPRI|POLLRDBAND, so);
2095 	selnotify(&so->so_rcv.sb_sel, POLLPRI | POLLRDBAND, NOTE_SUBMIT);
2096 }
2097 
2098 static void
2099 filt_sordetach(struct knote *kn)
2100 {
2101 	struct socket	*so;
2102 
2103 	so = ((file_t *)kn->kn_obj)->f_data;
2104 	solock(so);
2105 	SLIST_REMOVE(&so->so_rcv.sb_sel.sel_klist, kn, knote, kn_selnext);
2106 	if (SLIST_EMPTY(&so->so_rcv.sb_sel.sel_klist))
2107 		so->so_rcv.sb_flags &= ~SB_KNOTE;
2108 	sounlock(so);
2109 }
2110 
2111 /*ARGSUSED*/
2112 static int
2113 filt_soread(struct knote *kn, long hint)
2114 {
2115 	struct socket	*so;
2116 	int rv;
2117 
2118 	so = ((file_t *)kn->kn_obj)->f_data;
2119 	if (hint != NOTE_SUBMIT)
2120 		solock(so);
2121 	kn->kn_data = so->so_rcv.sb_cc;
2122 	if (so->so_state & SS_CANTRCVMORE) {
2123 		kn->kn_flags |= EV_EOF;
2124 		kn->kn_fflags = so->so_error;
2125 		rv = 1;
2126 	} else if (so->so_error)	/* temporary udp error */
2127 		rv = 1;
2128 	else if (kn->kn_sfflags & NOTE_LOWAT)
2129 		rv = (kn->kn_data >= kn->kn_sdata);
2130 	else
2131 		rv = (kn->kn_data >= so->so_rcv.sb_lowat);
2132 	if (hint != NOTE_SUBMIT)
2133 		sounlock(so);
2134 	return rv;
2135 }
2136 
2137 static void
2138 filt_sowdetach(struct knote *kn)
2139 {
2140 	struct socket	*so;
2141 
2142 	so = ((file_t *)kn->kn_obj)->f_data;
2143 	solock(so);
2144 	SLIST_REMOVE(&so->so_snd.sb_sel.sel_klist, kn, knote, kn_selnext);
2145 	if (SLIST_EMPTY(&so->so_snd.sb_sel.sel_klist))
2146 		so->so_snd.sb_flags &= ~SB_KNOTE;
2147 	sounlock(so);
2148 }
2149 
2150 /*ARGSUSED*/
2151 static int
2152 filt_sowrite(struct knote *kn, long hint)
2153 {
2154 	struct socket	*so;
2155 	int rv;
2156 
2157 	so = ((file_t *)kn->kn_obj)->f_data;
2158 	if (hint != NOTE_SUBMIT)
2159 		solock(so);
2160 	kn->kn_data = sbspace(&so->so_snd);
2161 	if (so->so_state & SS_CANTSENDMORE) {
2162 		kn->kn_flags |= EV_EOF;
2163 		kn->kn_fflags = so->so_error;
2164 		rv = 1;
2165 	} else if (so->so_error)	/* temporary udp error */
2166 		rv = 1;
2167 	else if (((so->so_state & SS_ISCONNECTED) == 0) &&
2168 	    (so->so_proto->pr_flags & PR_CONNREQUIRED))
2169 		rv = 0;
2170 	else if (kn->kn_sfflags & NOTE_LOWAT)
2171 		rv = (kn->kn_data >= kn->kn_sdata);
2172 	else
2173 		rv = (kn->kn_data >= so->so_snd.sb_lowat);
2174 	if (hint != NOTE_SUBMIT)
2175 		sounlock(so);
2176 	return rv;
2177 }
2178 
2179 /*ARGSUSED*/
2180 static int
2181 filt_solisten(struct knote *kn, long hint)
2182 {
2183 	struct socket	*so;
2184 	int rv;
2185 
2186 	so = ((file_t *)kn->kn_obj)->f_data;
2187 
2188 	/*
2189 	 * Set kn_data to number of incoming connections, not
2190 	 * counting partial (incomplete) connections.
2191 	 */
2192 	if (hint != NOTE_SUBMIT)
2193 		solock(so);
2194 	kn->kn_data = so->so_qlen;
2195 	rv = (kn->kn_data > 0);
2196 	if (hint != NOTE_SUBMIT)
2197 		sounlock(so);
2198 	return rv;
2199 }
2200 
2201 static const struct filterops solisten_filtops =
2202 	{ 1, NULL, filt_sordetach, filt_solisten };
2203 static const struct filterops soread_filtops =
2204 	{ 1, NULL, filt_sordetach, filt_soread };
2205 static const struct filterops sowrite_filtops =
2206 	{ 1, NULL, filt_sowdetach, filt_sowrite };
2207 
2208 int
2209 soo_kqfilter(struct file *fp, struct knote *kn)
2210 {
2211 	struct socket	*so;
2212 	struct sockbuf	*sb;
2213 
2214 	so = ((file_t *)kn->kn_obj)->f_data;
2215 	solock(so);
2216 	switch (kn->kn_filter) {
2217 	case EVFILT_READ:
2218 		if (so->so_options & SO_ACCEPTCONN)
2219 			kn->kn_fop = &solisten_filtops;
2220 		else
2221 			kn->kn_fop = &soread_filtops;
2222 		sb = &so->so_rcv;
2223 		break;
2224 	case EVFILT_WRITE:
2225 		kn->kn_fop = &sowrite_filtops;
2226 		sb = &so->so_snd;
2227 		break;
2228 	default:
2229 		sounlock(so);
2230 		return (EINVAL);
2231 	}
2232 	SLIST_INSERT_HEAD(&sb->sb_sel.sel_klist, kn, kn_selnext);
2233 	sb->sb_flags |= SB_KNOTE;
2234 	sounlock(so);
2235 	return (0);
2236 }
2237 
2238 static int
2239 sodopoll(struct socket *so, int events)
2240 {
2241 	int revents;
2242 
2243 	revents = 0;
2244 
2245 	if (events & (POLLIN | POLLRDNORM))
2246 		if (soreadable(so))
2247 			revents |= events & (POLLIN | POLLRDNORM);
2248 
2249 	if (events & (POLLOUT | POLLWRNORM))
2250 		if (sowritable(so))
2251 			revents |= events & (POLLOUT | POLLWRNORM);
2252 
2253 	if (events & (POLLPRI | POLLRDBAND))
2254 		if (so->so_oobmark || (so->so_state & SS_RCVATMARK))
2255 			revents |= events & (POLLPRI | POLLRDBAND);
2256 
2257 	return revents;
2258 }
2259 
2260 int
2261 sopoll(struct socket *so, int events)
2262 {
2263 	int revents = 0;
2264 
2265 #ifndef DIAGNOSTIC
2266 	/*
2267 	 * Do a quick, unlocked check in expectation that the socket
2268 	 * will be ready for I/O.  Don't do this check if DIAGNOSTIC,
2269 	 * as the solocked() assertions will fail.
2270 	 */
2271 	if ((revents = sodopoll(so, events)) != 0)
2272 		return revents;
2273 #endif
2274 
2275 	solock(so);
2276 	if ((revents = sodopoll(so, events)) == 0) {
2277 		if (events & (POLLIN | POLLPRI | POLLRDNORM | POLLRDBAND)) {
2278 			selrecord(curlwp, &so->so_rcv.sb_sel);
2279 			so->so_rcv.sb_flags |= SB_NOTIFY;
2280 		}
2281 
2282 		if (events & (POLLOUT | POLLWRNORM)) {
2283 			selrecord(curlwp, &so->so_snd.sb_sel);
2284 			so->so_snd.sb_flags |= SB_NOTIFY;
2285 		}
2286 	}
2287 	sounlock(so);
2288 
2289 	return revents;
2290 }
2291 
2292 
2293 #include <sys/sysctl.h>
2294 
2295 static int sysctl_kern_somaxkva(SYSCTLFN_PROTO);
2296 
2297 /*
2298  * sysctl helper routine for kern.somaxkva.  ensures that the given
2299  * value is not too small.
2300  * (XXX should we maybe make sure it's not too large as well?)
2301  */
2302 static int
2303 sysctl_kern_somaxkva(SYSCTLFN_ARGS)
2304 {
2305 	int error, new_somaxkva;
2306 	struct sysctlnode node;
2307 
2308 	new_somaxkva = somaxkva;
2309 	node = *rnode;
2310 	node.sysctl_data = &new_somaxkva;
2311 	error = sysctl_lookup(SYSCTLFN_CALL(&node));
2312 	if (error || newp == NULL)
2313 		return (error);
2314 
2315 	if (new_somaxkva < (16 * 1024 * 1024)) /* sanity */
2316 		return (EINVAL);
2317 
2318 	mutex_enter(&so_pendfree_lock);
2319 	somaxkva = new_somaxkva;
2320 	cv_broadcast(&socurkva_cv);
2321 	mutex_exit(&so_pendfree_lock);
2322 
2323 	return (error);
2324 }
2325 
2326 static void
2327 sysctl_kern_somaxkva_setup(void)
2328 {
2329 
2330 	KASSERT(socket_sysctllog == NULL);
2331 	sysctl_createv(&socket_sysctllog, 0, NULL, NULL,
2332 		       CTLFLAG_PERMANENT,
2333 		       CTLTYPE_NODE, "kern", NULL,
2334 		       NULL, 0, NULL, 0,
2335 		       CTL_KERN, CTL_EOL);
2336 
2337 	sysctl_createv(&socket_sysctllog, 0, NULL, NULL,
2338 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
2339 		       CTLTYPE_INT, "somaxkva",
2340 		       SYSCTL_DESCR("Maximum amount of kernel memory to be "
2341 				    "used for socket buffers"),
2342 		       sysctl_kern_somaxkva, 0, NULL, 0,
2343 		       CTL_KERN, KERN_SOMAXKVA, CTL_EOL);
2344 }
2345