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