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