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