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