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