xref: /netbsd-src/sys/kern/uipc_socket.c (revision 404ee5b9334f618040b6cdef96a0ff35a6fc4636)
1 /*	$NetBSD: uipc_socket.c,v 1.285 2019/10/14 16:27:03 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.285 2019/10/14 16:27:03 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)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 bad:
1184 		if (m != NULL)
1185 			m_freem(m);
1186 		return error;
1187 	}
1188 	if (mp != NULL)
1189 		*mp = NULL;
1190 
1191 	/*
1192 	 * solock() provides atomicity of access.  splsoftnet() prevents
1193 	 * protocol processing soft interrupts from interrupting us and
1194 	 * blocking (expensive).
1195 	 */
1196 	s = splsoftnet();
1197 	solock(so);
1198 restart:
1199 	if ((error = sblock(&so->so_rcv, SBLOCKWAIT(flags))) != 0) {
1200 		sounlock(so);
1201 		splx(s);
1202 		return error;
1203 	}
1204 	m = so->so_rcv.sb_mb;
1205 
1206 	/*
1207 	 * If we have less data than requested, block awaiting more
1208 	 * (subject to any timeout) if:
1209 	 *   1. the current count is less than the low water mark,
1210 	 *   2. MSG_WAITALL is set, and it is possible to do the entire
1211 	 *	receive operation at once if we block (resid <= hiwat), or
1212 	 *   3. MSG_DONTWAIT is not set.
1213 	 * If MSG_WAITALL is set but resid is larger than the receive buffer,
1214 	 * we have to do the receive in sections, and thus risk returning
1215 	 * a short count if a timeout or signal occurs after we start.
1216 	 */
1217 	if (m == NULL ||
1218 	    ((flags & MSG_DONTWAIT) == 0 &&
1219 	     so->so_rcv.sb_cc < uio->uio_resid &&
1220 	     (so->so_rcv.sb_cc < so->so_rcv.sb_lowat ||
1221 	      ((flags & MSG_WAITALL) &&
1222 	       uio->uio_resid <= so->so_rcv.sb_hiwat)) &&
1223 	     m->m_nextpkt == NULL && !atomic)) {
1224 #ifdef DIAGNOSTIC
1225 		if (m == NULL && so->so_rcv.sb_cc)
1226 			panic("receive 1");
1227 #endif
1228 		if (so->so_error || so->so_rerror) {
1229 			u_short *e;
1230 			if (m != NULL)
1231 				goto dontblock;
1232 			e = so->so_error ? &so->so_error : &so->so_rerror;
1233 			error = *e;
1234 			if ((flags & MSG_PEEK) == 0)
1235 				*e = 0;
1236 			goto release;
1237 		}
1238 		if (so->so_state & SS_CANTRCVMORE) {
1239 			if (m != NULL)
1240 				goto dontblock;
1241 			else
1242 				goto release;
1243 		}
1244 		for (; m != NULL; m = m->m_next)
1245 			if (m->m_type == MT_OOBDATA  || (m->m_flags & M_EOR)) {
1246 				m = so->so_rcv.sb_mb;
1247 				goto dontblock;
1248 			}
1249 		if ((so->so_state & (SS_ISCONNECTED|SS_ISCONNECTING)) == 0 &&
1250 		    (so->so_proto->pr_flags & PR_CONNREQUIRED)) {
1251 			error = ENOTCONN;
1252 			goto release;
1253 		}
1254 		if (uio->uio_resid == 0)
1255 			goto release;
1256 		if ((so->so_state & SS_NBIO) ||
1257 		    (flags & (MSG_DONTWAIT|MSG_NBIO))) {
1258 			error = EWOULDBLOCK;
1259 			goto release;
1260 		}
1261 		SBLASTRECORDCHK(&so->so_rcv, "soreceive sbwait 1");
1262 		SBLASTMBUFCHK(&so->so_rcv, "soreceive sbwait 1");
1263 		sbunlock(&so->so_rcv);
1264 		if (wakeup_state & SS_RESTARTSYS)
1265 			error = ERESTART;
1266 		else
1267 			error = sbwait(&so->so_rcv);
1268 		if (error != 0) {
1269 			sounlock(so);
1270 			splx(s);
1271 			return error;
1272 		}
1273 		wakeup_state = so->so_state;
1274 		goto restart;
1275 	}
1276 
1277 dontblock:
1278 	/*
1279 	 * On entry here, m points to the first record of the socket buffer.
1280 	 * From this point onward, we maintain 'nextrecord' as a cache of the
1281 	 * pointer to the next record in the socket buffer.  We must keep the
1282 	 * various socket buffer pointers and local stack versions of the
1283 	 * pointers in sync, pushing out modifications before dropping the
1284 	 * socket lock, and re-reading them when picking it up.
1285 	 *
1286 	 * Otherwise, we will race with the network stack appending new data
1287 	 * or records onto the socket buffer by using inconsistent/stale
1288 	 * versions of the field, possibly resulting in socket buffer
1289 	 * corruption.
1290 	 *
1291 	 * By holding the high-level sblock(), we prevent simultaneous
1292 	 * readers from pulling off the front of the socket buffer.
1293 	 */
1294 	if (l != NULL)
1295 		l->l_ru.ru_msgrcv++;
1296 	KASSERT(m == so->so_rcv.sb_mb);
1297 	SBLASTRECORDCHK(&so->so_rcv, "soreceive 1");
1298 	SBLASTMBUFCHK(&so->so_rcv, "soreceive 1");
1299 	nextrecord = m->m_nextpkt;
1300 
1301 	if (pr->pr_flags & PR_ADDR) {
1302 		KASSERT(m->m_type == MT_SONAME);
1303 		orig_resid = 0;
1304 		if (flags & MSG_PEEK) {
1305 			if (paddr)
1306 				*paddr = m_copym(m, 0, m->m_len, M_DONTWAIT);
1307 			m = m->m_next;
1308 		} else {
1309 			sbfree(&so->so_rcv, m);
1310 			mbuf_removed = 1;
1311 			if (paddr != NULL) {
1312 				*paddr = m;
1313 				so->so_rcv.sb_mb = m->m_next;
1314 				m->m_next = NULL;
1315 				m = so->so_rcv.sb_mb;
1316 			} else {
1317 				m = so->so_rcv.sb_mb = m_free(m);
1318 			}
1319 			sbsync(&so->so_rcv, nextrecord);
1320 		}
1321 	}
1322 
1323 	if (pr->pr_flags & PR_ADDR_OPT) {
1324 		/*
1325 		 * For SCTP we may be getting a whole message OR a partial
1326 		 * delivery.
1327 		 */
1328 		if (m->m_type == MT_SONAME) {
1329 			orig_resid = 0;
1330 			if (flags & MSG_PEEK) {
1331 				if (paddr)
1332 					*paddr = m_copym(m, 0, m->m_len, M_DONTWAIT);
1333 				m = m->m_next;
1334 			} else {
1335 				sbfree(&so->so_rcv, m);
1336 				/* XXX XXX XXX: should set mbuf_removed? */
1337 				if (paddr) {
1338 					*paddr = m;
1339 					so->so_rcv.sb_mb = m->m_next;
1340 					m->m_next = 0;
1341 					m = so->so_rcv.sb_mb;
1342 				} else {
1343 					m = so->so_rcv.sb_mb = m_free(m);
1344 				}
1345 				/* XXX XXX XXX: isn't there an sbsync()
1346 				 * missing here? */
1347 			}
1348 		}
1349 	}
1350 
1351 	/*
1352 	 * Process one or more MT_CONTROL mbufs present before any data mbufs
1353 	 * in the first mbuf chain on the socket buffer.  If MSG_PEEK, we
1354 	 * just copy the data; if !MSG_PEEK, we call into the protocol to
1355 	 * perform externalization (or freeing if controlp == NULL).
1356 	 */
1357 	if (__predict_false(m != NULL && m->m_type == MT_CONTROL)) {
1358 		struct mbuf *cm = NULL, *cmn;
1359 		struct mbuf **cme = &cm;
1360 
1361 		do {
1362 			if (flags & MSG_PEEK) {
1363 				if (controlp != NULL) {
1364 					*controlp = m_copym(m, 0, m->m_len, M_DONTWAIT);
1365 					controlp = &(*controlp)->m_next;
1366 				}
1367 				m = m->m_next;
1368 			} else {
1369 				sbfree(&so->so_rcv, m);
1370 				so->so_rcv.sb_mb = m->m_next;
1371 				m->m_next = NULL;
1372 				*cme = m;
1373 				cme = &(*cme)->m_next;
1374 				m = so->so_rcv.sb_mb;
1375 			}
1376 		} while (m != NULL && m->m_type == MT_CONTROL);
1377 		if ((flags & MSG_PEEK) == 0)
1378 			sbsync(&so->so_rcv, nextrecord);
1379 
1380 		for (; cm != NULL; cm = cmn) {
1381 			cmn = cm->m_next;
1382 			cm->m_next = NULL;
1383 			type = mtod(cm, struct cmsghdr *)->cmsg_type;
1384 			if (controlp != NULL) {
1385 				if (dom->dom_externalize != NULL &&
1386 				    type == SCM_RIGHTS) {
1387 					sounlock(so);
1388 					splx(s);
1389 					error = (*dom->dom_externalize)(cm, l,
1390 					    (flags & MSG_CMSG_CLOEXEC) ?
1391 					    O_CLOEXEC : 0);
1392 					s = splsoftnet();
1393 					solock(so);
1394 				}
1395 				*controlp = cm;
1396 				while (*controlp != NULL)
1397 					controlp = &(*controlp)->m_next;
1398 			} else {
1399 				/*
1400 				 * Dispose of any SCM_RIGHTS message that went
1401 				 * through the read path rather than recv.
1402 				 */
1403 				if (dom->dom_dispose != NULL &&
1404 				    type == SCM_RIGHTS) {
1405 					sounlock(so);
1406 					(*dom->dom_dispose)(cm);
1407 					solock(so);
1408 				}
1409 				m_freem(cm);
1410 			}
1411 		}
1412 		if (m != NULL)
1413 			nextrecord = so->so_rcv.sb_mb->m_nextpkt;
1414 		else
1415 			nextrecord = so->so_rcv.sb_mb;
1416 		orig_resid = 0;
1417 	}
1418 
1419 	/* If m is non-NULL, we have some data to read. */
1420 	if (__predict_true(m != NULL)) {
1421 		type = m->m_type;
1422 		if (type == MT_OOBDATA)
1423 			flags |= MSG_OOB;
1424 	}
1425 	SBLASTRECORDCHK(&so->so_rcv, "soreceive 2");
1426 	SBLASTMBUFCHK(&so->so_rcv, "soreceive 2");
1427 
1428 	moff = 0;
1429 	offset = 0;
1430 	while (m != NULL && uio->uio_resid > 0 && error == 0) {
1431 		/*
1432 		 * If the type of mbuf has changed, end the receive
1433 		 * operation and do a short read.
1434 		 */
1435 		if (m->m_type == MT_OOBDATA) {
1436 			if (type != MT_OOBDATA)
1437 				break;
1438 		} else if (type == MT_OOBDATA) {
1439 			break;
1440 		} else if (m->m_type == MT_CONTROL) {
1441 			break;
1442 		}
1443 #ifdef DIAGNOSTIC
1444 		else if (m->m_type != MT_DATA && m->m_type != MT_HEADER) {
1445 			panic("%s: m_type=%d", __func__, m->m_type);
1446 		}
1447 #endif
1448 
1449 		so->so_state &= ~SS_RCVATMARK;
1450 		wakeup_state = 0;
1451 		len = uio->uio_resid;
1452 		if (so->so_oobmark && len > so->so_oobmark - offset)
1453 			len = so->so_oobmark - offset;
1454 		if (len > m->m_len - moff)
1455 			len = m->m_len - moff;
1456 
1457 		/*
1458 		 * If mp is set, just pass back the mbufs.
1459 		 * Otherwise copy them out via the uio, then free.
1460 		 * Sockbuf must be consistent here (points to current mbuf,
1461 		 * it points to next record) when we drop priority;
1462 		 * we must note any additions to the sockbuf when we
1463 		 * block interrupts again.
1464 		 */
1465 		if (mp == NULL) {
1466 			SBLASTRECORDCHK(&so->so_rcv, "soreceive uiomove");
1467 			SBLASTMBUFCHK(&so->so_rcv, "soreceive uiomove");
1468 			sounlock(so);
1469 			splx(s);
1470 			error = uiomove(mtod(m, char *) + moff, len, uio);
1471 			s = splsoftnet();
1472 			solock(so);
1473 			if (error != 0) {
1474 				/*
1475 				 * If any part of the record has been removed
1476 				 * (such as the MT_SONAME mbuf, which will
1477 				 * happen when PR_ADDR, and thus also
1478 				 * PR_ATOMIC, is set), then drop the entire
1479 				 * record to maintain the atomicity of the
1480 				 * receive operation.
1481 				 *
1482 				 * This avoids a later panic("receive 1a")
1483 				 * when compiled with DIAGNOSTIC.
1484 				 */
1485 				if (m && mbuf_removed && atomic)
1486 					(void) sbdroprecord(&so->so_rcv);
1487 
1488 				goto release;
1489 			}
1490 		} else {
1491 			uio->uio_resid -= len;
1492 		}
1493 
1494 		if (len == m->m_len - moff) {
1495 			if (m->m_flags & M_EOR)
1496 				flags |= MSG_EOR;
1497 #ifdef SCTP
1498 			if (m->m_flags & M_NOTIFICATION)
1499 				flags |= MSG_NOTIFICATION;
1500 #endif
1501 			if (flags & MSG_PEEK) {
1502 				m = m->m_next;
1503 				moff = 0;
1504 			} else {
1505 				nextrecord = m->m_nextpkt;
1506 				sbfree(&so->so_rcv, m);
1507 				if (mp) {
1508 					*mp = m;
1509 					mp = &m->m_next;
1510 					so->so_rcv.sb_mb = m = m->m_next;
1511 					*mp = NULL;
1512 				} else {
1513 					m = so->so_rcv.sb_mb = m_free(m);
1514 				}
1515 				/*
1516 				 * If m != NULL, we also know that
1517 				 * so->so_rcv.sb_mb != NULL.
1518 				 */
1519 				KASSERT(so->so_rcv.sb_mb == m);
1520 				if (m) {
1521 					m->m_nextpkt = nextrecord;
1522 					if (nextrecord == NULL)
1523 						so->so_rcv.sb_lastrecord = m;
1524 				} else {
1525 					so->so_rcv.sb_mb = nextrecord;
1526 					SB_EMPTY_FIXUP(&so->so_rcv);
1527 				}
1528 				SBLASTRECORDCHK(&so->so_rcv, "soreceive 3");
1529 				SBLASTMBUFCHK(&so->so_rcv, "soreceive 3");
1530 			}
1531 		} else if (flags & MSG_PEEK) {
1532 			moff += len;
1533 		} else {
1534 			if (mp != NULL) {
1535 				mt = m_copym(m, 0, len, M_NOWAIT);
1536 				if (__predict_false(mt == NULL)) {
1537 					sounlock(so);
1538 					mt = m_copym(m, 0, len, M_WAIT);
1539 					solock(so);
1540 				}
1541 				*mp = mt;
1542 			}
1543 			m->m_data += len;
1544 			m->m_len -= len;
1545 			so->so_rcv.sb_cc -= len;
1546 		}
1547 
1548 		if (so->so_oobmark) {
1549 			if ((flags & MSG_PEEK) == 0) {
1550 				so->so_oobmark -= len;
1551 				if (so->so_oobmark == 0) {
1552 					so->so_state |= SS_RCVATMARK;
1553 					break;
1554 				}
1555 			} else {
1556 				offset += len;
1557 				if (offset == so->so_oobmark)
1558 					break;
1559 			}
1560 		}
1561 		if (flags & MSG_EOR)
1562 			break;
1563 
1564 		/*
1565 		 * If the MSG_WAITALL flag is set (for non-atomic socket),
1566 		 * we must not quit until "uio->uio_resid == 0" or an error
1567 		 * termination.  If a signal/timeout occurs, return
1568 		 * with a short count but without error.
1569 		 * Keep sockbuf locked against other readers.
1570 		 */
1571 		while (flags & MSG_WAITALL && m == NULL && uio->uio_resid > 0 &&
1572 		    !sosendallatonce(so) && !nextrecord) {
1573 			if (so->so_error || so->so_rerror ||
1574 			    so->so_state & SS_CANTRCVMORE)
1575 				break;
1576 			/*
1577 			 * If we are peeking and the socket receive buffer is
1578 			 * full, stop since we can't get more data to peek at.
1579 			 */
1580 			if ((flags & MSG_PEEK) && sbspace(&so->so_rcv) <= 0)
1581 				break;
1582 			/*
1583 			 * If we've drained the socket buffer, tell the
1584 			 * protocol in case it needs to do something to
1585 			 * get it filled again.
1586 			 */
1587 			if ((pr->pr_flags & PR_WANTRCVD) && so->so_pcb)
1588 				(*pr->pr_usrreqs->pr_rcvd)(so, flags, l);
1589 			SBLASTRECORDCHK(&so->so_rcv, "soreceive sbwait 2");
1590 			SBLASTMBUFCHK(&so->so_rcv, "soreceive sbwait 2");
1591 			if (wakeup_state & SS_RESTARTSYS)
1592 				error = ERESTART;
1593 			else
1594 				error = sbwait(&so->so_rcv);
1595 			if (error != 0) {
1596 				sbunlock(&so->so_rcv);
1597 				sounlock(so);
1598 				splx(s);
1599 				return 0;
1600 			}
1601 			if ((m = so->so_rcv.sb_mb) != NULL)
1602 				nextrecord = m->m_nextpkt;
1603 			wakeup_state = so->so_state;
1604 		}
1605 	}
1606 
1607 	if (m && atomic) {
1608 		flags |= MSG_TRUNC;
1609 		if ((flags & MSG_PEEK) == 0)
1610 			(void) sbdroprecord(&so->so_rcv);
1611 	}
1612 	if ((flags & MSG_PEEK) == 0) {
1613 		if (m == NULL) {
1614 			/*
1615 			 * First part is an inline SB_EMPTY_FIXUP().  Second
1616 			 * part makes sure sb_lastrecord is up-to-date if
1617 			 * there is still data in the socket buffer.
1618 			 */
1619 			so->so_rcv.sb_mb = nextrecord;
1620 			if (so->so_rcv.sb_mb == NULL) {
1621 				so->so_rcv.sb_mbtail = NULL;
1622 				so->so_rcv.sb_lastrecord = NULL;
1623 			} else if (nextrecord->m_nextpkt == NULL)
1624 				so->so_rcv.sb_lastrecord = nextrecord;
1625 		}
1626 		SBLASTRECORDCHK(&so->so_rcv, "soreceive 4");
1627 		SBLASTMBUFCHK(&so->so_rcv, "soreceive 4");
1628 		if (pr->pr_flags & PR_WANTRCVD && so->so_pcb)
1629 			(*pr->pr_usrreqs->pr_rcvd)(so, flags, l);
1630 	}
1631 	if (orig_resid == uio->uio_resid && orig_resid &&
1632 	    (flags & MSG_EOR) == 0 && (so->so_state & SS_CANTRCVMORE) == 0) {
1633 		sbunlock(&so->so_rcv);
1634 		goto restart;
1635 	}
1636 
1637 	if (flagsp != NULL)
1638 		*flagsp |= flags;
1639 release:
1640 	sbunlock(&so->so_rcv);
1641 	sounlock(so);
1642 	splx(s);
1643 	return error;
1644 }
1645 
1646 int
1647 soshutdown(struct socket *so, int how)
1648 {
1649 	const struct protosw *pr;
1650 	int error;
1651 
1652 	KASSERT(solocked(so));
1653 
1654 	pr = so->so_proto;
1655 	if (!(how == SHUT_RD || how == SHUT_WR || how == SHUT_RDWR))
1656 		return EINVAL;
1657 
1658 	if (how == SHUT_RD || how == SHUT_RDWR) {
1659 		sorflush(so);
1660 		error = 0;
1661 	}
1662 	if (how == SHUT_WR || how == SHUT_RDWR)
1663 		error = (*pr->pr_usrreqs->pr_shutdown)(so);
1664 
1665 	return error;
1666 }
1667 
1668 void
1669 sorestart(struct socket *so)
1670 {
1671 	/*
1672 	 * An application has called close() on an fd on which another
1673 	 * of its threads has called a socket system call.
1674 	 * Mark this and wake everyone up, and code that would block again
1675 	 * instead returns ERESTART.
1676 	 * On system call re-entry the fd is validated and EBADF returned.
1677 	 * Any other fd will block again on the 2nd syscall.
1678 	 */
1679 	solock(so);
1680 	so->so_state |= SS_RESTARTSYS;
1681 	cv_broadcast(&so->so_cv);
1682 	cv_broadcast(&so->so_snd.sb_cv);
1683 	cv_broadcast(&so->so_rcv.sb_cv);
1684 	sounlock(so);
1685 }
1686 
1687 void
1688 sorflush(struct socket *so)
1689 {
1690 	struct sockbuf *sb, asb;
1691 	const struct protosw *pr;
1692 
1693 	KASSERT(solocked(so));
1694 
1695 	sb = &so->so_rcv;
1696 	pr = so->so_proto;
1697 	socantrcvmore(so);
1698 	sb->sb_flags |= SB_NOINTR;
1699 	(void )sblock(sb, M_WAITOK);
1700 	sbunlock(sb);
1701 	asb = *sb;
1702 	/*
1703 	 * Clear most of the sockbuf structure, but leave some of the
1704 	 * fields valid.
1705 	 */
1706 	memset(&sb->sb_startzero, 0,
1707 	    sizeof(*sb) - offsetof(struct sockbuf, sb_startzero));
1708 	if (pr->pr_flags & PR_RIGHTS && pr->pr_domain->dom_dispose) {
1709 		sounlock(so);
1710 		(*pr->pr_domain->dom_dispose)(asb.sb_mb);
1711 		solock(so);
1712 	}
1713 	sbrelease(&asb, so);
1714 }
1715 
1716 /*
1717  * internal set SOL_SOCKET options
1718  */
1719 static int
1720 sosetopt1(struct socket *so, const struct sockopt *sopt)
1721 {
1722 	int error, opt;
1723 	int optval = 0; /* XXX: gcc */
1724 	struct linger l;
1725 	struct timeval tv;
1726 
1727 	opt = sopt->sopt_name;
1728 
1729 	switch (opt) {
1730 
1731 	case SO_ACCEPTFILTER:
1732 		error = accept_filt_setopt(so, sopt);
1733 		KASSERT(solocked(so));
1734 		break;
1735 
1736 	case SO_LINGER:
1737 		error = sockopt_get(sopt, &l, sizeof(l));
1738 		solock(so);
1739 		if (error)
1740 			break;
1741 		if (l.l_linger < 0 || l.l_linger > USHRT_MAX ||
1742 		    l.l_linger > (INT_MAX / hz)) {
1743 			error = EDOM;
1744 			break;
1745 		}
1746 		so->so_linger = l.l_linger;
1747 		if (l.l_onoff)
1748 			so->so_options |= SO_LINGER;
1749 		else
1750 			so->so_options &= ~SO_LINGER;
1751 		break;
1752 
1753 	case SO_DEBUG:
1754 	case SO_KEEPALIVE:
1755 	case SO_DONTROUTE:
1756 	case SO_USELOOPBACK:
1757 	case SO_BROADCAST:
1758 	case SO_REUSEADDR:
1759 	case SO_REUSEPORT:
1760 	case SO_OOBINLINE:
1761 	case SO_TIMESTAMP:
1762 	case SO_NOSIGPIPE:
1763 	case SO_RERROR:
1764 		error = sockopt_getint(sopt, &optval);
1765 		solock(so);
1766 		if (error)
1767 			break;
1768 		if (optval)
1769 			so->so_options |= opt;
1770 		else
1771 			so->so_options &= ~opt;
1772 		break;
1773 
1774 	case SO_SNDBUF:
1775 	case SO_RCVBUF:
1776 	case SO_SNDLOWAT:
1777 	case SO_RCVLOWAT:
1778 		error = sockopt_getint(sopt, &optval);
1779 		solock(so);
1780 		if (error)
1781 			break;
1782 
1783 		/*
1784 		 * Values < 1 make no sense for any of these
1785 		 * options, so disallow them.
1786 		 */
1787 		if (optval < 1) {
1788 			error = EINVAL;
1789 			break;
1790 		}
1791 
1792 		switch (opt) {
1793 		case SO_SNDBUF:
1794 			if (sbreserve(&so->so_snd, (u_long)optval, so) == 0) {
1795 				error = ENOBUFS;
1796 				break;
1797 			}
1798 			so->so_snd.sb_flags &= ~SB_AUTOSIZE;
1799 			break;
1800 
1801 		case SO_RCVBUF:
1802 			if (sbreserve(&so->so_rcv, (u_long)optval, so) == 0) {
1803 				error = ENOBUFS;
1804 				break;
1805 			}
1806 			so->so_rcv.sb_flags &= ~SB_AUTOSIZE;
1807 			break;
1808 
1809 		/*
1810 		 * Make sure the low-water is never greater than
1811 		 * the high-water.
1812 		 */
1813 		case SO_SNDLOWAT:
1814 			if (optval > so->so_snd.sb_hiwat)
1815 				optval = so->so_snd.sb_hiwat;
1816 
1817 			so->so_snd.sb_lowat = optval;
1818 			break;
1819 
1820 		case SO_RCVLOWAT:
1821 			if (optval > so->so_rcv.sb_hiwat)
1822 				optval = so->so_rcv.sb_hiwat;
1823 
1824 			so->so_rcv.sb_lowat = optval;
1825 			break;
1826 		}
1827 		break;
1828 
1829 	case SO_SNDTIMEO:
1830 	case SO_RCVTIMEO:
1831 		solock(so);
1832 		error = sockopt_get(sopt, &tv, sizeof(tv));
1833 		if (error)
1834 			break;
1835 
1836 		if (tv.tv_sec < 0 || tv.tv_usec < 0 || tv.tv_usec >= 1000000) {
1837 			error = EDOM;
1838 			break;
1839 		}
1840 		if (tv.tv_sec > (INT_MAX - tv.tv_usec / tick) / hz) {
1841 			error = EDOM;
1842 			break;
1843 		}
1844 
1845 		optval = tv.tv_sec * hz + tv.tv_usec / tick;
1846 		if (optval == 0 && tv.tv_usec != 0)
1847 			optval = 1;
1848 
1849 		switch (opt) {
1850 		case SO_SNDTIMEO:
1851 			so->so_snd.sb_timeo = optval;
1852 			break;
1853 		case SO_RCVTIMEO:
1854 			so->so_rcv.sb_timeo = optval;
1855 			break;
1856 		}
1857 		break;
1858 
1859 	default:
1860 		MODULE_HOOK_CALL(uipc_socket_50_setopt1_hook,
1861 		    (opt, so, sopt), enosys(), error);
1862 		if (error == ENOSYS || error == EPASSTHROUGH) {
1863 			solock(so);
1864 			error = ENOPROTOOPT;
1865 		}
1866 		break;
1867 	}
1868 	KASSERT(solocked(so));
1869 	return error;
1870 }
1871 
1872 int
1873 sosetopt(struct socket *so, struct sockopt *sopt)
1874 {
1875 	int error, prerr;
1876 
1877 	if (sopt->sopt_level == SOL_SOCKET) {
1878 		error = sosetopt1(so, sopt);
1879 		KASSERT(solocked(so));
1880 	} else {
1881 		error = ENOPROTOOPT;
1882 		solock(so);
1883 	}
1884 
1885 	if ((error == 0 || error == ENOPROTOOPT) &&
1886 	    so->so_proto != NULL && so->so_proto->pr_ctloutput != NULL) {
1887 		/* give the protocol stack a shot */
1888 		prerr = (*so->so_proto->pr_ctloutput)(PRCO_SETOPT, so, sopt);
1889 		if (prerr == 0)
1890 			error = 0;
1891 		else if (prerr != ENOPROTOOPT)
1892 			error = prerr;
1893 	}
1894 	sounlock(so);
1895 	return error;
1896 }
1897 
1898 /*
1899  * so_setsockopt() is a wrapper providing a sockopt structure for sosetopt()
1900  */
1901 int
1902 so_setsockopt(struct lwp *l, struct socket *so, int level, int name,
1903     const void *val, size_t valsize)
1904 {
1905 	struct sockopt sopt;
1906 	int error;
1907 
1908 	KASSERT(valsize == 0 || val != NULL);
1909 
1910 	sockopt_init(&sopt, level, name, valsize);
1911 	sockopt_set(&sopt, val, valsize);
1912 
1913 	error = sosetopt(so, &sopt);
1914 
1915 	sockopt_destroy(&sopt);
1916 
1917 	return error;
1918 }
1919 
1920 /*
1921  * internal get SOL_SOCKET options
1922  */
1923 static int
1924 sogetopt1(struct socket *so, struct sockopt *sopt)
1925 {
1926 	int error, optval, opt;
1927 	struct linger l;
1928 	struct timeval tv;
1929 
1930 	switch ((opt = sopt->sopt_name)) {
1931 
1932 	case SO_ACCEPTFILTER:
1933 		error = accept_filt_getopt(so, sopt);
1934 		break;
1935 
1936 	case SO_LINGER:
1937 		l.l_onoff = (so->so_options & SO_LINGER) ? 1 : 0;
1938 		l.l_linger = so->so_linger;
1939 
1940 		error = sockopt_set(sopt, &l, sizeof(l));
1941 		break;
1942 
1943 	case SO_USELOOPBACK:
1944 	case SO_DONTROUTE:
1945 	case SO_DEBUG:
1946 	case SO_KEEPALIVE:
1947 	case SO_REUSEADDR:
1948 	case SO_REUSEPORT:
1949 	case SO_BROADCAST:
1950 	case SO_OOBINLINE:
1951 	case SO_TIMESTAMP:
1952 	case SO_NOSIGPIPE:
1953 	case SO_RERROR:
1954 	case SO_ACCEPTCONN:
1955 		error = sockopt_setint(sopt, (so->so_options & opt) ? 1 : 0);
1956 		break;
1957 
1958 	case SO_TYPE:
1959 		error = sockopt_setint(sopt, so->so_type);
1960 		break;
1961 
1962 	case SO_ERROR:
1963 		if (so->so_error == 0) {
1964 			so->so_error = so->so_rerror;
1965 			so->so_rerror = 0;
1966 		}
1967 		error = sockopt_setint(sopt, so->so_error);
1968 		so->so_error = 0;
1969 		break;
1970 
1971 	case SO_SNDBUF:
1972 		error = sockopt_setint(sopt, so->so_snd.sb_hiwat);
1973 		break;
1974 
1975 	case SO_RCVBUF:
1976 		error = sockopt_setint(sopt, so->so_rcv.sb_hiwat);
1977 		break;
1978 
1979 	case SO_SNDLOWAT:
1980 		error = sockopt_setint(sopt, so->so_snd.sb_lowat);
1981 		break;
1982 
1983 	case SO_RCVLOWAT:
1984 		error = sockopt_setint(sopt, so->so_rcv.sb_lowat);
1985 		break;
1986 
1987 	case SO_SNDTIMEO:
1988 	case SO_RCVTIMEO:
1989 		optval = (opt == SO_SNDTIMEO ?
1990 		     so->so_snd.sb_timeo : so->so_rcv.sb_timeo);
1991 
1992 		tv.tv_sec = optval / hz;
1993 		tv.tv_usec = (optval % hz) * tick;
1994 
1995 		error = sockopt_set(sopt, &tv, sizeof(tv));
1996 		break;
1997 
1998 	case SO_OVERFLOWED:
1999 		error = sockopt_setint(sopt, so->so_rcv.sb_overflowed);
2000 		break;
2001 
2002 	default:
2003 		MODULE_HOOK_CALL(uipc_socket_50_getopt1_hook,
2004 		    (opt, so, sopt), enosys(), error);
2005 		if (error)
2006 			error = ENOPROTOOPT;
2007 		break;
2008 	}
2009 
2010 	return error;
2011 }
2012 
2013 int
2014 sogetopt(struct socket *so, struct sockopt *sopt)
2015 {
2016 	int error;
2017 
2018 	solock(so);
2019 	if (sopt->sopt_level != SOL_SOCKET) {
2020 		if (so->so_proto && so->so_proto->pr_ctloutput) {
2021 			error = ((*so->so_proto->pr_ctloutput)
2022 			    (PRCO_GETOPT, so, sopt));
2023 		} else
2024 			error = (ENOPROTOOPT);
2025 	} else {
2026 		error = sogetopt1(so, sopt);
2027 	}
2028 	sounlock(so);
2029 	return error;
2030 }
2031 
2032 /*
2033  * alloc sockopt data buffer buffer
2034  *	- will be released at destroy
2035  */
2036 static int
2037 sockopt_alloc(struct sockopt *sopt, size_t len, km_flag_t kmflag)
2038 {
2039 
2040 	KASSERT(sopt->sopt_size == 0);
2041 
2042 	if (len > sizeof(sopt->sopt_buf)) {
2043 		sopt->sopt_data = kmem_zalloc(len, kmflag);
2044 		if (sopt->sopt_data == NULL)
2045 			return ENOMEM;
2046 	} else
2047 		sopt->sopt_data = sopt->sopt_buf;
2048 
2049 	sopt->sopt_size = len;
2050 	return 0;
2051 }
2052 
2053 /*
2054  * initialise sockopt storage
2055  *	- MAY sleep during allocation
2056  */
2057 void
2058 sockopt_init(struct sockopt *sopt, int level, int name, size_t size)
2059 {
2060 
2061 	memset(sopt, 0, sizeof(*sopt));
2062 
2063 	sopt->sopt_level = level;
2064 	sopt->sopt_name = name;
2065 	(void)sockopt_alloc(sopt, size, KM_SLEEP);
2066 }
2067 
2068 /*
2069  * destroy sockopt storage
2070  *	- will release any held memory references
2071  */
2072 void
2073 sockopt_destroy(struct sockopt *sopt)
2074 {
2075 
2076 	if (sopt->sopt_data != sopt->sopt_buf)
2077 		kmem_free(sopt->sopt_data, sopt->sopt_size);
2078 
2079 	memset(sopt, 0, sizeof(*sopt));
2080 }
2081 
2082 /*
2083  * set sockopt value
2084  *	- value is copied into sockopt
2085  *	- memory is allocated when necessary, will not sleep
2086  */
2087 int
2088 sockopt_set(struct sockopt *sopt, const void *buf, size_t len)
2089 {
2090 	int error;
2091 
2092 	if (sopt->sopt_size == 0) {
2093 		error = sockopt_alloc(sopt, len, KM_NOSLEEP);
2094 		if (error)
2095 			return error;
2096 	}
2097 
2098 	sopt->sopt_retsize = MIN(sopt->sopt_size, len);
2099 	if (sopt->sopt_retsize > 0) {
2100 		memcpy(sopt->sopt_data, buf, sopt->sopt_retsize);
2101 	}
2102 
2103 	return 0;
2104 }
2105 
2106 /*
2107  * common case of set sockopt integer value
2108  */
2109 int
2110 sockopt_setint(struct sockopt *sopt, int val)
2111 {
2112 
2113 	return sockopt_set(sopt, &val, sizeof(int));
2114 }
2115 
2116 /*
2117  * get sockopt value
2118  *	- correct size must be given
2119  */
2120 int
2121 sockopt_get(const struct sockopt *sopt, void *buf, size_t len)
2122 {
2123 
2124 	if (sopt->sopt_size != len)
2125 		return EINVAL;
2126 
2127 	memcpy(buf, sopt->sopt_data, len);
2128 	return 0;
2129 }
2130 
2131 /*
2132  * common case of get sockopt integer value
2133  */
2134 int
2135 sockopt_getint(const struct sockopt *sopt, int *valp)
2136 {
2137 
2138 	return sockopt_get(sopt, valp, sizeof(int));
2139 }
2140 
2141 /*
2142  * set sockopt value from mbuf
2143  *	- ONLY for legacy code
2144  *	- mbuf is released by sockopt
2145  *	- will not sleep
2146  */
2147 int
2148 sockopt_setmbuf(struct sockopt *sopt, struct mbuf *m)
2149 {
2150 	size_t len;
2151 	int error;
2152 
2153 	len = m_length(m);
2154 
2155 	if (sopt->sopt_size == 0) {
2156 		error = sockopt_alloc(sopt, len, KM_NOSLEEP);
2157 		if (error)
2158 			return error;
2159 	}
2160 
2161 	sopt->sopt_retsize = MIN(sopt->sopt_size, len);
2162 	m_copydata(m, 0, sopt->sopt_retsize, sopt->sopt_data);
2163 	m_freem(m);
2164 
2165 	return 0;
2166 }
2167 
2168 /*
2169  * get sockopt value into mbuf
2170  *	- ONLY for legacy code
2171  *	- mbuf to be released by the caller
2172  *	- will not sleep
2173  */
2174 struct mbuf *
2175 sockopt_getmbuf(const struct sockopt *sopt)
2176 {
2177 	struct mbuf *m;
2178 
2179 	if (sopt->sopt_size > MCLBYTES)
2180 		return NULL;
2181 
2182 	m = m_get(M_DONTWAIT, MT_SOOPTS);
2183 	if (m == NULL)
2184 		return NULL;
2185 
2186 	if (sopt->sopt_size > MLEN) {
2187 		MCLGET(m, M_DONTWAIT);
2188 		if ((m->m_flags & M_EXT) == 0) {
2189 			m_free(m);
2190 			return NULL;
2191 		}
2192 	}
2193 
2194 	memcpy(mtod(m, void *), sopt->sopt_data, sopt->sopt_size);
2195 	m->m_len = sopt->sopt_size;
2196 
2197 	return m;
2198 }
2199 
2200 void
2201 sohasoutofband(struct socket *so)
2202 {
2203 
2204 	fownsignal(so->so_pgid, SIGURG, POLL_PRI, POLLPRI|POLLRDBAND, so);
2205 	selnotify(&so->so_rcv.sb_sel, POLLPRI | POLLRDBAND, NOTE_SUBMIT);
2206 }
2207 
2208 static void
2209 filt_sordetach(struct knote *kn)
2210 {
2211 	struct socket *so;
2212 
2213 	so = ((file_t *)kn->kn_obj)->f_socket;
2214 	solock(so);
2215 	SLIST_REMOVE(&so->so_rcv.sb_sel.sel_klist, kn, knote, kn_selnext);
2216 	if (SLIST_EMPTY(&so->so_rcv.sb_sel.sel_klist))
2217 		so->so_rcv.sb_flags &= ~SB_KNOTE;
2218 	sounlock(so);
2219 }
2220 
2221 /*ARGSUSED*/
2222 static int
2223 filt_soread(struct knote *kn, long hint)
2224 {
2225 	struct socket *so;
2226 	int rv;
2227 
2228 	so = ((file_t *)kn->kn_obj)->f_socket;
2229 	if (hint != NOTE_SUBMIT)
2230 		solock(so);
2231 	kn->kn_data = so->so_rcv.sb_cc;
2232 	if (so->so_state & SS_CANTRCVMORE) {
2233 		kn->kn_flags |= EV_EOF;
2234 		kn->kn_fflags = so->so_error;
2235 		rv = 1;
2236 	} else if (so->so_error || so->so_rerror)
2237 		rv = 1;
2238 	else if (kn->kn_sfflags & NOTE_LOWAT)
2239 		rv = (kn->kn_data >= kn->kn_sdata);
2240 	else
2241 		rv = (kn->kn_data >= so->so_rcv.sb_lowat);
2242 	if (hint != NOTE_SUBMIT)
2243 		sounlock(so);
2244 	return rv;
2245 }
2246 
2247 static void
2248 filt_sowdetach(struct knote *kn)
2249 {
2250 	struct socket *so;
2251 
2252 	so = ((file_t *)kn->kn_obj)->f_socket;
2253 	solock(so);
2254 	SLIST_REMOVE(&so->so_snd.sb_sel.sel_klist, kn, knote, kn_selnext);
2255 	if (SLIST_EMPTY(&so->so_snd.sb_sel.sel_klist))
2256 		so->so_snd.sb_flags &= ~SB_KNOTE;
2257 	sounlock(so);
2258 }
2259 
2260 /*ARGSUSED*/
2261 static int
2262 filt_sowrite(struct knote *kn, long hint)
2263 {
2264 	struct socket *so;
2265 	int rv;
2266 
2267 	so = ((file_t *)kn->kn_obj)->f_socket;
2268 	if (hint != NOTE_SUBMIT)
2269 		solock(so);
2270 	kn->kn_data = sbspace(&so->so_snd);
2271 	if (so->so_state & SS_CANTSENDMORE) {
2272 		kn->kn_flags |= EV_EOF;
2273 		kn->kn_fflags = so->so_error;
2274 		rv = 1;
2275 	} else if (so->so_error)
2276 		rv = 1;
2277 	else if (((so->so_state & SS_ISCONNECTED) == 0) &&
2278 	    (so->so_proto->pr_flags & PR_CONNREQUIRED))
2279 		rv = 0;
2280 	else if (kn->kn_sfflags & NOTE_LOWAT)
2281 		rv = (kn->kn_data >= kn->kn_sdata);
2282 	else
2283 		rv = (kn->kn_data >= so->so_snd.sb_lowat);
2284 	if (hint != NOTE_SUBMIT)
2285 		sounlock(so);
2286 	return rv;
2287 }
2288 
2289 /*ARGSUSED*/
2290 static int
2291 filt_solisten(struct knote *kn, long hint)
2292 {
2293 	struct socket *so;
2294 	int rv;
2295 
2296 	so = ((file_t *)kn->kn_obj)->f_socket;
2297 
2298 	/*
2299 	 * Set kn_data to number of incoming connections, not
2300 	 * counting partial (incomplete) connections.
2301 	 */
2302 	if (hint != NOTE_SUBMIT)
2303 		solock(so);
2304 	kn->kn_data = so->so_qlen;
2305 	rv = (kn->kn_data > 0);
2306 	if (hint != NOTE_SUBMIT)
2307 		sounlock(so);
2308 	return rv;
2309 }
2310 
2311 static const struct filterops solisten_filtops = {
2312 	.f_isfd = 1,
2313 	.f_attach = NULL,
2314 	.f_detach = filt_sordetach,
2315 	.f_event = filt_solisten,
2316 };
2317 
2318 static const struct filterops soread_filtops = {
2319 	.f_isfd = 1,
2320 	.f_attach = NULL,
2321 	.f_detach = filt_sordetach,
2322 	.f_event = filt_soread,
2323 };
2324 
2325 static const struct filterops sowrite_filtops = {
2326 	.f_isfd = 1,
2327 	.f_attach = NULL,
2328 	.f_detach = filt_sowdetach,
2329 	.f_event = filt_sowrite,
2330 };
2331 
2332 int
2333 soo_kqfilter(struct file *fp, struct knote *kn)
2334 {
2335 	struct socket *so;
2336 	struct sockbuf *sb;
2337 
2338 	so = ((file_t *)kn->kn_obj)->f_socket;
2339 	solock(so);
2340 	switch (kn->kn_filter) {
2341 	case EVFILT_READ:
2342 		if (so->so_options & SO_ACCEPTCONN)
2343 			kn->kn_fop = &solisten_filtops;
2344 		else
2345 			kn->kn_fop = &soread_filtops;
2346 		sb = &so->so_rcv;
2347 		break;
2348 	case EVFILT_WRITE:
2349 		kn->kn_fop = &sowrite_filtops;
2350 		sb = &so->so_snd;
2351 		break;
2352 	default:
2353 		sounlock(so);
2354 		return EINVAL;
2355 	}
2356 	SLIST_INSERT_HEAD(&sb->sb_sel.sel_klist, kn, kn_selnext);
2357 	sb->sb_flags |= SB_KNOTE;
2358 	sounlock(so);
2359 	return 0;
2360 }
2361 
2362 static int
2363 sodopoll(struct socket *so, int events)
2364 {
2365 	int revents;
2366 
2367 	revents = 0;
2368 
2369 	if (events & (POLLIN | POLLRDNORM))
2370 		if (soreadable(so))
2371 			revents |= events & (POLLIN | POLLRDNORM);
2372 
2373 	if (events & (POLLOUT | POLLWRNORM))
2374 		if (sowritable(so))
2375 			revents |= events & (POLLOUT | POLLWRNORM);
2376 
2377 	if (events & (POLLPRI | POLLRDBAND))
2378 		if (so->so_oobmark || (so->so_state & SS_RCVATMARK))
2379 			revents |= events & (POLLPRI | POLLRDBAND);
2380 
2381 	return revents;
2382 }
2383 
2384 int
2385 sopoll(struct socket *so, int events)
2386 {
2387 	int revents = 0;
2388 
2389 #ifndef DIAGNOSTIC
2390 	/*
2391 	 * Do a quick, unlocked check in expectation that the socket
2392 	 * will be ready for I/O.  Don't do this check if DIAGNOSTIC,
2393 	 * as the solocked() assertions will fail.
2394 	 */
2395 	if ((revents = sodopoll(so, events)) != 0)
2396 		return revents;
2397 #endif
2398 
2399 	solock(so);
2400 	if ((revents = sodopoll(so, events)) == 0) {
2401 		if (events & (POLLIN | POLLPRI | POLLRDNORM | POLLRDBAND)) {
2402 			selrecord(curlwp, &so->so_rcv.sb_sel);
2403 			so->so_rcv.sb_flags |= SB_NOTIFY;
2404 		}
2405 
2406 		if (events & (POLLOUT | POLLWRNORM)) {
2407 			selrecord(curlwp, &so->so_snd.sb_sel);
2408 			so->so_snd.sb_flags |= SB_NOTIFY;
2409 		}
2410 	}
2411 	sounlock(so);
2412 
2413 	return revents;
2414 }
2415 
2416 struct mbuf **
2417 sbsavetimestamp(int opt, struct mbuf **mp)
2418 {
2419 	struct timeval tv;
2420 	int error;
2421 
2422 	microtime(&tv);
2423 
2424 	MODULE_HOOK_CALL(uipc_socket_50_sbts_hook, (opt, &mp), enosys(), error);
2425 	if (error == 0)
2426 		return mp;
2427 
2428 	if (opt & SO_TIMESTAMP) {
2429 		*mp = sbcreatecontrol(&tv, sizeof(tv),
2430 		    SCM_TIMESTAMP, SOL_SOCKET);
2431 		if (*mp)
2432 			mp = &(*mp)->m_next;
2433 	}
2434 	return mp;
2435 }
2436 
2437 
2438 #include <sys/sysctl.h>
2439 
2440 static int sysctl_kern_somaxkva(SYSCTLFN_PROTO);
2441 static int sysctl_kern_sbmax(SYSCTLFN_PROTO);
2442 
2443 /*
2444  * sysctl helper routine for kern.somaxkva.  ensures that the given
2445  * value is not too small.
2446  * (XXX should we maybe make sure it's not too large as well?)
2447  */
2448 static int
2449 sysctl_kern_somaxkva(SYSCTLFN_ARGS)
2450 {
2451 	int error, new_somaxkva;
2452 	struct sysctlnode node;
2453 
2454 	new_somaxkva = somaxkva;
2455 	node = *rnode;
2456 	node.sysctl_data = &new_somaxkva;
2457 	error = sysctl_lookup(SYSCTLFN_CALL(&node));
2458 	if (error || newp == NULL)
2459 		return error;
2460 
2461 	if (new_somaxkva < (16 * 1024 * 1024)) /* sanity */
2462 		return EINVAL;
2463 
2464 	mutex_enter(&so_pendfree_lock);
2465 	somaxkva = new_somaxkva;
2466 	cv_broadcast(&socurkva_cv);
2467 	mutex_exit(&so_pendfree_lock);
2468 
2469 	return error;
2470 }
2471 
2472 /*
2473  * sysctl helper routine for kern.sbmax. Basically just ensures that
2474  * any new value is not too small.
2475  */
2476 static int
2477 sysctl_kern_sbmax(SYSCTLFN_ARGS)
2478 {
2479 	int error, new_sbmax;
2480 	struct sysctlnode node;
2481 
2482 	new_sbmax = sb_max;
2483 	node = *rnode;
2484 	node.sysctl_data = &new_sbmax;
2485 	error = sysctl_lookup(SYSCTLFN_CALL(&node));
2486 	if (error || newp == NULL)
2487 		return error;
2488 
2489 	KERNEL_LOCK(1, NULL);
2490 	error = sb_max_set(new_sbmax);
2491 	KERNEL_UNLOCK_ONE(NULL);
2492 
2493 	return error;
2494 }
2495 
2496 /*
2497  * sysctl helper routine for kern.sooptions. Ensures that only allowed
2498  * options can be set.
2499  */
2500 static int
2501 sysctl_kern_sooptions(SYSCTLFN_ARGS)
2502 {
2503 	int error, new_options;
2504 	struct sysctlnode node;
2505 
2506 	new_options = sooptions;
2507 	node = *rnode;
2508 	node.sysctl_data = &new_options;
2509 	error = sysctl_lookup(SYSCTLFN_CALL(&node));
2510 	if (error || newp == NULL)
2511 		return error;
2512 
2513 	if (new_options & ~SO_DEFOPTS)
2514 		return EINVAL;
2515 
2516 	sooptions = new_options;
2517 
2518 	return 0;
2519 }
2520 
2521 static void
2522 sysctl_kern_socket_setup(void)
2523 {
2524 
2525 	KASSERT(socket_sysctllog == NULL);
2526 
2527 	sysctl_createv(&socket_sysctllog, 0, NULL, NULL,
2528 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
2529 		       CTLTYPE_INT, "somaxkva",
2530 		       SYSCTL_DESCR("Maximum amount of kernel memory to be "
2531 		                    "used for socket buffers"),
2532 		       sysctl_kern_somaxkva, 0, NULL, 0,
2533 		       CTL_KERN, KERN_SOMAXKVA, CTL_EOL);
2534 
2535 	sysctl_createv(&socket_sysctllog, 0, NULL, NULL,
2536 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
2537 		       CTLTYPE_INT, "sbmax",
2538 		       SYSCTL_DESCR("Maximum socket buffer size"),
2539 		       sysctl_kern_sbmax, 0, NULL, 0,
2540 		       CTL_KERN, KERN_SBMAX, CTL_EOL);
2541 
2542 	sysctl_createv(&socket_sysctllog, 0, NULL, NULL,
2543 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
2544 		       CTLTYPE_INT, "sooptions",
2545 		       SYSCTL_DESCR("Default socket options"),
2546 		       sysctl_kern_sooptions, 0, NULL, 0,
2547 		       CTL_KERN, CTL_CREATE, CTL_EOL);
2548 }
2549