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