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