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