xref: /netbsd-src/sys/kern/uipc_socket.c (revision 4d342c046e3288fb5a1edcd33cfec48c41c80664)
1 /*	$NetBSD: uipc_socket.c,v 1.291 2020/08/26 22:54:30 christos 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.291 2020/08/26 22:54:30 christos 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)(uintptr_t)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_egid = kauth_cred_getegid(l->l_cred);
530 	so->so_cpid = l->l_proc->p_pid;
531 
532 	/*
533 	 * Lock assigned and taken during PCB attach, unless we share
534 	 * the lock with another socket, e.g. socketpair(2) case.
535 	 */
536 	if (lockso) {
537 		lock = lockso->so_lock;
538 		so->so_lock = lock;
539 		mutex_obj_hold(lock);
540 		mutex_enter(lock);
541 	}
542 
543 	/* Attach the PCB (returns with the socket lock held). */
544 	error = (*prp->pr_usrreqs->pr_attach)(so, proto);
545 	KASSERT(solocked(so));
546 
547 	if (error) {
548 		KASSERT(so->so_pcb == NULL);
549 		so->so_state |= SS_NOFDREF;
550 		sofree(so);
551 		return error;
552 	}
553 	so->so_cred = kauth_cred_dup(l->l_cred);
554 	sounlock(so);
555 
556 	*aso = so;
557 	return 0;
558 }
559 
560 /*
561  * fsocreate: create a socket and a file descriptor associated with it.
562  *
563  * => On success, write file descriptor to fdout and return zero.
564  * => On failure, return non-zero; *fdout will be undefined.
565  */
566 int
567 fsocreate(int domain, struct socket **sop, int type, int proto, int *fdout)
568 {
569 	lwp_t *l = curlwp;
570 	int error, fd, flags;
571 	struct socket *so;
572 	struct file *fp;
573 
574 	if ((error = fd_allocfile(&fp, &fd)) != 0) {
575 		return error;
576 	}
577 	flags = type & SOCK_FLAGS_MASK;
578 	fd_set_exclose(l, fd, (flags & SOCK_CLOEXEC) != 0);
579 	fp->f_flag = FREAD|FWRITE|((flags & SOCK_NONBLOCK) ? FNONBLOCK : 0)|
580 	    ((flags & SOCK_NOSIGPIPE) ? FNOSIGPIPE : 0);
581 	fp->f_type = DTYPE_SOCKET;
582 	fp->f_ops = &socketops;
583 
584 	type &= ~SOCK_FLAGS_MASK;
585 	error = socreate(domain, &so, type, proto, l, NULL);
586 	if (error) {
587 		fd_abort(curproc, fp, fd);
588 		return error;
589 	}
590 	if (flags & SOCK_NONBLOCK) {
591 		so->so_state |= SS_NBIO;
592 	}
593 	fp->f_socket = so;
594 	fd_affix(curproc, fp, fd);
595 
596 	if (sop != NULL) {
597 		*sop = so;
598 	}
599 	*fdout = fd;
600 	return error;
601 }
602 
603 int
604 sofamily(const struct socket *so)
605 {
606 	const struct protosw *pr;
607 	const struct domain *dom;
608 
609 	if ((pr = so->so_proto) == NULL)
610 		return AF_UNSPEC;
611 	if ((dom = pr->pr_domain) == NULL)
612 		return AF_UNSPEC;
613 	return dom->dom_family;
614 }
615 
616 int
617 sobind(struct socket *so, struct sockaddr *nam, struct lwp *l)
618 {
619 	int error;
620 
621 	solock(so);
622 	if (nam->sa_family != so->so_proto->pr_domain->dom_family) {
623 		sounlock(so);
624 		return EAFNOSUPPORT;
625 	}
626 	error = (*so->so_proto->pr_usrreqs->pr_bind)(so, nam, l);
627 	sounlock(so);
628 	return error;
629 }
630 
631 int
632 solisten(struct socket *so, int backlog, struct lwp *l)
633 {
634 	int error;
635 	short oldopt, oldqlimit;
636 
637 	solock(so);
638 	if ((so->so_state & (SS_ISCONNECTED | SS_ISCONNECTING |
639 	    SS_ISDISCONNECTING)) != 0) {
640 		sounlock(so);
641 		return EINVAL;
642 	}
643 	oldopt = so->so_options;
644 	oldqlimit = so->so_qlimit;
645 	if (TAILQ_EMPTY(&so->so_q))
646 		so->so_options |= SO_ACCEPTCONN;
647 	if (backlog < 0)
648 		backlog = 0;
649 	so->so_qlimit = uimin(backlog, somaxconn);
650 
651 	error = (*so->so_proto->pr_usrreqs->pr_listen)(so, l);
652 	if (error != 0) {
653 		so->so_options = oldopt;
654 		so->so_qlimit = oldqlimit;
655 		sounlock(so);
656 		return error;
657 	}
658 	sounlock(so);
659 	return 0;
660 }
661 
662 void
663 sofree(struct socket *so)
664 {
665 	u_int refs;
666 
667 	KASSERT(solocked(so));
668 
669 	if (so->so_pcb || (so->so_state & SS_NOFDREF) == 0) {
670 		sounlock(so);
671 		return;
672 	}
673 	if (so->so_head) {
674 		/*
675 		 * We must not decommission a socket that's on the accept(2)
676 		 * queue.  If we do, then accept(2) may hang after select(2)
677 		 * indicated that the listening socket was ready.
678 		 */
679 		if (!soqremque(so, 0)) {
680 			sounlock(so);
681 			return;
682 		}
683 	}
684 	if (so->so_rcv.sb_hiwat)
685 		(void)chgsbsize(so->so_uidinfo, &so->so_rcv.sb_hiwat, 0,
686 		    RLIM_INFINITY);
687 	if (so->so_snd.sb_hiwat)
688 		(void)chgsbsize(so->so_uidinfo, &so->so_snd.sb_hiwat, 0,
689 		    RLIM_INFINITY);
690 	sbrelease(&so->so_snd, so);
691 	KASSERT(!cv_has_waiters(&so->so_cv));
692 	KASSERT(!cv_has_waiters(&so->so_rcv.sb_cv));
693 	KASSERT(!cv_has_waiters(&so->so_snd.sb_cv));
694 	sorflush(so);
695 	refs = so->so_aborting;	/* XXX */
696 	/* Remove acccept filter if one is present. */
697 	if (so->so_accf != NULL)
698 		(void)accept_filt_clear(so);
699 	sounlock(so);
700 	if (refs == 0)		/* XXX */
701 		soput(so);
702 }
703 
704 /*
705  * soclose: close a socket on last file table reference removal.
706  * Initiate disconnect if connected.  Free socket when disconnect complete.
707  */
708 int
709 soclose(struct socket *so)
710 {
711 	struct socket *so2;
712 	int error = 0;
713 
714 	solock(so);
715 	if (so->so_options & SO_ACCEPTCONN) {
716 		for (;;) {
717 			if ((so2 = TAILQ_FIRST(&so->so_q0)) != 0) {
718 				KASSERT(solocked2(so, so2));
719 				(void) soqremque(so2, 0);
720 				/* soabort drops the lock. */
721 				(void) soabort(so2);
722 				solock(so);
723 				continue;
724 			}
725 			if ((so2 = TAILQ_FIRST(&so->so_q)) != 0) {
726 				KASSERT(solocked2(so, so2));
727 				(void) soqremque(so2, 1);
728 				/* soabort drops the lock. */
729 				(void) soabort(so2);
730 				solock(so);
731 				continue;
732 			}
733 			break;
734 		}
735 	}
736 	if (so->so_pcb == NULL)
737 		goto discard;
738 	if (so->so_state & SS_ISCONNECTED) {
739 		if ((so->so_state & SS_ISDISCONNECTING) == 0) {
740 			error = sodisconnect(so);
741 			if (error)
742 				goto drop;
743 		}
744 		if (so->so_options & SO_LINGER) {
745 			if ((so->so_state & (SS_ISDISCONNECTING|SS_NBIO)) ==
746 			    (SS_ISDISCONNECTING|SS_NBIO))
747 				goto drop;
748 			while (so->so_state & SS_ISCONNECTED) {
749 				error = sowait(so, true, so->so_linger * hz);
750 				if (error)
751 					break;
752 			}
753 		}
754 	}
755  drop:
756 	if (so->so_pcb) {
757 		KASSERT(solocked(so));
758 		(*so->so_proto->pr_usrreqs->pr_detach)(so);
759 	}
760  discard:
761 	KASSERT((so->so_state & SS_NOFDREF) == 0);
762 	kauth_cred_free(so->so_cred);
763 	so->so_cred = NULL;
764 	so->so_state |= SS_NOFDREF;
765 	sofree(so);
766 	return error;
767 }
768 
769 /*
770  * Must be called with the socket locked..  Will return with it unlocked.
771  */
772 int
773 soabort(struct socket *so)
774 {
775 	u_int refs;
776 	int error;
777 
778 	KASSERT(solocked(so));
779 	KASSERT(so->so_head == NULL);
780 
781 	so->so_aborting++;		/* XXX */
782 	error = (*so->so_proto->pr_usrreqs->pr_abort)(so);
783 	refs = --so->so_aborting;	/* XXX */
784 	if (error || (refs == 0)) {
785 		sofree(so);
786 	} else {
787 		sounlock(so);
788 	}
789 	return error;
790 }
791 
792 int
793 soaccept(struct socket *so, struct sockaddr *nam)
794 {
795 	int error;
796 
797 	KASSERT(solocked(so));
798 	KASSERT((so->so_state & SS_NOFDREF) != 0);
799 
800 	so->so_state &= ~SS_NOFDREF;
801 	if ((so->so_state & SS_ISDISCONNECTED) == 0 ||
802 	    (so->so_proto->pr_flags & PR_ABRTACPTDIS) == 0)
803 		error = (*so->so_proto->pr_usrreqs->pr_accept)(so, nam);
804 	else
805 		error = ECONNABORTED;
806 
807 	return error;
808 }
809 
810 int
811 soconnect(struct socket *so, struct sockaddr *nam, struct lwp *l)
812 {
813 	int error;
814 
815 	KASSERT(solocked(so));
816 
817 	if (so->so_options & SO_ACCEPTCONN)
818 		return EOPNOTSUPP;
819 	/*
820 	 * If protocol is connection-based, can only connect once.
821 	 * Otherwise, if connected, try to disconnect first.
822 	 * This allows user to disconnect by connecting to, e.g.,
823 	 * a null address.
824 	 */
825 	if (so->so_state & (SS_ISCONNECTED|SS_ISCONNECTING) &&
826 	    ((so->so_proto->pr_flags & PR_CONNREQUIRED) ||
827 	    (error = sodisconnect(so)))) {
828 		error = EISCONN;
829 	} else {
830 		if (nam->sa_family != so->so_proto->pr_domain->dom_family) {
831 			return EAFNOSUPPORT;
832 		}
833 		error = (*so->so_proto->pr_usrreqs->pr_connect)(so, nam, l);
834 	}
835 
836 	return error;
837 }
838 
839 int
840 soconnect2(struct socket *so1, struct socket *so2)
841 {
842 	KASSERT(solocked2(so1, so2));
843 
844 	return (*so1->so_proto->pr_usrreqs->pr_connect2)(so1, so2);
845 }
846 
847 int
848 sodisconnect(struct socket *so)
849 {
850 	int error;
851 
852 	KASSERT(solocked(so));
853 
854 	if ((so->so_state & SS_ISCONNECTED) == 0) {
855 		error = ENOTCONN;
856 	} else if (so->so_state & SS_ISDISCONNECTING) {
857 		error = EALREADY;
858 	} else {
859 		error = (*so->so_proto->pr_usrreqs->pr_disconnect)(so);
860 	}
861 	return error;
862 }
863 
864 #define	SBLOCKWAIT(f)	(((f) & MSG_DONTWAIT) ? M_NOWAIT : M_WAITOK)
865 /*
866  * Send on a socket.
867  * If send must go all at once and message is larger than
868  * send buffering, then hard error.
869  * Lock against other senders.
870  * If must go all at once and not enough room now, then
871  * inform user that this would block and do nothing.
872  * Otherwise, if nonblocking, send as much as possible.
873  * The data to be sent is described by "uio" if nonzero,
874  * otherwise by the mbuf chain "top" (which must be null
875  * if uio is not).  Data provided in mbuf chain must be small
876  * enough to send all at once.
877  *
878  * Returns nonzero on error, timeout or signal; callers
879  * must check for short counts if EINTR/ERESTART are returned.
880  * Data and control buffers are freed on return.
881  */
882 int
883 sosend(struct socket *so, struct sockaddr *addr, struct uio *uio,
884 	struct mbuf *top, struct mbuf *control, int flags, struct lwp *l)
885 {
886 	struct mbuf **mp, *m;
887 	long space, len, resid, clen, mlen;
888 	int error, s, dontroute, atomic;
889 	short wakeup_state = 0;
890 
891 	clen = 0;
892 
893 	/*
894 	 * solock() provides atomicity of access.  splsoftnet() prevents
895 	 * protocol processing soft interrupts from interrupting us and
896 	 * blocking (expensive).
897 	 */
898 	s = splsoftnet();
899 	solock(so);
900 	atomic = sosendallatonce(so) || top;
901 	if (uio)
902 		resid = uio->uio_resid;
903 	else
904 		resid = top->m_pkthdr.len;
905 	/*
906 	 * In theory resid should be unsigned.
907 	 * However, space must be signed, as it might be less than 0
908 	 * if we over-committed, and we must use a signed comparison
909 	 * of space and resid.  On the other hand, a negative resid
910 	 * causes us to loop sending 0-length segments to the protocol.
911 	 */
912 	if (resid < 0) {
913 		error = EINVAL;
914 		goto out;
915 	}
916 	dontroute =
917 	    (flags & MSG_DONTROUTE) && (so->so_options & SO_DONTROUTE) == 0 &&
918 	    (so->so_proto->pr_flags & PR_ATOMIC);
919 	l->l_ru.ru_msgsnd++;
920 	if (control)
921 		clen = control->m_len;
922  restart:
923 	if ((error = sblock(&so->so_snd, SBLOCKWAIT(flags))) != 0)
924 		goto out;
925 	do {
926 		if (so->so_state & SS_CANTSENDMORE) {
927 			error = EPIPE;
928 			goto release;
929 		}
930 		if (so->so_error) {
931 			error = so->so_error;
932 			if ((flags & MSG_PEEK) == 0)
933 				so->so_error = 0;
934 			goto release;
935 		}
936 		if ((so->so_state & SS_ISCONNECTED) == 0) {
937 			if (so->so_proto->pr_flags & PR_CONNREQUIRED) {
938 				if (resid || clen == 0) {
939 					error = ENOTCONN;
940 					goto release;
941 				}
942 			} else if (addr == NULL) {
943 				error = EDESTADDRREQ;
944 				goto release;
945 			}
946 		}
947 		space = sbspace(&so->so_snd);
948 		if (flags & MSG_OOB)
949 			space += 1024;
950 		if ((atomic && resid > so->so_snd.sb_hiwat) ||
951 		    clen > so->so_snd.sb_hiwat) {
952 			error = EMSGSIZE;
953 			goto release;
954 		}
955 		if (space < resid + clen &&
956 		    (atomic || space < so->so_snd.sb_lowat || space < clen)) {
957 			if ((so->so_state & SS_NBIO) || (flags & MSG_NBIO)) {
958 				error = EWOULDBLOCK;
959 				goto release;
960 			}
961 			sbunlock(&so->so_snd);
962 			if (wakeup_state & SS_RESTARTSYS) {
963 				error = ERESTART;
964 				goto out;
965 			}
966 			error = sbwait(&so->so_snd);
967 			if (error)
968 				goto out;
969 			wakeup_state = so->so_state;
970 			goto restart;
971 		}
972 		wakeup_state = 0;
973 		mp = &top;
974 		space -= clen;
975 		do {
976 			if (uio == NULL) {
977 				/*
978 				 * Data is prepackaged in "top".
979 				 */
980 				resid = 0;
981 				if (flags & MSG_EOR)
982 					top->m_flags |= M_EOR;
983 			} else do {
984 				sounlock(so);
985 				splx(s);
986 				if (top == NULL) {
987 					m = m_gethdr(M_WAIT, MT_DATA);
988 					mlen = MHLEN;
989 					m->m_pkthdr.len = 0;
990 					m_reset_rcvif(m);
991 				} else {
992 					m = m_get(M_WAIT, MT_DATA);
993 					mlen = MLEN;
994 				}
995 				MCLAIM(m, so->so_snd.sb_mowner);
996 				if (sock_loan_thresh >= 0 &&
997 				    uio->uio_iov->iov_len >= sock_loan_thresh &&
998 				    space >= sock_loan_thresh &&
999 				    (len = sosend_loan(so, uio, m,
1000 						       space)) != 0) {
1001 					SOSEND_COUNTER_INCR(&sosend_loan_big);
1002 					space -= len;
1003 					goto have_data;
1004 				}
1005 				if (resid >= MINCLSIZE && space >= MCLBYTES) {
1006 					SOSEND_COUNTER_INCR(&sosend_copy_big);
1007 					m_clget(m, M_DONTWAIT);
1008 					if ((m->m_flags & M_EXT) == 0)
1009 						goto nopages;
1010 					mlen = MCLBYTES;
1011 					if (atomic && top == 0) {
1012 						len = lmin(MCLBYTES - max_hdr,
1013 						    resid);
1014 						m->m_data += max_hdr;
1015 					} else
1016 						len = lmin(MCLBYTES, resid);
1017 					space -= len;
1018 				} else {
1019  nopages:
1020 					SOSEND_COUNTER_INCR(&sosend_copy_small);
1021 					len = lmin(lmin(mlen, resid), space);
1022 					space -= len;
1023 					/*
1024 					 * For datagram protocols, leave room
1025 					 * for protocol headers in first mbuf.
1026 					 */
1027 					if (atomic && top == 0 && len < mlen)
1028 						m_align(m, len);
1029 				}
1030 				error = uiomove(mtod(m, void *), (int)len, uio);
1031  have_data:
1032 				resid = uio->uio_resid;
1033 				m->m_len = len;
1034 				*mp = m;
1035 				top->m_pkthdr.len += len;
1036 				s = splsoftnet();
1037 				solock(so);
1038 				if (error != 0)
1039 					goto release;
1040 				mp = &m->m_next;
1041 				if (resid <= 0) {
1042 					if (flags & MSG_EOR)
1043 						top->m_flags |= M_EOR;
1044 					break;
1045 				}
1046 			} while (space > 0 && atomic);
1047 
1048 			if (so->so_state & SS_CANTSENDMORE) {
1049 				error = EPIPE;
1050 				goto release;
1051 			}
1052 			if (dontroute)
1053 				so->so_options |= SO_DONTROUTE;
1054 			if (resid > 0)
1055 				so->so_state |= SS_MORETOCOME;
1056 			if (flags & MSG_OOB) {
1057 				error = (*so->so_proto->pr_usrreqs->pr_sendoob)(
1058 				    so, top, control);
1059 			} else {
1060 				error = (*so->so_proto->pr_usrreqs->pr_send)(so,
1061 				    top, addr, control, l);
1062 			}
1063 			if (dontroute)
1064 				so->so_options &= ~SO_DONTROUTE;
1065 			if (resid > 0)
1066 				so->so_state &= ~SS_MORETOCOME;
1067 			clen = 0;
1068 			control = NULL;
1069 			top = NULL;
1070 			mp = &top;
1071 			if (error != 0)
1072 				goto release;
1073 		} while (resid && space > 0);
1074 	} while (resid);
1075 
1076  release:
1077 	sbunlock(&so->so_snd);
1078  out:
1079 	sounlock(so);
1080 	splx(s);
1081 	if (top)
1082 		m_freem(top);
1083 	if (control)
1084 		m_freem(control);
1085 	return error;
1086 }
1087 
1088 /*
1089  * Following replacement or removal of the first mbuf on the first
1090  * mbuf chain of a socket buffer, push necessary state changes back
1091  * into the socket buffer so that other consumers see the values
1092  * consistently.  'nextrecord' is the caller's locally stored value of
1093  * the original value of sb->sb_mb->m_nextpkt which must be restored
1094  * when the lead mbuf changes.  NOTE: 'nextrecord' may be NULL.
1095  */
1096 static void
1097 sbsync(struct sockbuf *sb, struct mbuf *nextrecord)
1098 {
1099 
1100 	KASSERT(solocked(sb->sb_so));
1101 
1102 	/*
1103 	 * First, update for the new value of nextrecord.  If necessary,
1104 	 * make it the first record.
1105 	 */
1106 	if (sb->sb_mb != NULL)
1107 		sb->sb_mb->m_nextpkt = nextrecord;
1108 	else
1109 		sb->sb_mb = nextrecord;
1110 
1111         /*
1112          * Now update any dependent socket buffer fields to reflect
1113          * the new state.  This is an inline of SB_EMPTY_FIXUP, with
1114          * the addition of a second clause that takes care of the
1115          * case where sb_mb has been updated, but remains the last
1116          * record.
1117          */
1118         if (sb->sb_mb == NULL) {
1119                 sb->sb_mbtail = NULL;
1120                 sb->sb_lastrecord = NULL;
1121         } else if (sb->sb_mb->m_nextpkt == NULL)
1122                 sb->sb_lastrecord = sb->sb_mb;
1123 }
1124 
1125 /*
1126  * Implement receive operations on a socket.
1127  *
1128  * We depend on the way that records are added to the sockbuf by sbappend*. In
1129  * particular, each record (mbufs linked through m_next) must begin with an
1130  * address if the protocol so specifies, followed by an optional mbuf or mbufs
1131  * containing ancillary data, and then zero or more mbufs of data.
1132  *
1133  * In order to avoid blocking network interrupts for the entire time here, we
1134  * splx() while doing the actual copy to user space. Although the sockbuf is
1135  * locked, new data may still be appended, and thus we must maintain
1136  * consistency of the sockbuf during that time.
1137  *
1138  * The caller may receive the data as a single mbuf chain by supplying an mbuf
1139  * **mp0 for use in returning the chain. The uio is then used only for the
1140  * count in uio_resid.
1141  */
1142 int
1143 soreceive(struct socket *so, struct mbuf **paddr, struct uio *uio,
1144     struct mbuf **mp0, struct mbuf **controlp, int *flagsp)
1145 {
1146 	struct lwp *l = curlwp;
1147 	struct mbuf *m, **mp, *mt;
1148 	size_t len, offset, moff, orig_resid;
1149 	int atomic, flags, error, s, type;
1150 	const struct protosw *pr;
1151 	struct mbuf *nextrecord;
1152 	int mbuf_removed = 0;
1153 	const struct domain *dom;
1154 	short wakeup_state = 0;
1155 
1156 	pr = so->so_proto;
1157 	atomic = pr->pr_flags & PR_ATOMIC;
1158 	dom = pr->pr_domain;
1159 	mp = mp0;
1160 	type = 0;
1161 	orig_resid = uio->uio_resid;
1162 
1163 	if (paddr != NULL)
1164 		*paddr = NULL;
1165 	if (controlp != NULL)
1166 		*controlp = NULL;
1167 	if (flagsp != NULL)
1168 		flags = *flagsp &~ MSG_EOR;
1169 	else
1170 		flags = 0;
1171 
1172 	if (flags & MSG_OOB) {
1173 		m = m_get(M_WAIT, MT_DATA);
1174 		solock(so);
1175 		error = (*pr->pr_usrreqs->pr_recvoob)(so, m, flags & MSG_PEEK);
1176 		sounlock(so);
1177 		if (error)
1178 			goto bad;
1179 		do {
1180 			error = uiomove(mtod(m, void *),
1181 			    MIN(uio->uio_resid, m->m_len), uio);
1182 			m = m_free(m);
1183 		} while (uio->uio_resid > 0 && error == 0 && m);
1184 		/* We consumed the oob data, no more oobmark.  */
1185 		so->so_oobmark = 0;
1186 		so->so_state &= ~SS_RCVATMARK;
1187 bad:
1188 		if (m != NULL)
1189 			m_freem(m);
1190 		return error;
1191 	}
1192 	if (mp != NULL)
1193 		*mp = NULL;
1194 
1195 	/*
1196 	 * solock() provides atomicity of access.  splsoftnet() prevents
1197 	 * protocol processing soft interrupts from interrupting us and
1198 	 * blocking (expensive).
1199 	 */
1200 	s = splsoftnet();
1201 	solock(so);
1202 restart:
1203 	if ((error = sblock(&so->so_rcv, SBLOCKWAIT(flags))) != 0) {
1204 		sounlock(so);
1205 		splx(s);
1206 		return error;
1207 	}
1208 	m = so->so_rcv.sb_mb;
1209 
1210 	/*
1211 	 * If we have less data than requested, block awaiting more
1212 	 * (subject to any timeout) if:
1213 	 *   1. the current count is less than the low water mark,
1214 	 *   2. MSG_WAITALL is set, and it is possible to do the entire
1215 	 *	receive operation at once if we block (resid <= hiwat), or
1216 	 *   3. MSG_DONTWAIT is not set.
1217 	 * If MSG_WAITALL is set but resid is larger than the receive buffer,
1218 	 * we have to do the receive in sections, and thus risk returning
1219 	 * a short count if a timeout or signal occurs after we start.
1220 	 */
1221 	if (m == NULL ||
1222 	    ((flags & MSG_DONTWAIT) == 0 &&
1223 	     so->so_rcv.sb_cc < uio->uio_resid &&
1224 	     (so->so_rcv.sb_cc < so->so_rcv.sb_lowat ||
1225 	      ((flags & MSG_WAITALL) &&
1226 	       uio->uio_resid <= so->so_rcv.sb_hiwat)) &&
1227 	     m->m_nextpkt == NULL && !atomic)) {
1228 #ifdef DIAGNOSTIC
1229 		if (m == NULL && so->so_rcv.sb_cc)
1230 			panic("receive 1");
1231 #endif
1232 		if (so->so_error || so->so_rerror) {
1233 			u_short *e;
1234 			if (m != NULL)
1235 				goto dontblock;
1236 			e = so->so_error ? &so->so_error : &so->so_rerror;
1237 			error = *e;
1238 			if ((flags & MSG_PEEK) == 0)
1239 				*e = 0;
1240 			goto release;
1241 		}
1242 		if (so->so_state & SS_CANTRCVMORE) {
1243 			if (m != NULL)
1244 				goto dontblock;
1245 			else
1246 				goto release;
1247 		}
1248 		for (; m != NULL; m = m->m_next)
1249 			if (m->m_type == MT_OOBDATA  || (m->m_flags & M_EOR)) {
1250 				m = so->so_rcv.sb_mb;
1251 				goto dontblock;
1252 			}
1253 		if ((so->so_state & (SS_ISCONNECTED|SS_ISCONNECTING)) == 0 &&
1254 		    (so->so_proto->pr_flags & PR_CONNREQUIRED)) {
1255 			error = ENOTCONN;
1256 			goto release;
1257 		}
1258 		if (uio->uio_resid == 0)
1259 			goto release;
1260 		if ((so->so_state & SS_NBIO) ||
1261 		    (flags & (MSG_DONTWAIT|MSG_NBIO))) {
1262 			error = EWOULDBLOCK;
1263 			goto release;
1264 		}
1265 		SBLASTRECORDCHK(&so->so_rcv, "soreceive sbwait 1");
1266 		SBLASTMBUFCHK(&so->so_rcv, "soreceive sbwait 1");
1267 		sbunlock(&so->so_rcv);
1268 		if (wakeup_state & SS_RESTARTSYS)
1269 			error = ERESTART;
1270 		else
1271 			error = sbwait(&so->so_rcv);
1272 		if (error != 0) {
1273 			sounlock(so);
1274 			splx(s);
1275 			return error;
1276 		}
1277 		wakeup_state = so->so_state;
1278 		goto restart;
1279 	}
1280 
1281 dontblock:
1282 	/*
1283 	 * On entry here, m points to the first record of the socket buffer.
1284 	 * From this point onward, we maintain 'nextrecord' as a cache of the
1285 	 * pointer to the next record in the socket buffer.  We must keep the
1286 	 * various socket buffer pointers and local stack versions of the
1287 	 * pointers in sync, pushing out modifications before dropping the
1288 	 * socket lock, and re-reading them when picking it up.
1289 	 *
1290 	 * Otherwise, we will race with the network stack appending new data
1291 	 * or records onto the socket buffer by using inconsistent/stale
1292 	 * versions of the field, possibly resulting in socket buffer
1293 	 * corruption.
1294 	 *
1295 	 * By holding the high-level sblock(), we prevent simultaneous
1296 	 * readers from pulling off the front of the socket buffer.
1297 	 */
1298 	if (l != NULL)
1299 		l->l_ru.ru_msgrcv++;
1300 	KASSERT(m == so->so_rcv.sb_mb);
1301 	SBLASTRECORDCHK(&so->so_rcv, "soreceive 1");
1302 	SBLASTMBUFCHK(&so->so_rcv, "soreceive 1");
1303 	nextrecord = m->m_nextpkt;
1304 
1305 	if (pr->pr_flags & PR_ADDR) {
1306 		KASSERT(m->m_type == MT_SONAME);
1307 		orig_resid = 0;
1308 		if (flags & MSG_PEEK) {
1309 			if (paddr)
1310 				*paddr = m_copym(m, 0, m->m_len, M_DONTWAIT);
1311 			m = m->m_next;
1312 		} else {
1313 			sbfree(&so->so_rcv, m);
1314 			mbuf_removed = 1;
1315 			if (paddr != NULL) {
1316 				*paddr = m;
1317 				so->so_rcv.sb_mb = m->m_next;
1318 				m->m_next = NULL;
1319 				m = so->so_rcv.sb_mb;
1320 			} else {
1321 				m = so->so_rcv.sb_mb = m_free(m);
1322 			}
1323 			sbsync(&so->so_rcv, nextrecord);
1324 		}
1325 	}
1326 
1327 	if (pr->pr_flags & PR_ADDR_OPT) {
1328 		/*
1329 		 * For SCTP we may be getting a whole message OR a partial
1330 		 * delivery.
1331 		 */
1332 		if (m->m_type == MT_SONAME) {
1333 			orig_resid = 0;
1334 			if (flags & MSG_PEEK) {
1335 				if (paddr)
1336 					*paddr = m_copym(m, 0, m->m_len, M_DONTWAIT);
1337 				m = m->m_next;
1338 			} else {
1339 				sbfree(&so->so_rcv, m);
1340 				mbuf_removed = 1;
1341 				if (paddr) {
1342 					*paddr = m;
1343 					so->so_rcv.sb_mb = m->m_next;
1344 					m->m_next = 0;
1345 					m = so->so_rcv.sb_mb;
1346 				} else {
1347 					m = so->so_rcv.sb_mb = m_free(m);
1348 				}
1349 				sbsync(&so->so_rcv, nextrecord);
1350 			}
1351 		}
1352 	}
1353 
1354 	/*
1355 	 * Process one or more MT_CONTROL mbufs present before any data mbufs
1356 	 * in the first mbuf chain on the socket buffer.  If MSG_PEEK, we
1357 	 * just copy the data; if !MSG_PEEK, we call into the protocol to
1358 	 * perform externalization (or freeing if controlp == NULL).
1359 	 */
1360 	if (__predict_false(m != NULL && m->m_type == MT_CONTROL)) {
1361 		struct mbuf *cm = NULL, *cmn;
1362 		struct mbuf **cme = &cm;
1363 
1364 		do {
1365 			if (flags & MSG_PEEK) {
1366 				if (controlp != NULL) {
1367 					*controlp = m_copym(m, 0, m->m_len, M_DONTWAIT);
1368 					controlp = &(*controlp)->m_next;
1369 				}
1370 				m = m->m_next;
1371 			} else {
1372 				sbfree(&so->so_rcv, m);
1373 				so->so_rcv.sb_mb = m->m_next;
1374 				m->m_next = NULL;
1375 				*cme = m;
1376 				cme = &(*cme)->m_next;
1377 				m = so->so_rcv.sb_mb;
1378 			}
1379 		} while (m != NULL && m->m_type == MT_CONTROL);
1380 		if ((flags & MSG_PEEK) == 0)
1381 			sbsync(&so->so_rcv, nextrecord);
1382 
1383 		for (; cm != NULL; cm = cmn) {
1384 			cmn = cm->m_next;
1385 			cm->m_next = NULL;
1386 			type = mtod(cm, struct cmsghdr *)->cmsg_type;
1387 			if (controlp != NULL) {
1388 				if (dom->dom_externalize != NULL &&
1389 				    type == SCM_RIGHTS) {
1390 					sounlock(so);
1391 					splx(s);
1392 					error = (*dom->dom_externalize)(cm, l,
1393 					    (flags & MSG_CMSG_CLOEXEC) ?
1394 					    O_CLOEXEC : 0);
1395 					s = splsoftnet();
1396 					solock(so);
1397 				}
1398 				*controlp = cm;
1399 				while (*controlp != NULL)
1400 					controlp = &(*controlp)->m_next;
1401 			} else {
1402 				/*
1403 				 * Dispose of any SCM_RIGHTS message that went
1404 				 * through the read path rather than recv.
1405 				 */
1406 				if (dom->dom_dispose != NULL &&
1407 				    type == SCM_RIGHTS) {
1408 					sounlock(so);
1409 					(*dom->dom_dispose)(cm);
1410 					solock(so);
1411 				}
1412 				m_freem(cm);
1413 			}
1414 		}
1415 		if (m != NULL)
1416 			nextrecord = so->so_rcv.sb_mb->m_nextpkt;
1417 		else
1418 			nextrecord = so->so_rcv.sb_mb;
1419 		orig_resid = 0;
1420 	}
1421 
1422 	/* If m is non-NULL, we have some data to read. */
1423 	if (__predict_true(m != NULL)) {
1424 		type = m->m_type;
1425 		if (type == MT_OOBDATA)
1426 			flags |= MSG_OOB;
1427 	}
1428 	SBLASTRECORDCHK(&so->so_rcv, "soreceive 2");
1429 	SBLASTMBUFCHK(&so->so_rcv, "soreceive 2");
1430 
1431 	moff = 0;
1432 	offset = 0;
1433 	while (m != NULL && uio->uio_resid > 0 && error == 0) {
1434 		/*
1435 		 * If the type of mbuf has changed, end the receive
1436 		 * operation and do a short read.
1437 		 */
1438 		if (m->m_type == MT_OOBDATA) {
1439 			if (type != MT_OOBDATA)
1440 				break;
1441 		} else if (type == MT_OOBDATA) {
1442 			break;
1443 		} else if (m->m_type == MT_CONTROL) {
1444 			break;
1445 		}
1446 #ifdef DIAGNOSTIC
1447 		else if (m->m_type != MT_DATA && m->m_type != MT_HEADER) {
1448 			panic("%s: m_type=%d", __func__, m->m_type);
1449 		}
1450 #endif
1451 
1452 		so->so_state &= ~SS_RCVATMARK;
1453 		wakeup_state = 0;
1454 		len = uio->uio_resid;
1455 		if (so->so_oobmark && len > so->so_oobmark - offset)
1456 			len = so->so_oobmark - offset;
1457 		if (len > m->m_len - moff)
1458 			len = m->m_len - moff;
1459 
1460 		/*
1461 		 * If mp is set, just pass back the mbufs.
1462 		 * Otherwise copy them out via the uio, then free.
1463 		 * Sockbuf must be consistent here (points to current mbuf,
1464 		 * it points to next record) when we drop priority;
1465 		 * we must note any additions to the sockbuf when we
1466 		 * block interrupts again.
1467 		 */
1468 		if (mp == NULL) {
1469 			SBLASTRECORDCHK(&so->so_rcv, "soreceive uiomove");
1470 			SBLASTMBUFCHK(&so->so_rcv, "soreceive uiomove");
1471 			sounlock(so);
1472 			splx(s);
1473 			error = uiomove(mtod(m, char *) + moff, len, uio);
1474 			s = splsoftnet();
1475 			solock(so);
1476 			if (error != 0) {
1477 				/*
1478 				 * If any part of the record has been removed
1479 				 * (such as the MT_SONAME mbuf, which will
1480 				 * happen when PR_ADDR, and thus also
1481 				 * PR_ATOMIC, is set), then drop the entire
1482 				 * record to maintain the atomicity of the
1483 				 * receive operation.
1484 				 *
1485 				 * This avoids a later panic("receive 1a")
1486 				 * when compiled with DIAGNOSTIC.
1487 				 */
1488 				if (m && mbuf_removed && atomic)
1489 					(void) sbdroprecord(&so->so_rcv);
1490 
1491 				goto release;
1492 			}
1493 		} else {
1494 			uio->uio_resid -= len;
1495 		}
1496 
1497 		if (len == m->m_len - moff) {
1498 			if (m->m_flags & M_EOR)
1499 				flags |= MSG_EOR;
1500 #ifdef SCTP
1501 			if (m->m_flags & M_NOTIFICATION)
1502 				flags |= MSG_NOTIFICATION;
1503 #endif
1504 			if (flags & MSG_PEEK) {
1505 				m = m->m_next;
1506 				moff = 0;
1507 			} else {
1508 				nextrecord = m->m_nextpkt;
1509 				sbfree(&so->so_rcv, m);
1510 				if (mp) {
1511 					*mp = m;
1512 					mp = &m->m_next;
1513 					so->so_rcv.sb_mb = m = m->m_next;
1514 					*mp = NULL;
1515 				} else {
1516 					m = so->so_rcv.sb_mb = m_free(m);
1517 				}
1518 				/*
1519 				 * If m != NULL, we also know that
1520 				 * so->so_rcv.sb_mb != NULL.
1521 				 */
1522 				KASSERT(so->so_rcv.sb_mb == m);
1523 				if (m) {
1524 					m->m_nextpkt = nextrecord;
1525 					if (nextrecord == NULL)
1526 						so->so_rcv.sb_lastrecord = m;
1527 				} else {
1528 					so->so_rcv.sb_mb = nextrecord;
1529 					SB_EMPTY_FIXUP(&so->so_rcv);
1530 				}
1531 				SBLASTRECORDCHK(&so->so_rcv, "soreceive 3");
1532 				SBLASTMBUFCHK(&so->so_rcv, "soreceive 3");
1533 			}
1534 		} else if (flags & MSG_PEEK) {
1535 			moff += len;
1536 		} else {
1537 			if (mp != NULL) {
1538 				mt = m_copym(m, 0, len, M_NOWAIT);
1539 				if (__predict_false(mt == NULL)) {
1540 					sounlock(so);
1541 					mt = m_copym(m, 0, len, M_WAIT);
1542 					solock(so);
1543 				}
1544 				*mp = mt;
1545 			}
1546 			m->m_data += len;
1547 			m->m_len -= len;
1548 			so->so_rcv.sb_cc -= len;
1549 		}
1550 
1551 		if (so->so_oobmark) {
1552 			if ((flags & MSG_PEEK) == 0) {
1553 				so->so_oobmark -= len;
1554 				if (so->so_oobmark == 0) {
1555 					so->so_state |= SS_RCVATMARK;
1556 					break;
1557 				}
1558 			} else {
1559 				offset += len;
1560 				if (offset == so->so_oobmark)
1561 					break;
1562 			}
1563 		}
1564 		if (flags & MSG_EOR)
1565 			break;
1566 
1567 		/*
1568 		 * If the MSG_WAITALL flag is set (for non-atomic socket),
1569 		 * we must not quit until "uio->uio_resid == 0" or an error
1570 		 * termination.  If a signal/timeout occurs, return
1571 		 * with a short count but without error.
1572 		 * Keep sockbuf locked against other readers.
1573 		 */
1574 		while (flags & MSG_WAITALL && m == NULL && uio->uio_resid > 0 &&
1575 		    !sosendallatonce(so) && !nextrecord) {
1576 			if (so->so_error || so->so_rerror ||
1577 			    so->so_state & SS_CANTRCVMORE)
1578 				break;
1579 			/*
1580 			 * If we are peeking and the socket receive buffer is
1581 			 * full, stop since we can't get more data to peek at.
1582 			 */
1583 			if ((flags & MSG_PEEK) && sbspace(&so->so_rcv) <= 0)
1584 				break;
1585 			/*
1586 			 * If we've drained the socket buffer, tell the
1587 			 * protocol in case it needs to do something to
1588 			 * get it filled again.
1589 			 */
1590 			if ((pr->pr_flags & PR_WANTRCVD) && so->so_pcb)
1591 				(*pr->pr_usrreqs->pr_rcvd)(so, flags, l);
1592 			SBLASTRECORDCHK(&so->so_rcv, "soreceive sbwait 2");
1593 			SBLASTMBUFCHK(&so->so_rcv, "soreceive sbwait 2");
1594 			if (wakeup_state & SS_RESTARTSYS)
1595 				error = ERESTART;
1596 			else
1597 				error = sbwait(&so->so_rcv);
1598 			if (error != 0) {
1599 				sbunlock(&so->so_rcv);
1600 				sounlock(so);
1601 				splx(s);
1602 				return 0;
1603 			}
1604 			if ((m = so->so_rcv.sb_mb) != NULL)
1605 				nextrecord = m->m_nextpkt;
1606 			wakeup_state = so->so_state;
1607 		}
1608 	}
1609 
1610 	if (m && atomic) {
1611 		flags |= MSG_TRUNC;
1612 		if ((flags & MSG_PEEK) == 0)
1613 			(void) sbdroprecord(&so->so_rcv);
1614 	}
1615 	if ((flags & MSG_PEEK) == 0) {
1616 		if (m == NULL) {
1617 			/*
1618 			 * First part is an inline SB_EMPTY_FIXUP().  Second
1619 			 * part makes sure sb_lastrecord is up-to-date if
1620 			 * there is still data in the socket buffer.
1621 			 */
1622 			so->so_rcv.sb_mb = nextrecord;
1623 			if (so->so_rcv.sb_mb == NULL) {
1624 				so->so_rcv.sb_mbtail = NULL;
1625 				so->so_rcv.sb_lastrecord = NULL;
1626 			} else if (nextrecord->m_nextpkt == NULL)
1627 				so->so_rcv.sb_lastrecord = nextrecord;
1628 		}
1629 		SBLASTRECORDCHK(&so->so_rcv, "soreceive 4");
1630 		SBLASTMBUFCHK(&so->so_rcv, "soreceive 4");
1631 		if (pr->pr_flags & PR_WANTRCVD && so->so_pcb)
1632 			(*pr->pr_usrreqs->pr_rcvd)(so, flags, l);
1633 	}
1634 	if (orig_resid == uio->uio_resid && orig_resid &&
1635 	    (flags & MSG_EOR) == 0 && (so->so_state & SS_CANTRCVMORE) == 0) {
1636 		sbunlock(&so->so_rcv);
1637 		goto restart;
1638 	}
1639 
1640 	if (flagsp != NULL)
1641 		*flagsp |= flags;
1642 release:
1643 	sbunlock(&so->so_rcv);
1644 	sounlock(so);
1645 	splx(s);
1646 	return error;
1647 }
1648 
1649 int
1650 soshutdown(struct socket *so, int how)
1651 {
1652 	const struct protosw *pr;
1653 	int error;
1654 
1655 	KASSERT(solocked(so));
1656 
1657 	pr = so->so_proto;
1658 	if (!(how == SHUT_RD || how == SHUT_WR || how == SHUT_RDWR))
1659 		return EINVAL;
1660 
1661 	if (how == SHUT_RD || how == SHUT_RDWR) {
1662 		sorflush(so);
1663 		error = 0;
1664 	}
1665 	if (how == SHUT_WR || how == SHUT_RDWR)
1666 		error = (*pr->pr_usrreqs->pr_shutdown)(so);
1667 
1668 	return error;
1669 }
1670 
1671 void
1672 sorestart(struct socket *so)
1673 {
1674 	/*
1675 	 * An application has called close() on an fd on which another
1676 	 * of its threads has called a socket system call.
1677 	 * Mark this and wake everyone up, and code that would block again
1678 	 * instead returns ERESTART.
1679 	 * On system call re-entry the fd is validated and EBADF returned.
1680 	 * Any other fd will block again on the 2nd syscall.
1681 	 */
1682 	solock(so);
1683 	so->so_state |= SS_RESTARTSYS;
1684 	cv_broadcast(&so->so_cv);
1685 	cv_broadcast(&so->so_snd.sb_cv);
1686 	cv_broadcast(&so->so_rcv.sb_cv);
1687 	sounlock(so);
1688 }
1689 
1690 void
1691 sorflush(struct socket *so)
1692 {
1693 	struct sockbuf *sb, asb;
1694 	const struct protosw *pr;
1695 
1696 	KASSERT(solocked(so));
1697 
1698 	sb = &so->so_rcv;
1699 	pr = so->so_proto;
1700 	socantrcvmore(so);
1701 	sb->sb_flags |= SB_NOINTR;
1702 	(void )sblock(sb, M_WAITOK);
1703 	sbunlock(sb);
1704 	asb = *sb;
1705 	/*
1706 	 * Clear most of the sockbuf structure, but leave some of the
1707 	 * fields valid.
1708 	 */
1709 	memset(&sb->sb_startzero, 0,
1710 	    sizeof(*sb) - offsetof(struct sockbuf, sb_startzero));
1711 	if (pr->pr_flags & PR_RIGHTS && pr->pr_domain->dom_dispose) {
1712 		sounlock(so);
1713 		(*pr->pr_domain->dom_dispose)(asb.sb_mb);
1714 		solock(so);
1715 	}
1716 	sbrelease(&asb, so);
1717 }
1718 
1719 /*
1720  * internal set SOL_SOCKET options
1721  */
1722 static int
1723 sosetopt1(struct socket *so, const struct sockopt *sopt)
1724 {
1725 	int error, opt;
1726 	int optval = 0; /* XXX: gcc */
1727 	struct linger l;
1728 	struct timeval tv;
1729 
1730 	opt = sopt->sopt_name;
1731 
1732 	switch (opt) {
1733 
1734 	case SO_ACCEPTFILTER:
1735 		error = accept_filt_setopt(so, sopt);
1736 		KASSERT(solocked(so));
1737 		break;
1738 
1739 	case SO_LINGER:
1740 		error = sockopt_get(sopt, &l, sizeof(l));
1741 		solock(so);
1742 		if (error)
1743 			break;
1744 		if (l.l_linger < 0 || l.l_linger > USHRT_MAX ||
1745 		    l.l_linger > (INT_MAX / hz)) {
1746 			error = EDOM;
1747 			break;
1748 		}
1749 		so->so_linger = l.l_linger;
1750 		if (l.l_onoff)
1751 			so->so_options |= SO_LINGER;
1752 		else
1753 			so->so_options &= ~SO_LINGER;
1754 		break;
1755 
1756 	case SO_DEBUG:
1757 	case SO_KEEPALIVE:
1758 	case SO_DONTROUTE:
1759 	case SO_USELOOPBACK:
1760 	case SO_BROADCAST:
1761 	case SO_REUSEADDR:
1762 	case SO_REUSEPORT:
1763 	case SO_OOBINLINE:
1764 	case SO_TIMESTAMP:
1765 	case SO_NOSIGPIPE:
1766 	case SO_RERROR:
1767 		error = sockopt_getint(sopt, &optval);
1768 		solock(so);
1769 		if (error)
1770 			break;
1771 		if (optval)
1772 			so->so_options |= opt;
1773 		else
1774 			so->so_options &= ~opt;
1775 		break;
1776 
1777 	case SO_SNDBUF:
1778 	case SO_RCVBUF:
1779 	case SO_SNDLOWAT:
1780 	case SO_RCVLOWAT:
1781 		error = sockopt_getint(sopt, &optval);
1782 		solock(so);
1783 		if (error)
1784 			break;
1785 
1786 		/*
1787 		 * Values < 1 make no sense for any of these
1788 		 * options, so disallow them.
1789 		 */
1790 		if (optval < 1) {
1791 			error = EINVAL;
1792 			break;
1793 		}
1794 
1795 		switch (opt) {
1796 		case SO_SNDBUF:
1797 			if (sbreserve(&so->so_snd, (u_long)optval, so) == 0) {
1798 				error = ENOBUFS;
1799 				break;
1800 			}
1801 			so->so_snd.sb_flags &= ~SB_AUTOSIZE;
1802 			break;
1803 
1804 		case SO_RCVBUF:
1805 			if (sbreserve(&so->so_rcv, (u_long)optval, so) == 0) {
1806 				error = ENOBUFS;
1807 				break;
1808 			}
1809 			so->so_rcv.sb_flags &= ~SB_AUTOSIZE;
1810 			break;
1811 
1812 		/*
1813 		 * Make sure the low-water is never greater than
1814 		 * the high-water.
1815 		 */
1816 		case SO_SNDLOWAT:
1817 			if (optval > so->so_snd.sb_hiwat)
1818 				optval = so->so_snd.sb_hiwat;
1819 
1820 			so->so_snd.sb_lowat = optval;
1821 			break;
1822 
1823 		case SO_RCVLOWAT:
1824 			if (optval > so->so_rcv.sb_hiwat)
1825 				optval = so->so_rcv.sb_hiwat;
1826 
1827 			so->so_rcv.sb_lowat = optval;
1828 			break;
1829 		}
1830 		break;
1831 
1832 	case SO_SNDTIMEO:
1833 	case SO_RCVTIMEO:
1834 		solock(so);
1835 		error = sockopt_get(sopt, &tv, sizeof(tv));
1836 		if (error)
1837 			break;
1838 
1839 		if (tv.tv_sec < 0 || tv.tv_usec < 0 || tv.tv_usec >= 1000000) {
1840 			error = EDOM;
1841 			break;
1842 		}
1843 		if (tv.tv_sec > (INT_MAX - tv.tv_usec / tick) / hz) {
1844 			error = EDOM;
1845 			break;
1846 		}
1847 
1848 		optval = tv.tv_sec * hz + tv.tv_usec / tick;
1849 		if (optval == 0 && tv.tv_usec != 0)
1850 			optval = 1;
1851 
1852 		switch (opt) {
1853 		case SO_SNDTIMEO:
1854 			so->so_snd.sb_timeo = optval;
1855 			break;
1856 		case SO_RCVTIMEO:
1857 			so->so_rcv.sb_timeo = optval;
1858 			break;
1859 		}
1860 		break;
1861 
1862 	default:
1863 		MODULE_HOOK_CALL(uipc_socket_50_setopt1_hook,
1864 		    (opt, so, sopt), enosys(), error);
1865 		if (error == ENOSYS || error == EPASSTHROUGH) {
1866 			solock(so);
1867 			error = ENOPROTOOPT;
1868 		}
1869 		break;
1870 	}
1871 	KASSERT(solocked(so));
1872 	return error;
1873 }
1874 
1875 int
1876 sosetopt(struct socket *so, struct sockopt *sopt)
1877 {
1878 	int error, prerr;
1879 
1880 	if (sopt->sopt_level == SOL_SOCKET) {
1881 		error = sosetopt1(so, sopt);
1882 		KASSERT(solocked(so));
1883 	} else {
1884 		error = ENOPROTOOPT;
1885 		solock(so);
1886 	}
1887 
1888 	if ((error == 0 || error == ENOPROTOOPT) &&
1889 	    so->so_proto != NULL && so->so_proto->pr_ctloutput != NULL) {
1890 		/* give the protocol stack a shot */
1891 		prerr = (*so->so_proto->pr_ctloutput)(PRCO_SETOPT, so, sopt);
1892 		if (prerr == 0)
1893 			error = 0;
1894 		else if (prerr != ENOPROTOOPT)
1895 			error = prerr;
1896 	}
1897 	sounlock(so);
1898 	return error;
1899 }
1900 
1901 /*
1902  * so_setsockopt() is a wrapper providing a sockopt structure for sosetopt()
1903  */
1904 int
1905 so_setsockopt(struct lwp *l, struct socket *so, int level, int name,
1906     const void *val, size_t valsize)
1907 {
1908 	struct sockopt sopt;
1909 	int error;
1910 
1911 	KASSERT(valsize == 0 || val != NULL);
1912 
1913 	sockopt_init(&sopt, level, name, valsize);
1914 	sockopt_set(&sopt, val, valsize);
1915 
1916 	error = sosetopt(so, &sopt);
1917 
1918 	sockopt_destroy(&sopt);
1919 
1920 	return error;
1921 }
1922 
1923 /*
1924  * internal get SOL_SOCKET options
1925  */
1926 static int
1927 sogetopt1(struct socket *so, struct sockopt *sopt)
1928 {
1929 	int error, optval, opt;
1930 	struct linger l;
1931 	struct timeval tv;
1932 
1933 	switch ((opt = sopt->sopt_name)) {
1934 
1935 	case SO_ACCEPTFILTER:
1936 		error = accept_filt_getopt(so, sopt);
1937 		break;
1938 
1939 	case SO_LINGER:
1940 		l.l_onoff = (so->so_options & SO_LINGER) ? 1 : 0;
1941 		l.l_linger = so->so_linger;
1942 
1943 		error = sockopt_set(sopt, &l, sizeof(l));
1944 		break;
1945 
1946 	case SO_USELOOPBACK:
1947 	case SO_DONTROUTE:
1948 	case SO_DEBUG:
1949 	case SO_KEEPALIVE:
1950 	case SO_REUSEADDR:
1951 	case SO_REUSEPORT:
1952 	case SO_BROADCAST:
1953 	case SO_OOBINLINE:
1954 	case SO_TIMESTAMP:
1955 	case SO_NOSIGPIPE:
1956 	case SO_RERROR:
1957 	case SO_ACCEPTCONN:
1958 		error = sockopt_setint(sopt, (so->so_options & opt) ? 1 : 0);
1959 		break;
1960 
1961 	case SO_TYPE:
1962 		error = sockopt_setint(sopt, so->so_type);
1963 		break;
1964 
1965 	case SO_ERROR:
1966 		if (so->so_error == 0) {
1967 			so->so_error = so->so_rerror;
1968 			so->so_rerror = 0;
1969 		}
1970 		error = sockopt_setint(sopt, so->so_error);
1971 		so->so_error = 0;
1972 		break;
1973 
1974 	case SO_SNDBUF:
1975 		error = sockopt_setint(sopt, so->so_snd.sb_hiwat);
1976 		break;
1977 
1978 	case SO_RCVBUF:
1979 		error = sockopt_setint(sopt, so->so_rcv.sb_hiwat);
1980 		break;
1981 
1982 	case SO_SNDLOWAT:
1983 		error = sockopt_setint(sopt, so->so_snd.sb_lowat);
1984 		break;
1985 
1986 	case SO_RCVLOWAT:
1987 		error = sockopt_setint(sopt, so->so_rcv.sb_lowat);
1988 		break;
1989 
1990 	case SO_SNDTIMEO:
1991 	case SO_RCVTIMEO:
1992 		optval = (opt == SO_SNDTIMEO ?
1993 		     so->so_snd.sb_timeo : so->so_rcv.sb_timeo);
1994 
1995 		memset(&tv, 0, sizeof(tv));
1996 		tv.tv_sec = optval / hz;
1997 		tv.tv_usec = (optval % hz) * tick;
1998 
1999 		error = sockopt_set(sopt, &tv, sizeof(tv));
2000 		break;
2001 
2002 	case SO_OVERFLOWED:
2003 		error = sockopt_setint(sopt, so->so_rcv.sb_overflowed);
2004 		break;
2005 
2006 	default:
2007 		MODULE_HOOK_CALL(uipc_socket_50_getopt1_hook,
2008 		    (opt, so, sopt), enosys(), error);
2009 		if (error)
2010 			error = ENOPROTOOPT;
2011 		break;
2012 	}
2013 
2014 	return error;
2015 }
2016 
2017 int
2018 sogetopt(struct socket *so, struct sockopt *sopt)
2019 {
2020 	int error;
2021 
2022 	solock(so);
2023 	if (sopt->sopt_level != SOL_SOCKET) {
2024 		if (so->so_proto && so->so_proto->pr_ctloutput) {
2025 			error = ((*so->so_proto->pr_ctloutput)
2026 			    (PRCO_GETOPT, so, sopt));
2027 		} else
2028 			error = (ENOPROTOOPT);
2029 	} else {
2030 		error = sogetopt1(so, sopt);
2031 	}
2032 	sounlock(so);
2033 	return error;
2034 }
2035 
2036 /*
2037  * alloc sockopt data buffer buffer
2038  *	- will be released at destroy
2039  */
2040 static int
2041 sockopt_alloc(struct sockopt *sopt, size_t len, km_flag_t kmflag)
2042 {
2043 	void *data;
2044 
2045 	KASSERT(sopt->sopt_size == 0);
2046 
2047 	if (len > sizeof(sopt->sopt_buf)) {
2048 		data = kmem_zalloc(len, kmflag);
2049 		if (data == NULL)
2050 			return ENOMEM;
2051 		sopt->sopt_data = data;
2052 	} else
2053 		sopt->sopt_data = sopt->sopt_buf;
2054 
2055 	sopt->sopt_size = len;
2056 	return 0;
2057 }
2058 
2059 /*
2060  * initialise sockopt storage
2061  *	- MAY sleep during allocation
2062  */
2063 void
2064 sockopt_init(struct sockopt *sopt, int level, int name, size_t size)
2065 {
2066 
2067 	memset(sopt, 0, sizeof(*sopt));
2068 
2069 	sopt->sopt_level = level;
2070 	sopt->sopt_name = name;
2071 	(void)sockopt_alloc(sopt, size, KM_SLEEP);
2072 }
2073 
2074 /*
2075  * destroy sockopt storage
2076  *	- will release any held memory references
2077  */
2078 void
2079 sockopt_destroy(struct sockopt *sopt)
2080 {
2081 
2082 	if (sopt->sopt_data != sopt->sopt_buf)
2083 		kmem_free(sopt->sopt_data, sopt->sopt_size);
2084 
2085 	memset(sopt, 0, sizeof(*sopt));
2086 }
2087 
2088 /*
2089  * set sockopt value
2090  *	- value is copied into sockopt
2091  *	- memory is allocated when necessary, will not sleep
2092  */
2093 int
2094 sockopt_set(struct sockopt *sopt, const void *buf, size_t len)
2095 {
2096 	int error;
2097 
2098 	if (sopt->sopt_size == 0) {
2099 		error = sockopt_alloc(sopt, len, KM_NOSLEEP);
2100 		if (error)
2101 			return error;
2102 	}
2103 
2104 	sopt->sopt_retsize = MIN(sopt->sopt_size, len);
2105 	if (sopt->sopt_retsize > 0) {
2106 		memcpy(sopt->sopt_data, buf, sopt->sopt_retsize);
2107 	}
2108 
2109 	return 0;
2110 }
2111 
2112 /*
2113  * common case of set sockopt integer value
2114  */
2115 int
2116 sockopt_setint(struct sockopt *sopt, int val)
2117 {
2118 
2119 	return sockopt_set(sopt, &val, sizeof(int));
2120 }
2121 
2122 /*
2123  * get sockopt value
2124  *	- correct size must be given
2125  */
2126 int
2127 sockopt_get(const struct sockopt *sopt, void *buf, size_t len)
2128 {
2129 
2130 	if (sopt->sopt_size != len)
2131 		return EINVAL;
2132 
2133 	memcpy(buf, sopt->sopt_data, len);
2134 	return 0;
2135 }
2136 
2137 /*
2138  * common case of get sockopt integer value
2139  */
2140 int
2141 sockopt_getint(const struct sockopt *sopt, int *valp)
2142 {
2143 
2144 	return sockopt_get(sopt, valp, sizeof(int));
2145 }
2146 
2147 /*
2148  * set sockopt value from mbuf
2149  *	- ONLY for legacy code
2150  *	- mbuf is released by sockopt
2151  *	- will not sleep
2152  */
2153 int
2154 sockopt_setmbuf(struct sockopt *sopt, struct mbuf *m)
2155 {
2156 	size_t len;
2157 	int error;
2158 
2159 	len = m_length(m);
2160 
2161 	if (sopt->sopt_size == 0) {
2162 		error = sockopt_alloc(sopt, len, KM_NOSLEEP);
2163 		if (error)
2164 			return error;
2165 	}
2166 
2167 	sopt->sopt_retsize = MIN(sopt->sopt_size, len);
2168 	m_copydata(m, 0, sopt->sopt_retsize, sopt->sopt_data);
2169 	m_freem(m);
2170 
2171 	return 0;
2172 }
2173 
2174 /*
2175  * get sockopt value into mbuf
2176  *	- ONLY for legacy code
2177  *	- mbuf to be released by the caller
2178  *	- will not sleep
2179  */
2180 struct mbuf *
2181 sockopt_getmbuf(const struct sockopt *sopt)
2182 {
2183 	struct mbuf *m;
2184 
2185 	if (sopt->sopt_size > MCLBYTES)
2186 		return NULL;
2187 
2188 	m = m_get(M_DONTWAIT, MT_SOOPTS);
2189 	if (m == NULL)
2190 		return NULL;
2191 
2192 	if (sopt->sopt_size > MLEN) {
2193 		MCLGET(m, M_DONTWAIT);
2194 		if ((m->m_flags & M_EXT) == 0) {
2195 			m_free(m);
2196 			return NULL;
2197 		}
2198 	}
2199 
2200 	memcpy(mtod(m, void *), sopt->sopt_data, sopt->sopt_size);
2201 	m->m_len = sopt->sopt_size;
2202 
2203 	return m;
2204 }
2205 
2206 void
2207 sohasoutofband(struct socket *so)
2208 {
2209 
2210 	fownsignal(so->so_pgid, SIGURG, POLL_PRI, POLLPRI|POLLRDBAND, so);
2211 	selnotify(&so->so_rcv.sb_sel, POLLPRI | POLLRDBAND, NOTE_SUBMIT);
2212 }
2213 
2214 static void
2215 filt_sordetach(struct knote *kn)
2216 {
2217 	struct socket *so;
2218 
2219 	so = ((file_t *)kn->kn_obj)->f_socket;
2220 	solock(so);
2221 	SLIST_REMOVE(&so->so_rcv.sb_sel.sel_klist, kn, knote, kn_selnext);
2222 	if (SLIST_EMPTY(&so->so_rcv.sb_sel.sel_klist))
2223 		so->so_rcv.sb_flags &= ~SB_KNOTE;
2224 	sounlock(so);
2225 }
2226 
2227 /*ARGSUSED*/
2228 static int
2229 filt_soread(struct knote *kn, long hint)
2230 {
2231 	struct socket *so;
2232 	int rv;
2233 
2234 	so = ((file_t *)kn->kn_obj)->f_socket;
2235 	if (hint != NOTE_SUBMIT)
2236 		solock(so);
2237 	kn->kn_data = so->so_rcv.sb_cc;
2238 	if (so->so_state & SS_CANTRCVMORE) {
2239 		kn->kn_flags |= EV_EOF;
2240 		kn->kn_fflags = so->so_error;
2241 		rv = 1;
2242 	} else if (so->so_error || so->so_rerror)
2243 		rv = 1;
2244 	else if (kn->kn_sfflags & NOTE_LOWAT)
2245 		rv = (kn->kn_data >= kn->kn_sdata);
2246 	else
2247 		rv = (kn->kn_data >= so->so_rcv.sb_lowat);
2248 	if (hint != NOTE_SUBMIT)
2249 		sounlock(so);
2250 	return rv;
2251 }
2252 
2253 static void
2254 filt_sowdetach(struct knote *kn)
2255 {
2256 	struct socket *so;
2257 
2258 	so = ((file_t *)kn->kn_obj)->f_socket;
2259 	solock(so);
2260 	SLIST_REMOVE(&so->so_snd.sb_sel.sel_klist, kn, knote, kn_selnext);
2261 	if (SLIST_EMPTY(&so->so_snd.sb_sel.sel_klist))
2262 		so->so_snd.sb_flags &= ~SB_KNOTE;
2263 	sounlock(so);
2264 }
2265 
2266 /*ARGSUSED*/
2267 static int
2268 filt_sowrite(struct knote *kn, long hint)
2269 {
2270 	struct socket *so;
2271 	int rv;
2272 
2273 	so = ((file_t *)kn->kn_obj)->f_socket;
2274 	if (hint != NOTE_SUBMIT)
2275 		solock(so);
2276 	kn->kn_data = sbspace(&so->so_snd);
2277 	if (so->so_state & SS_CANTSENDMORE) {
2278 		kn->kn_flags |= EV_EOF;
2279 		kn->kn_fflags = so->so_error;
2280 		rv = 1;
2281 	} else if (so->so_error)
2282 		rv = 1;
2283 	else if (((so->so_state & SS_ISCONNECTED) == 0) &&
2284 	    (so->so_proto->pr_flags & PR_CONNREQUIRED))
2285 		rv = 0;
2286 	else if (kn->kn_sfflags & NOTE_LOWAT)
2287 		rv = (kn->kn_data >= kn->kn_sdata);
2288 	else
2289 		rv = (kn->kn_data >= so->so_snd.sb_lowat);
2290 	if (hint != NOTE_SUBMIT)
2291 		sounlock(so);
2292 	return rv;
2293 }
2294 
2295 /*ARGSUSED*/
2296 static int
2297 filt_solisten(struct knote *kn, long hint)
2298 {
2299 	struct socket *so;
2300 	int rv;
2301 
2302 	so = ((file_t *)kn->kn_obj)->f_socket;
2303 
2304 	/*
2305 	 * Set kn_data to number of incoming connections, not
2306 	 * counting partial (incomplete) connections.
2307 	 */
2308 	if (hint != NOTE_SUBMIT)
2309 		solock(so);
2310 	kn->kn_data = so->so_qlen;
2311 	rv = (kn->kn_data > 0);
2312 	if (hint != NOTE_SUBMIT)
2313 		sounlock(so);
2314 	return rv;
2315 }
2316 
2317 static const struct filterops solisten_filtops = {
2318 	.f_isfd = 1,
2319 	.f_attach = NULL,
2320 	.f_detach = filt_sordetach,
2321 	.f_event = filt_solisten,
2322 };
2323 
2324 static const struct filterops soread_filtops = {
2325 	.f_isfd = 1,
2326 	.f_attach = NULL,
2327 	.f_detach = filt_sordetach,
2328 	.f_event = filt_soread,
2329 };
2330 
2331 static const struct filterops sowrite_filtops = {
2332 	.f_isfd = 1,
2333 	.f_attach = NULL,
2334 	.f_detach = filt_sowdetach,
2335 	.f_event = filt_sowrite,
2336 };
2337 
2338 int
2339 soo_kqfilter(struct file *fp, struct knote *kn)
2340 {
2341 	struct socket *so;
2342 	struct sockbuf *sb;
2343 
2344 	so = ((file_t *)kn->kn_obj)->f_socket;
2345 	solock(so);
2346 	switch (kn->kn_filter) {
2347 	case EVFILT_READ:
2348 		if (so->so_options & SO_ACCEPTCONN)
2349 			kn->kn_fop = &solisten_filtops;
2350 		else
2351 			kn->kn_fop = &soread_filtops;
2352 		sb = &so->so_rcv;
2353 		break;
2354 	case EVFILT_WRITE:
2355 		kn->kn_fop = &sowrite_filtops;
2356 		sb = &so->so_snd;
2357 		break;
2358 	default:
2359 		sounlock(so);
2360 		return EINVAL;
2361 	}
2362 	SLIST_INSERT_HEAD(&sb->sb_sel.sel_klist, kn, kn_selnext);
2363 	sb->sb_flags |= SB_KNOTE;
2364 	sounlock(so);
2365 	return 0;
2366 }
2367 
2368 static int
2369 sodopoll(struct socket *so, int events)
2370 {
2371 	int revents;
2372 
2373 	revents = 0;
2374 
2375 	if (events & (POLLIN | POLLRDNORM))
2376 		if (soreadable(so))
2377 			revents |= events & (POLLIN | POLLRDNORM);
2378 
2379 	if (events & (POLLOUT | POLLWRNORM))
2380 		if (sowritable(so))
2381 			revents |= events & (POLLOUT | POLLWRNORM);
2382 
2383 	if (events & (POLLPRI | POLLRDBAND))
2384 		if (so->so_oobmark || (so->so_state & SS_RCVATMARK))
2385 			revents |= events & (POLLPRI | POLLRDBAND);
2386 
2387 	return revents;
2388 }
2389 
2390 int
2391 sopoll(struct socket *so, int events)
2392 {
2393 	int revents = 0;
2394 
2395 #ifndef DIAGNOSTIC
2396 	/*
2397 	 * Do a quick, unlocked check in expectation that the socket
2398 	 * will be ready for I/O.  Don't do this check if DIAGNOSTIC,
2399 	 * as the solocked() assertions will fail.
2400 	 */
2401 	if ((revents = sodopoll(so, events)) != 0)
2402 		return revents;
2403 #endif
2404 
2405 	solock(so);
2406 	if ((revents = sodopoll(so, events)) == 0) {
2407 		if (events & (POLLIN | POLLPRI | POLLRDNORM | POLLRDBAND)) {
2408 			selrecord(curlwp, &so->so_rcv.sb_sel);
2409 			so->so_rcv.sb_flags |= SB_NOTIFY;
2410 		}
2411 
2412 		if (events & (POLLOUT | POLLWRNORM)) {
2413 			selrecord(curlwp, &so->so_snd.sb_sel);
2414 			so->so_snd.sb_flags |= SB_NOTIFY;
2415 		}
2416 	}
2417 	sounlock(so);
2418 
2419 	return revents;
2420 }
2421 
2422 struct mbuf **
2423 sbsavetimestamp(int opt, struct mbuf **mp)
2424 {
2425 	struct timeval tv;
2426 	int error;
2427 
2428 	microtime(&tv);
2429 
2430 	MODULE_HOOK_CALL(uipc_socket_50_sbts_hook, (opt, &mp), enosys(), error);
2431 	if (error == 0)
2432 		return mp;
2433 
2434 	if (opt & SO_TIMESTAMP) {
2435 		*mp = sbcreatecontrol(&tv, sizeof(tv),
2436 		    SCM_TIMESTAMP, SOL_SOCKET);
2437 		if (*mp)
2438 			mp = &(*mp)->m_next;
2439 	}
2440 	return mp;
2441 }
2442 
2443 
2444 #include <sys/sysctl.h>
2445 
2446 static int sysctl_kern_somaxkva(SYSCTLFN_PROTO);
2447 static int sysctl_kern_sbmax(SYSCTLFN_PROTO);
2448 
2449 /*
2450  * sysctl helper routine for kern.somaxkva.  ensures that the given
2451  * value is not too small.
2452  * (XXX should we maybe make sure it's not too large as well?)
2453  */
2454 static int
2455 sysctl_kern_somaxkva(SYSCTLFN_ARGS)
2456 {
2457 	int error, new_somaxkva;
2458 	struct sysctlnode node;
2459 
2460 	new_somaxkva = somaxkva;
2461 	node = *rnode;
2462 	node.sysctl_data = &new_somaxkva;
2463 	error = sysctl_lookup(SYSCTLFN_CALL(&node));
2464 	if (error || newp == NULL)
2465 		return error;
2466 
2467 	if (new_somaxkva < (16 * 1024 * 1024)) /* sanity */
2468 		return EINVAL;
2469 
2470 	mutex_enter(&so_pendfree_lock);
2471 	somaxkva = new_somaxkva;
2472 	cv_broadcast(&socurkva_cv);
2473 	mutex_exit(&so_pendfree_lock);
2474 
2475 	return error;
2476 }
2477 
2478 /*
2479  * sysctl helper routine for kern.sbmax. Basically just ensures that
2480  * any new value is not too small.
2481  */
2482 static int
2483 sysctl_kern_sbmax(SYSCTLFN_ARGS)
2484 {
2485 	int error, new_sbmax;
2486 	struct sysctlnode node;
2487 
2488 	new_sbmax = sb_max;
2489 	node = *rnode;
2490 	node.sysctl_data = &new_sbmax;
2491 	error = sysctl_lookup(SYSCTLFN_CALL(&node));
2492 	if (error || newp == NULL)
2493 		return error;
2494 
2495 	KERNEL_LOCK(1, NULL);
2496 	error = sb_max_set(new_sbmax);
2497 	KERNEL_UNLOCK_ONE(NULL);
2498 
2499 	return error;
2500 }
2501 
2502 /*
2503  * sysctl helper routine for kern.sooptions. Ensures that only allowed
2504  * options can be set.
2505  */
2506 static int
2507 sysctl_kern_sooptions(SYSCTLFN_ARGS)
2508 {
2509 	int error, new_options;
2510 	struct sysctlnode node;
2511 
2512 	new_options = sooptions;
2513 	node = *rnode;
2514 	node.sysctl_data = &new_options;
2515 	error = sysctl_lookup(SYSCTLFN_CALL(&node));
2516 	if (error || newp == NULL)
2517 		return error;
2518 
2519 	if (new_options & ~SO_DEFOPTS)
2520 		return EINVAL;
2521 
2522 	sooptions = new_options;
2523 
2524 	return 0;
2525 }
2526 
2527 static void
2528 sysctl_kern_socket_setup(void)
2529 {
2530 
2531 	KASSERT(socket_sysctllog == NULL);
2532 
2533 	sysctl_createv(&socket_sysctllog, 0, NULL, NULL,
2534 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
2535 		       CTLTYPE_INT, "somaxkva",
2536 		       SYSCTL_DESCR("Maximum amount of kernel memory to be "
2537 		                    "used for socket buffers"),
2538 		       sysctl_kern_somaxkva, 0, NULL, 0,
2539 		       CTL_KERN, KERN_SOMAXKVA, CTL_EOL);
2540 
2541 	sysctl_createv(&socket_sysctllog, 0, NULL, NULL,
2542 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
2543 		       CTLTYPE_INT, "sbmax",
2544 		       SYSCTL_DESCR("Maximum socket buffer size"),
2545 		       sysctl_kern_sbmax, 0, NULL, 0,
2546 		       CTL_KERN, KERN_SBMAX, CTL_EOL);
2547 
2548 	sysctl_createv(&socket_sysctllog, 0, NULL, NULL,
2549 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
2550 		       CTLTYPE_INT, "sooptions",
2551 		       SYSCTL_DESCR("Default socket options"),
2552 		       sysctl_kern_sooptions, 0, NULL, 0,
2553 		       CTL_KERN, CTL_CREATE, CTL_EOL);
2554 }
2555