xref: /freebsd/sys/kern/uipc_socket.c (revision cb7009867ae6b33aa39cb6cb1453b69073144b44)
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 1982, 1986, 1988, 1990, 1993
5  *	The Regents of the University of California.
6  * Copyright (c) 2004 The FreeBSD Foundation
7  * Copyright (c) 2004-2008 Robert N. M. Watson
8  * All rights reserved.
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  * 3. Neither the name of the University nor the names of its contributors
19  *    may be used to endorse or promote products derived from this software
20  *    without specific prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  */
34 
35 /*
36  * Comments on the socket life cycle:
37  *
38  * soalloc() sets of socket layer state for a socket, called only by
39  * socreate() and sonewconn().  Socket layer private.
40  *
41  * sodealloc() tears down socket layer state for a socket, called only by
42  * sofree() and sonewconn().  Socket layer private.
43  *
44  * pr_attach() associates protocol layer state with an allocated socket;
45  * called only once, may fail, aborting socket allocation.  This is called
46  * from socreate() and sonewconn().  Socket layer private.
47  *
48  * pr_detach() disassociates protocol layer state from an attached socket,
49  * and will be called exactly once for sockets in which pr_attach() has
50  * been successfully called.  If pr_attach() returned an error,
51  * pr_detach() will not be called.  Socket layer private.
52  *
53  * pr_abort() and pr_close() notify the protocol layer that the last
54  * consumer of a socket is starting to tear down the socket, and that the
55  * protocol should terminate the connection.  Historically, pr_abort() also
56  * detached protocol state from the socket state, but this is no longer the
57  * case.  pr_fdclose() is called when userspace invokes close(2) on a socket
58  * file descriptor.
59  *
60  * socreate() creates a socket and attaches protocol state.  This is a public
61  * interface that may be used by socket layer consumers to create new
62  * sockets.
63  *
64  * sonewconn() creates a socket and attaches protocol state.  This is a
65  * public interface  that may be used by protocols to create new sockets when
66  * a new connection is received and will be available for accept() on a
67  * listen socket.
68  *
69  * soclose() destroys a socket after possibly waiting for it to disconnect.
70  * This is a public interface that socket consumers should use to close and
71  * release a socket when done with it.
72  *
73  * soabort() destroys a socket without waiting for it to disconnect (used
74  * only for incoming connections that are already partially or fully
75  * connected).  This is used internally by the socket layer when clearing
76  * listen socket queues (due to overflow or close on the listen socket), but
77  * is also a public interface protocols may use to abort connections in
78  * their incomplete listen queues should they no longer be required.  Sockets
79  * placed in completed connection listen queues should not be aborted for
80  * reasons described in the comment above the soclose() implementation.  This
81  * is not a general purpose close routine, and except in the specific
82  * circumstances described here, should not be used.
83  *
84  * sofree() will free a socket and its protocol state if all references on
85  * the socket have been released, and is the public interface to attempt to
86  * free a socket when a reference is removed.  This is a socket layer private
87  * interface.
88  *
89  * NOTE: In addition to socreate() and soclose(), which provide a single
90  * socket reference to the consumer to be managed as required, there are two
91  * calls to explicitly manage socket references, soref(), and sorele().
92  * Currently, these are generally required only when transitioning a socket
93  * from a listen queue to a file descriptor, in order to prevent garbage
94  * collection of the socket at an untimely moment.  For a number of reasons,
95  * these interfaces are not preferred, and should be avoided.
96  *
97  * NOTE: With regard to VNETs the general rule is that callers do not set
98  * curvnet. Exceptions to this rule include soabort(), sodisconnect(),
99  * sofree(), sorele(), sonewconn() and sorflush(), which are usually called
100  * from a pre-set VNET context.  sopoll_generic() currently does not need a
101  * VNET context to be set.
102  */
103 
104 #include <sys/cdefs.h>
105 #include "opt_inet.h"
106 #include "opt_inet6.h"
107 #include "opt_kern_tls.h"
108 #include "opt_ktrace.h"
109 #include "opt_sctp.h"
110 
111 #include <sys/param.h>
112 #include <sys/systm.h>
113 #include <sys/capsicum.h>
114 #include <sys/fcntl.h>
115 #include <sys/limits.h>
116 #include <sys/lock.h>
117 #include <sys/mac.h>
118 #include <sys/malloc.h>
119 #include <sys/mbuf.h>
120 #include <sys/mutex.h>
121 #include <sys/domain.h>
122 #include <sys/file.h>			/* for struct knote */
123 #include <sys/hhook.h>
124 #include <sys/kernel.h>
125 #include <sys/khelp.h>
126 #include <sys/kthread.h>
127 #include <sys/ktls.h>
128 #include <sys/event.h>
129 #include <sys/eventhandler.h>
130 #include <sys/poll.h>
131 #include <sys/proc.h>
132 #include <sys/protosw.h>
133 #include <sys/sbuf.h>
134 #include <sys/socket.h>
135 #include <sys/socketvar.h>
136 #include <sys/resourcevar.h>
137 #include <net/route.h>
138 #include <sys/sched.h>
139 #include <sys/signalvar.h>
140 #include <sys/smp.h>
141 #include <sys/stat.h>
142 #include <sys/sx.h>
143 #include <sys/sysctl.h>
144 #include <sys/taskqueue.h>
145 #include <sys/uio.h>
146 #include <sys/un.h>
147 #include <sys/unpcb.h>
148 #include <sys/jail.h>
149 #include <sys/syslog.h>
150 #include <netinet/in.h>
151 #include <netinet/in_pcb.h>
152 #include <netinet/tcp.h>
153 
154 #include <net/vnet.h>
155 
156 #include <security/mac/mac_framework.h>
157 #include <security/mac/mac_internal.h>
158 
159 #include <vm/uma.h>
160 
161 #ifdef COMPAT_FREEBSD32
162 #include <sys/mount.h>
163 #include <sys/sysent.h>
164 #include <compat/freebsd32/freebsd32.h>
165 #endif
166 
167 static int	soreceive_generic_locked(struct socket *so,
168 		    struct sockaddr **psa, struct uio *uio, struct mbuf **mp,
169 		    struct mbuf **controlp, int *flagsp);
170 static int	soreceive_rcvoob(struct socket *so, struct uio *uio,
171 		    int flags);
172 static int	soreceive_stream_locked(struct socket *so, struct sockbuf *sb,
173 		    struct sockaddr **psa, struct uio *uio, struct mbuf **mp,
174 		    struct mbuf **controlp, int flags);
175 static int	sosend_generic_locked(struct socket *so, struct sockaddr *addr,
176 		    struct uio *uio, struct mbuf *top, struct mbuf *control,
177 		    int flags, struct thread *td);
178 static void	so_rdknl_lock(void *);
179 static void	so_rdknl_unlock(void *);
180 static void	so_rdknl_assert_lock(void *, int);
181 static void	so_wrknl_lock(void *);
182 static void	so_wrknl_unlock(void *);
183 static void	so_wrknl_assert_lock(void *, int);
184 
185 static void	filt_sordetach(struct knote *kn);
186 static int	filt_soread(struct knote *kn, long hint);
187 static void	filt_sowdetach(struct knote *kn);
188 static int	filt_sowrite(struct knote *kn, long hint);
189 static int	filt_soempty(struct knote *kn, long hint);
190 
191 static const struct filterops soread_filtops = {
192 	.f_isfd = 1,
193 	.f_detach = filt_sordetach,
194 	.f_event = filt_soread,
195 	.f_copy = knote_triv_copy,
196 };
197 static const struct filterops sowrite_filtops = {
198 	.f_isfd = 1,
199 	.f_detach = filt_sowdetach,
200 	.f_event = filt_sowrite,
201 	.f_copy = knote_triv_copy,
202 };
203 static const struct filterops soempty_filtops = {
204 	.f_isfd = 1,
205 	.f_detach = filt_sowdetach,
206 	.f_event = filt_soempty,
207 	.f_copy = knote_triv_copy,
208 };
209 
210 so_gen_t	so_gencnt;	/* generation count for sockets */
211 
212 MALLOC_DEFINE(M_SONAME, "soname", "socket name");
213 MALLOC_DEFINE(M_PCB, "pcb", "protocol control block");
214 
215 #define	VNET_SO_ASSERT(so)						\
216 	VNET_ASSERT(curvnet != NULL,					\
217 	    ("%s:%d curvnet is NULL, so=%p", __func__, __LINE__, (so)));
218 
219 #ifdef SOCKET_HHOOK
220 VNET_DEFINE(struct hhook_head *, socket_hhh[HHOOK_SOCKET_LAST + 1]);
221 #define	V_socket_hhh		VNET(socket_hhh)
222 static inline int hhook_run_socket(struct socket *, void *, int32_t);
223 #endif
224 
225 #ifdef COMPAT_FREEBSD32
226 #ifdef __amd64__
227 /* off_t has 4-byte alignment on i386 but not on other 32-bit platforms. */
228 #define	__splice32_packed	__packed
229 #else
230 #define	__splice32_packed
231 #endif
232 struct splice32 {
233 	int32_t	sp_fd;
234 	int64_t sp_max;
235 	struct timeval32 sp_idle;
236 } __splice32_packed;
237 #undef __splice32_packed
238 #endif
239 
240 /*
241  * Limit on the number of connections in the listen queue waiting
242  * for accept(2).
243  * NB: The original sysctl somaxconn is still available but hidden
244  * to prevent confusion about the actual purpose of this number.
245  */
246 VNET_DEFINE_STATIC(u_int, somaxconn) = SOMAXCONN;
247 #define	V_somaxconn	VNET(somaxconn)
248 
249 static int
sysctl_somaxconn(SYSCTL_HANDLER_ARGS)250 sysctl_somaxconn(SYSCTL_HANDLER_ARGS)
251 {
252 	int error;
253 	u_int val;
254 
255 	val = V_somaxconn;
256 	error = sysctl_handle_int(oidp, &val, 0, req);
257 	if (error || !req->newptr )
258 		return (error);
259 
260 	/*
261 	 * The purpose of the UINT_MAX / 3 limit, is so that the formula
262 	 *   3 * sol_qlimit / 2
263 	 * below, will not overflow.
264          */
265 
266 	if (val < 1 || val > UINT_MAX / 3)
267 		return (EINVAL);
268 
269 	V_somaxconn = val;
270 	return (0);
271 }
272 SYSCTL_PROC(_kern_ipc, OID_AUTO, soacceptqueue,
273     CTLTYPE_UINT | CTLFLAG_RW | CTLFLAG_MPSAFE | CTLFLAG_VNET, 0, sizeof(u_int),
274     sysctl_somaxconn, "IU",
275     "Maximum listen socket pending connection accept queue size");
276 SYSCTL_PROC(_kern_ipc, KIPC_SOMAXCONN, somaxconn,
277     CTLTYPE_UINT | CTLFLAG_RW | CTLFLAG_SKIP | CTLFLAG_MPSAFE | CTLFLAG_VNET, 0,
278     sizeof(u_int), sysctl_somaxconn, "IU",
279     "Maximum listen socket pending connection accept queue size (compat)");
280 
281 static u_int numopensockets;
282 static int
sysctl_numopensockets(SYSCTL_HANDLER_ARGS)283 sysctl_numopensockets(SYSCTL_HANDLER_ARGS)
284 {
285 	u_int val;
286 
287 #ifdef VIMAGE
288 	if(!IS_DEFAULT_VNET(curvnet))
289 		val = curvnet->vnet_sockcnt;
290 	else
291 #endif
292 		val = numopensockets;
293 	return (sysctl_handle_int(oidp, &val, 0, req));
294 }
295 SYSCTL_PROC(_kern_ipc, OID_AUTO, numopensockets,
296     CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE | CTLFLAG_VNET, 0, sizeof(u_int),
297     sysctl_numopensockets, "IU", "Number of open sockets");
298 
299 /*
300  * so_global_mtx protects so_gencnt, numopensockets, and the per-socket
301  * so_gencnt field.
302  */
303 static struct mtx so_global_mtx;
304 MTX_SYSINIT(so_global_mtx, &so_global_mtx, "so_glabel", MTX_DEF);
305 
306 /*
307  * General IPC sysctl name space, used by sockets and a variety of other IPC
308  * types.
309  */
310 SYSCTL_NODE(_kern, KERN_IPC, ipc, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
311     "IPC");
312 
313 /*
314  * Initialize the socket subsystem and set up the socket
315  * memory allocator.
316  */
317 static uma_zone_t socket_zone;
318 int	maxsockets;
319 
320 static void
socket_zone_change(void * tag)321 socket_zone_change(void *tag)
322 {
323 
324 	maxsockets = uma_zone_set_max(socket_zone, maxsockets);
325 }
326 
327 static int splice_init_state;
328 static struct sx splice_init_lock;
329 SX_SYSINIT(splice_init_lock, &splice_init_lock, "splice_init");
330 
331 static SYSCTL_NODE(_kern_ipc, OID_AUTO, splice, CTLFLAG_RW, 0,
332     "Settings relating to the SO_SPLICE socket option");
333 
334 static bool splice_receive_stream = true;
335 SYSCTL_BOOL(_kern_ipc_splice, OID_AUTO, receive_stream, CTLFLAG_RWTUN,
336     &splice_receive_stream, 0,
337     "Use soreceive_stream() for stream splices");
338 
339 static int splice_num_wq = -1;
340 static int
sysctl_splice_num_wq(SYSCTL_HANDLER_ARGS)341 sysctl_splice_num_wq(SYSCTL_HANDLER_ARGS)
342 {
343 	int error, new;
344 
345 	new = splice_num_wq;
346 	error = sysctl_handle_int(oidp, &new, 0, req);
347 	if (error == 0 && req->newptr && new != splice_num_wq) {
348 		if (!cold)
349 			sx_xlock(&splice_init_lock);
350 		if (new < -1 || new > mp_ncpus ||
351 		    (new <= 0 && splice_init_state != 0)) {
352 			error = EINVAL;
353 		} else {
354 			splice_num_wq = new;
355 		}
356 		if (!cold)
357 			sx_xunlock(&splice_init_lock);
358 	}
359 	return (error);
360 }
361 SYSCTL_PROC(_kern_ipc_splice, OID_AUTO, num_wq,
362     CTLTYPE_INT | CTLFLAG_RWTUN | CTLFLAG_MPSAFE,
363     &splice_num_wq, 0, sysctl_splice_num_wq, "IU",
364     "Number of splice worker queues");
365 
366 static uma_zone_t splice_zone;
367 static struct proc *splice_proc;
368 struct splice_wq {
369 	struct mtx	mtx;
370 	STAILQ_HEAD(, so_splice) head;
371 	bool		running;
372 } __aligned(CACHE_LINE_SIZE);
373 static struct splice_wq *splice_wq;
374 static uint32_t splice_index = 0;
375 
376 static void so_splice_timeout(void *arg, int pending);
377 static void so_splice_xfer(struct so_splice *s);
378 static int so_unsplice(struct socket *so, bool timeout);
379 
380 static void
splice_work_thread(void * ctx)381 splice_work_thread(void *ctx)
382 {
383 	struct splice_wq *wq = ctx;
384 	struct so_splice *s, *s_temp;
385 	STAILQ_HEAD(, so_splice) local_head;
386 	int cpu;
387 
388 	cpu = wq - splice_wq;
389 	if (bootverbose)
390 		printf("starting so_splice worker thread for CPU %d\n", cpu);
391 
392 	for (;;) {
393 		mtx_lock(&wq->mtx);
394 		while (STAILQ_EMPTY(&wq->head)) {
395 			wq->running = false;
396 			mtx_sleep(wq, &wq->mtx, 0, "-", 0);
397 			wq->running = true;
398 		}
399 		STAILQ_INIT(&local_head);
400 		STAILQ_CONCAT(&local_head, &wq->head);
401 		STAILQ_INIT(&wq->head);
402 		mtx_unlock(&wq->mtx);
403 		STAILQ_FOREACH_SAFE(s, &local_head, next, s_temp) {
404 			mtx_lock(&s->mtx);
405 			CURVNET_SET(s->src->so_vnet);
406 			so_splice_xfer(s);
407 			CURVNET_RESTORE();
408 		}
409 	}
410 }
411 
412 static void
so_splice_dispatch_async(struct so_splice * sp)413 so_splice_dispatch_async(struct so_splice *sp)
414 {
415 	struct splice_wq *wq;
416 	bool running;
417 
418 	wq = &splice_wq[sp->wq_index];
419 	mtx_lock(&wq->mtx);
420 	STAILQ_INSERT_TAIL(&wq->head, sp, next);
421 	running = wq->running;
422 	mtx_unlock(&wq->mtx);
423 	if (!running)
424 		wakeup(wq);
425 }
426 
427 void
so_splice_dispatch(struct so_splice * sp)428 so_splice_dispatch(struct so_splice *sp)
429 {
430 	mtx_assert(&sp->mtx, MA_OWNED);
431 
432 	if (sp->state != SPLICE_IDLE) {
433 		mtx_unlock(&sp->mtx);
434 	} else {
435 		sp->state = SPLICE_QUEUED;
436 		mtx_unlock(&sp->mtx);
437 		so_splice_dispatch_async(sp);
438 	}
439 }
440 
441 static int
splice_zinit(void * mem,int size __unused,int flags __unused)442 splice_zinit(void *mem, int size __unused, int flags __unused)
443 {
444 	struct so_splice *s;
445 
446 	s = (struct so_splice *)mem;
447 	mtx_init(&s->mtx, "so_splice", NULL, MTX_DEF);
448 	return (0);
449 }
450 
451 static void
splice_zfini(void * mem,int size)452 splice_zfini(void *mem, int size)
453 {
454 	struct so_splice *s;
455 
456 	s = (struct so_splice *)mem;
457 	mtx_destroy(&s->mtx);
458 }
459 
460 static int
splice_init(void)461 splice_init(void)
462 {
463 	struct thread *td;
464 	int error, i, state;
465 
466 	state = atomic_load_acq_int(&splice_init_state);
467 	if (__predict_true(state > 0))
468 		return (0);
469 	if (state < 0)
470 		return (ENXIO);
471 	sx_xlock(&splice_init_lock);
472 	if (splice_init_state != 0) {
473 		sx_xunlock(&splice_init_lock);
474 		return (0);
475 	}
476 
477 	if (splice_num_wq == -1) {
478 		/* if no user preference, use all cores */
479 		splice_num_wq = mp_ncpus;
480 	} else if (splice_num_wq == 0) {
481 		/* allow user to disable */
482 		splice_init_state = -1;
483 		sx_xunlock(&splice_init_lock);
484 		return (ENXIO);
485 	} else if (splice_num_wq > mp_ncpus) {
486 		splice_num_wq = mp_ncpus;
487 	}
488 
489 	splice_zone = uma_zcreate("splice", sizeof(struct so_splice), NULL,
490 	    NULL, splice_zinit, splice_zfini, UMA_ALIGN_CACHE, 0);
491 
492 	splice_wq = mallocarray(mp_ncpus, sizeof(*splice_wq), M_TEMP,
493 	    M_WAITOK | M_ZERO);
494 
495 	/*
496 	 * Initialize the workqueues to run the splice work.  We create a
497 	 * work queue for each CPU.
498 	 */
499 	for (i = 0; i < mp_ncpus; i++) {
500 		STAILQ_INIT(&splice_wq[i].head);
501 		mtx_init(&splice_wq[i].mtx, "splice work queue", NULL, MTX_DEF);
502 	}
503 
504 	/* Start kthreads for each workqueue. */
505 	error = 0;
506 	for (i = 0; i < mp_ncpus; i++) {
507 		error = kproc_kthread_add(splice_work_thread, &splice_wq[i],
508 		    &splice_proc, &td, 0, 0, "so_splice", "thr_%d", i);
509 		if (error) {
510 			printf("Can't add so_splice thread %d error %d\n",
511 			    i, error);
512 			break;
513 		}
514 
515 		/*
516 		 * It's possible to create loops with SO_SPLICE; ensure that
517 		 * worker threads aren't able to starve the system too easily.
518 		 */
519 		thread_lock(td);
520 		sched_prio(td, PUSER);
521 		thread_unlock(td);
522 	}
523 
524 	splice_init_state = error != 0 ? -1 : 1;
525 	sx_xunlock(&splice_init_lock);
526 
527 	return (error);
528 }
529 
530 /*
531  * Lock a pair of socket's I/O locks for splicing.  Avoid blocking while holding
532  * one lock in order to avoid potential deadlocks in case there is some other
533  * code path which acquires more than one I/O lock at a time.
534  */
535 static void
splice_lock_pair(struct socket * so_src,struct socket * so_dst)536 splice_lock_pair(struct socket *so_src, struct socket *so_dst)
537 {
538 	int error;
539 
540 	for (;;) {
541 		error = SOCK_IO_SEND_LOCK(so_dst, SBL_WAIT | SBL_NOINTR);
542 		KASSERT(error == 0,
543 		    ("%s: failed to lock send I/O lock: %d", __func__, error));
544 		error = SOCK_IO_RECV_LOCK(so_src, 0);
545 		KASSERT(error == 0 || error == EWOULDBLOCK,
546 		    ("%s: failed to lock recv I/O lock: %d", __func__, error));
547 		if (error == 0)
548 			break;
549 		SOCK_IO_SEND_UNLOCK(so_dst);
550 
551 		error = SOCK_IO_RECV_LOCK(so_src, SBL_WAIT | SBL_NOINTR);
552 		KASSERT(error == 0,
553 		    ("%s: failed to lock recv I/O lock: %d", __func__, error));
554 		error = SOCK_IO_SEND_LOCK(so_dst, 0);
555 		KASSERT(error == 0 || error == EWOULDBLOCK,
556 		    ("%s: failed to lock send I/O lock: %d", __func__, error));
557 		if (error == 0)
558 			break;
559 		SOCK_IO_RECV_UNLOCK(so_src);
560 	}
561 }
562 
563 static void
splice_unlock_pair(struct socket * so_src,struct socket * so_dst)564 splice_unlock_pair(struct socket *so_src, struct socket *so_dst)
565 {
566 	SOCK_IO_RECV_UNLOCK(so_src);
567 	SOCK_IO_SEND_UNLOCK(so_dst);
568 }
569 
570 /*
571  * Move data from the source to the sink.  Assumes that both of the relevant
572  * socket I/O locks are held.
573  */
574 static int
so_splice_xfer_data(struct socket * so_src,struct socket * so_dst,off_t max,ssize_t * lenp)575 so_splice_xfer_data(struct socket *so_src, struct socket *so_dst, off_t max,
576     ssize_t *lenp)
577 {
578 	struct uio uio;
579 	struct mbuf *m;
580 	struct sockbuf *sb_src, *sb_dst;
581 	ssize_t len;
582 	long space;
583 	int error, flags;
584 
585 	SOCK_IO_RECV_ASSERT_LOCKED(so_src);
586 	SOCK_IO_SEND_ASSERT_LOCKED(so_dst);
587 
588 	error = 0;
589 	m = NULL;
590 	memset(&uio, 0, sizeof(uio));
591 
592 	sb_src = &so_src->so_rcv;
593 	sb_dst = &so_dst->so_snd;
594 
595 	space = sbspace(sb_dst);
596 	if (space < 0)
597 		space = 0;
598 	len = MIN(max, MIN(space, sbavail(sb_src)));
599 	if (len == 0) {
600 		SOCK_RECVBUF_LOCK(so_src);
601 		if ((sb_src->sb_state & SBS_CANTRCVMORE) != 0)
602 			error = EPIPE;
603 		SOCK_RECVBUF_UNLOCK(so_src);
604 	} else {
605 		flags = MSG_DONTWAIT;
606 		uio.uio_resid = len;
607 		if (splice_receive_stream && sb_src->sb_tls_info == NULL) {
608 			error = soreceive_stream_locked(so_src, sb_src, NULL,
609 			    &uio, &m, NULL, flags);
610 		} else {
611 			error = soreceive_generic_locked(so_src, NULL,
612 			    &uio, &m, NULL, &flags);
613 		}
614 		if (error != 0 && m != NULL) {
615 			m_freem(m);
616 			m = NULL;
617 		}
618 	}
619 	if (m != NULL) {
620 		len -= uio.uio_resid;
621 		error = sosend_generic_locked(so_dst, NULL, NULL, m, NULL,
622 		    MSG_DONTWAIT, curthread);
623 	} else if (error == 0) {
624 		len = 0;
625 		SOCK_SENDBUF_LOCK(so_dst);
626 		if ((sb_dst->sb_state & SBS_CANTSENDMORE) != 0)
627 			error = EPIPE;
628 		SOCK_SENDBUF_UNLOCK(so_dst);
629 	}
630 	if (error == 0)
631 		*lenp = len;
632 	return (error);
633 }
634 
635 /*
636  * Transfer data from the source to the sink.
637  */
638 static void
so_splice_xfer(struct so_splice * sp)639 so_splice_xfer(struct so_splice *sp)
640 {
641 	struct socket *so_src, *so_dst;
642 	off_t max;
643 	ssize_t len;
644 	int error;
645 
646 	mtx_assert(&sp->mtx, MA_OWNED);
647 	KASSERT(sp->state == SPLICE_QUEUED || sp->state == SPLICE_CLOSING,
648 	    ("so_splice_xfer: invalid state %d", sp->state));
649 	KASSERT(sp->max != 0, ("so_splice_xfer: max == 0"));
650 
651 	if (sp->state == SPLICE_CLOSING) {
652 		/* Userspace asked us to close the splice. */
653 		goto closing;
654 	}
655 
656 	sp->state = SPLICE_RUNNING;
657 	so_src = sp->src;
658 	so_dst = sp->dst;
659 	max = sp->max > 0 ? sp->max - so_src->so_splice_sent : OFF_MAX;
660 	if (max < 0)
661 		max = 0;
662 
663 	/*
664 	 * Lock the sockets in order to block userspace from doing anything
665 	 * sneaky.  If an error occurs or one of the sockets can no longer
666 	 * transfer data, we will automatically unsplice.
667 	 */
668 	mtx_unlock(&sp->mtx);
669 	splice_lock_pair(so_src, so_dst);
670 
671 	error = so_splice_xfer_data(so_src, so_dst, max, &len);
672 
673 	mtx_lock(&sp->mtx);
674 
675 	/*
676 	 * Update our stats while still holding the socket locks.  This
677 	 * synchronizes with getsockopt(SO_SPLICE), see the comment there.
678 	 */
679 	if (error == 0) {
680 		KASSERT(len >= 0, ("%s: len %zd < 0", __func__, len));
681 		so_src->so_splice_sent += len;
682 	}
683 	splice_unlock_pair(so_src, so_dst);
684 
685 	switch (sp->state) {
686 	case SPLICE_CLOSING:
687 closing:
688 		sp->state = SPLICE_CLOSED;
689 		wakeup(sp);
690 		mtx_unlock(&sp->mtx);
691 		break;
692 	case SPLICE_RUNNING:
693 		if (error != 0 ||
694 		    (sp->max > 0 && so_src->so_splice_sent >= sp->max)) {
695 			sp->state = SPLICE_EXCEPTION;
696 			soref(so_src);
697 			mtx_unlock(&sp->mtx);
698 			(void)so_unsplice(so_src, false);
699 			sorele(so_src);
700 		} else {
701 			/*
702 			 * Locklessly check for additional bytes in the source's
703 			 * receive buffer and queue more work if possible.  We
704 			 * may end up queuing needless work, but that's ok, and
705 			 * if we race with a thread inserting more data into the
706 			 * buffer and observe sbavail() == 0, the splice mutex
707 			 * ensures that splice_push() will queue more work for
708 			 * us.
709 			 */
710 			if (sbavail(&so_src->so_rcv) > 0 &&
711 			    sbspace(&so_dst->so_snd) > 0) {
712 				sp->state = SPLICE_QUEUED;
713 				mtx_unlock(&sp->mtx);
714 				so_splice_dispatch_async(sp);
715 			} else {
716 				sp->state = SPLICE_IDLE;
717 				mtx_unlock(&sp->mtx);
718 			}
719 		}
720 		break;
721 	default:
722 		__assert_unreachable();
723 	}
724 }
725 
726 static void
socket_init(void * tag)727 socket_init(void *tag)
728 {
729 
730 	socket_zone = uma_zcreate("socket", sizeof(struct socket), NULL, NULL,
731 	    NULL, NULL, UMA_ALIGN_PTR, 0);
732 	maxsockets = uma_zone_set_max(socket_zone, maxsockets);
733 	uma_zone_set_warning(socket_zone, "kern.ipc.maxsockets limit reached");
734 	EVENTHANDLER_REGISTER(maxsockets_change, socket_zone_change, NULL,
735 	    EVENTHANDLER_PRI_FIRST);
736 }
737 SYSINIT(socket, SI_SUB_PROTO_DOMAININIT, SI_ORDER_ANY, socket_init, NULL);
738 
739 #ifdef SOCKET_HHOOK
740 static void
socket_hhook_register(int subtype)741 socket_hhook_register(int subtype)
742 {
743 
744 	if (hhook_head_register(HHOOK_TYPE_SOCKET, subtype,
745 	    &V_socket_hhh[subtype],
746 	    HHOOK_NOWAIT|HHOOK_HEADISINVNET) != 0)
747 		printf("%s: WARNING: unable to register hook\n", __func__);
748 }
749 
750 static void
socket_hhook_deregister(int subtype)751 socket_hhook_deregister(int subtype)
752 {
753 
754 	if (hhook_head_deregister(V_socket_hhh[subtype]) != 0)
755 		printf("%s: WARNING: unable to deregister hook\n", __func__);
756 }
757 
758 static void
socket_vnet_init(const void * unused __unused)759 socket_vnet_init(const void *unused __unused)
760 {
761 	int i;
762 
763 	/* We expect a contiguous range */
764 	for (i = 0; i <= HHOOK_SOCKET_LAST; i++)
765 		socket_hhook_register(i);
766 }
767 VNET_SYSINIT(socket_vnet_init, SI_SUB_PROTO_DOMAININIT, SI_ORDER_ANY,
768     socket_vnet_init, NULL);
769 
770 static void
socket_vnet_uninit(const void * unused __unused)771 socket_vnet_uninit(const void *unused __unused)
772 {
773 	int i;
774 
775 	for (i = 0; i <= HHOOK_SOCKET_LAST; i++)
776 		socket_hhook_deregister(i);
777 }
778 VNET_SYSUNINIT(socket_vnet_uninit, SI_SUB_PROTO_DOMAININIT, SI_ORDER_ANY,
779     socket_vnet_uninit, NULL);
780 #endif	/* SOCKET_HHOOK */
781 
782 /*
783  * Initialise maxsockets.  This SYSINIT must be run after
784  * tunable_mbinit().
785  */
786 static void
init_maxsockets(void * ignored)787 init_maxsockets(void *ignored)
788 {
789 
790 	TUNABLE_INT_FETCH("kern.ipc.maxsockets", &maxsockets);
791 	maxsockets = imax(maxsockets, maxfiles);
792 }
793 SYSINIT(param, SI_SUB_TUNABLES, SI_ORDER_ANY, init_maxsockets, NULL);
794 
795 /*
796  * Sysctl to get and set the maximum global sockets limit.  Notify protocols
797  * of the change so that they can update their dependent limits as required.
798  */
799 static int
sysctl_maxsockets(SYSCTL_HANDLER_ARGS)800 sysctl_maxsockets(SYSCTL_HANDLER_ARGS)
801 {
802 	int error, newmaxsockets;
803 
804 	newmaxsockets = maxsockets;
805 	error = sysctl_handle_int(oidp, &newmaxsockets, 0, req);
806 	if (error == 0 && req->newptr && newmaxsockets != maxsockets) {
807 		if (newmaxsockets > maxsockets &&
808 		    newmaxsockets <= maxfiles) {
809 			maxsockets = newmaxsockets;
810 			EVENTHANDLER_INVOKE(maxsockets_change);
811 		} else
812 			error = EINVAL;
813 	}
814 	return (error);
815 }
816 SYSCTL_PROC(_kern_ipc, OID_AUTO, maxsockets,
817     CTLTYPE_INT | CTLFLAG_RWTUN | CTLFLAG_NOFETCH | CTLFLAG_MPSAFE,
818     &maxsockets, 0, sysctl_maxsockets, "IU",
819     "Maximum number of sockets available");
820 
821 /*
822  * Socket operation routines.  These routines are called by the routines in
823  * sys_socket.c or from a system process, and implement the semantics of
824  * socket operations by switching out to the protocol specific routines.
825  */
826 
827 /*
828  * Get a socket structure from our zone, and initialize it.  Note that it
829  * would probably be better to allocate socket and PCB at the same time, but
830  * I'm not convinced that all the protocols can be easily modified to do
831  * this.
832  *
833  * soalloc() returns a socket with a ref count of 0.
834  */
835 static struct socket *
soalloc(struct vnet * vnet)836 soalloc(struct vnet *vnet)
837 {
838 	struct socket *so;
839 
840 	so = uma_zalloc(socket_zone, M_NOWAIT | M_ZERO);
841 	if (so == NULL)
842 		return (NULL);
843 #ifdef MAC
844 	if (mac_socket_init(so, M_NOWAIT) != 0) {
845 		uma_zfree(socket_zone, so);
846 		return (NULL);
847 	}
848 #endif
849 	if (khelp_init_osd(HELPER_CLASS_SOCKET, &so->osd)) {
850 		uma_zfree(socket_zone, so);
851 		return (NULL);
852 	}
853 
854 	/*
855 	 * The socket locking protocol allows to lock 2 sockets at a time,
856 	 * however, the first one must be a listening socket.  WITNESS lacks
857 	 * a feature to change class of an existing lock, so we use DUPOK.
858 	 */
859 	mtx_init(&so->so_lock, "socket", NULL, MTX_DEF | MTX_DUPOK);
860 	so->so_rcv.sb_sel = &so->so_rdsel;
861 	so->so_snd.sb_sel = &so->so_wrsel;
862 	sx_init(&so->so_snd_sx, "so_snd_sx");
863 	sx_init(&so->so_rcv_sx, "so_rcv_sx");
864 	TAILQ_INIT(&so->so_snd.sb_aiojobq);
865 	TAILQ_INIT(&so->so_rcv.sb_aiojobq);
866 	TASK_INIT(&so->so_snd.sb_aiotask, 0, soaio_snd, so);
867 	TASK_INIT(&so->so_rcv.sb_aiotask, 0, soaio_rcv, so);
868 #ifdef VIMAGE
869 	VNET_ASSERT(vnet != NULL, ("%s:%d vnet is NULL, so=%p",
870 	    __func__, __LINE__, so));
871 	so->so_vnet = vnet;
872 #endif
873 #ifdef SOCKET_HHOOK
874 	/* We shouldn't need the so_global_mtx */
875 	if (hhook_run_socket(so, NULL, HHOOK_SOCKET_CREATE)) {
876 		/* Do we need more comprehensive error returns? */
877 		uma_zfree(socket_zone, so);
878 		return (NULL);
879 	}
880 #endif
881 	mtx_lock(&so_global_mtx);
882 	so->so_gencnt = ++so_gencnt;
883 	++numopensockets;
884 #ifdef VIMAGE
885 	vnet->vnet_sockcnt++;
886 #endif
887 	mtx_unlock(&so_global_mtx);
888 
889 	return (so);
890 }
891 
892 /*
893  * Free the storage associated with a socket at the socket layer, tear down
894  * locks, labels, etc.  All protocol state is assumed already to have been
895  * torn down (and possibly never set up) by the caller.
896  */
897 void
sodealloc(struct socket * so)898 sodealloc(struct socket *so)
899 {
900 
901 	KASSERT(so->so_count == 0, ("sodealloc(): so_count %d", so->so_count));
902 	KASSERT(so->so_pcb == NULL, ("sodealloc(): so_pcb != NULL"));
903 
904 	mtx_lock(&so_global_mtx);
905 	so->so_gencnt = ++so_gencnt;
906 	--numopensockets;	/* Could be below, but faster here. */
907 #ifdef VIMAGE
908 	VNET_ASSERT(so->so_vnet != NULL, ("%s:%d so_vnet is NULL, so=%p",
909 	    __func__, __LINE__, so));
910 	so->so_vnet->vnet_sockcnt--;
911 #endif
912 	mtx_unlock(&so_global_mtx);
913 #ifdef MAC
914 	mac_socket_destroy(so);
915 #endif
916 #ifdef SOCKET_HHOOK
917 	hhook_run_socket(so, NULL, HHOOK_SOCKET_CLOSE);
918 #endif
919 
920 	khelp_destroy_osd(&so->osd);
921 	if (SOLISTENING(so)) {
922 		if (so->sol_accept_filter != NULL)
923 			accept_filt_setopt(so, NULL);
924 	} else {
925 		if (so->so_rcv.sb_hiwat)
926 			(void)chgsbsize(so->so_cred->cr_uidinfo,
927 			    &so->so_rcv.sb_hiwat, 0, RLIM_INFINITY);
928 		if (so->so_snd.sb_hiwat)
929 			(void)chgsbsize(so->so_cred->cr_uidinfo,
930 			    &so->so_snd.sb_hiwat, 0, RLIM_INFINITY);
931 		sx_destroy(&so->so_snd_sx);
932 		sx_destroy(&so->so_rcv_sx);
933 	}
934 	crfree(so->so_cred);
935 	mtx_destroy(&so->so_lock);
936 	uma_zfree(socket_zone, so);
937 }
938 
939 /*
940  * Shim to accomodate protocols that already do their own socket buffers
941  * management (marked with PR_SOCKBUF) with protocols that yet do not.
942  *
943  * Attach via socket(2) is different from attach via accept(2).  In case of
944  * normal socket(2) syscall it is the pr_attach that calls soreserve(), even
945  * for protocols that don't yet do PR_SOCKBUF.  In case of accepted connection
946  * it is our shim that calls soreserve() and the hiwat values are taken from
947  * the parent socket.  The SCTP's sopeeloff() hands us a non-listening parent
948  * socket.
949  *
950  * This whole shim should go away when all major protocols fully manage their
951  * socket buffers.
952  */
953 static int
soattach(struct socket * so,int proto,struct thread * td,struct socket * head)954 soattach(struct socket *so, int proto, struct thread *td, struct socket *head)
955 {
956 	int error;
957 
958 	VNET_ASSERT(curvnet == so->so_vnet,
959 	    ("%s: %p != %p", __func__, curvnet,  so->so_vnet));
960 
961 	if ((so->so_proto->pr_flags & PR_SOCKBUF) == 0) {
962 		mtx_init(&so->so_snd_mtx, "so_snd", NULL, MTX_DEF);
963 		mtx_init(&so->so_rcv_mtx, "so_rcv", NULL, MTX_DEF);
964 		so->so_snd.sb_mtx = &so->so_snd_mtx;
965 		so->so_rcv.sb_mtx = &so->so_rcv_mtx;
966 	}
967 	if (head == NULL || (error = soreserve(so,
968 	    SOLISTENING(head) ? head->sol_sbsnd_hiwat : head->so_snd.sb_hiwat,
969 	    SOLISTENING(head) ? head->sol_sbrcv_hiwat : head->so_rcv.sb_hiwat))
970 	    == 0)
971 		error = so->so_proto->pr_attach(so, proto, td);
972 	if (error != 0 && (so->so_proto->pr_flags & PR_SOCKBUF) == 0) {
973 		mtx_destroy(&so->so_snd_mtx);
974 		mtx_destroy(&so->so_rcv_mtx);
975 	}
976 
977 	return (error);
978 }
979 
980 /*
981  * socreate returns a socket with a ref count of 1 and a file descriptor
982  * reference.  The socket should be closed with soclose().
983  */
984 int
socreate(int dom,struct socket ** aso,int type,int proto,struct ucred * cred,struct thread * td)985 socreate(int dom, struct socket **aso, int type, int proto,
986     struct ucred *cred, struct thread *td)
987 {
988 	struct protosw *prp;
989 	struct socket *so;
990 	int error;
991 
992 #ifdef COMPAT_FREEBSD15
993 	/* divert(4) historically abuses PF_INET.  Use PF_DIVERT instead. */
994 	if (__predict_false(dom == PF_INET && type == SOCK_RAW &&
995 	    proto == __IPPROTO_DIVERT))
996 		dom = PF_DIVERT;
997 #endif
998 
999 	prp = pffindproto(dom, type, proto);
1000 	if (prp == NULL) {
1001 		/* No support for domain. */
1002 		if (pffinddomain(dom) == NULL)
1003 			return (EAFNOSUPPORT);
1004 		/* No support for socket type. */
1005 		if (proto == 0 && type != 0)
1006 			return (EPROTOTYPE);
1007 		return (EPROTONOSUPPORT);
1008 	}
1009 
1010 	MPASS(prp->pr_attach);
1011 
1012 	if ((prp->pr_flags & PR_CAPATTACH) == 0) {
1013 		if (CAP_TRACING(td))
1014 			ktrcapfail(CAPFAIL_PROTO, &proto);
1015 		if (IN_CAPABILITY_MODE(td))
1016 			return (ECAPMODE);
1017 	}
1018 
1019 	if (prison_check_af(cred, prp->pr_domain->dom_family) != 0)
1020 		return (EPROTONOSUPPORT);
1021 
1022 	so = soalloc(CRED_TO_VNET(cred));
1023 	if (so == NULL)
1024 		return (ENOBUFS);
1025 
1026 	so->so_type = type;
1027 	so->so_cred = crhold(cred);
1028 	if ((prp->pr_domain->dom_family == PF_INET) ||
1029 	    (prp->pr_domain->dom_family == PF_INET6) ||
1030 	    (prp->pr_domain->dom_family == PF_ROUTE))
1031 		so->so_fibnum = td->td_proc->p_fibnum;
1032 	else
1033 		so->so_fibnum = 0;
1034 	so->so_proto = prp;
1035 #ifdef MAC
1036 	mac_socket_create(cred, so);
1037 #endif
1038 	knlist_init(&so->so_rdsel.si_note, so, so_rdknl_lock, so_rdknl_unlock,
1039 	    so_rdknl_assert_lock);
1040 	knlist_init(&so->so_wrsel.si_note, so, so_wrknl_lock, so_wrknl_unlock,
1041 	    so_wrknl_assert_lock);
1042 	CURVNET_SET(so->so_vnet);
1043 	error = soattach(so, proto, td, NULL);
1044 	CURVNET_RESTORE();
1045 	if (error) {
1046 		sodealloc(so);
1047 		return (error);
1048 	}
1049 	soref(so);
1050 	*aso = so;
1051 	return (0);
1052 }
1053 
1054 #ifdef REGRESSION
1055 static int regression_sonewconn_earlytest = 1;
1056 SYSCTL_INT(_regression, OID_AUTO, sonewconn_earlytest, CTLFLAG_RW,
1057     &regression_sonewconn_earlytest, 0, "Perform early sonewconn limit test");
1058 #endif
1059 
1060 static int sooverprio = LOG_DEBUG;
1061 SYSCTL_INT(_kern_ipc, OID_AUTO, sooverprio, CTLFLAG_RW,
1062     &sooverprio, 0, "Log priority for listen socket overflows: 0..7 or -1 to disable");
1063 
1064 static struct timeval overinterval = { 60, 0 };
1065 SYSCTL_TIMEVAL_SEC(_kern_ipc, OID_AUTO, sooverinterval, CTLFLAG_RW,
1066     &overinterval,
1067     "Delay in seconds between warnings for listen socket overflows");
1068 
1069 /*
1070  * When an attempt at a new connection is noted on a socket which supports
1071  * accept(2), the protocol has two options:
1072  * 1) Call legacy sonewconn() function, which would call protocol attach
1073  *    method, same as used for socket(2).
1074  * 2) Call solisten_clone(), do attach that is specific to a cloned connection,
1075  *    and then call solisten_enqueue().
1076  *
1077  * Note: the ref count on the socket is 0 on return.
1078  */
1079 struct socket *
solisten_clone(struct socket * head)1080 solisten_clone(struct socket *head)
1081 {
1082 	struct sbuf descrsb;
1083 	struct socket *so;
1084 	int len, overcount;
1085 	u_int qlen;
1086 	const char localprefix[] = "local:";
1087 	char descrbuf[SUNPATHLEN + sizeof(localprefix)];
1088 #if defined(INET6)
1089 	char addrbuf[INET6_ADDRSTRLEN];
1090 #elif defined(INET)
1091 	char addrbuf[INET_ADDRSTRLEN];
1092 #endif
1093 	bool dolog, over;
1094 
1095 	SOLISTEN_LOCK(head);
1096 	over = (head->sol_qlen > 3 * head->sol_qlimit / 2);
1097 #ifdef REGRESSION
1098 	if (regression_sonewconn_earlytest && over) {
1099 #else
1100 	if (over) {
1101 #endif
1102 		head->sol_overcount++;
1103 		dolog = (sooverprio >= 0) &&
1104 			!!ratecheck(&head->sol_lastover, &overinterval);
1105 
1106 		/*
1107 		 * If we're going to log, copy the overflow count and queue
1108 		 * length from the listen socket before dropping the lock.
1109 		 * Also, reset the overflow count.
1110 		 */
1111 		if (dolog) {
1112 			overcount = head->sol_overcount;
1113 			head->sol_overcount = 0;
1114 			qlen = head->sol_qlen;
1115 		}
1116 		SOLISTEN_UNLOCK(head);
1117 
1118 		if (dolog) {
1119 			/*
1120 			 * Try to print something descriptive about the
1121 			 * socket for the error message.
1122 			 */
1123 			sbuf_new(&descrsb, descrbuf, sizeof(descrbuf),
1124 			    SBUF_FIXEDLEN);
1125 			switch (head->so_proto->pr_domain->dom_family) {
1126 #if defined(INET) || defined(INET6)
1127 #ifdef INET
1128 			case AF_INET:
1129 #endif
1130 #ifdef INET6
1131 			case AF_INET6:
1132 				if (head->so_proto->pr_domain->dom_family ==
1133 				    AF_INET6 ||
1134 				    (sotoinpcb(head)->inp_inc.inc_flags &
1135 				    INC_ISIPV6)) {
1136 					ip6_sprintf(addrbuf,
1137 					    &sotoinpcb(head)->inp_inc.inc6_laddr);
1138 					sbuf_printf(&descrsb, "[%s]", addrbuf);
1139 				} else
1140 #endif
1141 				{
1142 #ifdef INET
1143 					inet_ntoa_r(
1144 					    sotoinpcb(head)->inp_inc.inc_laddr,
1145 					    addrbuf);
1146 					sbuf_cat(&descrsb, addrbuf);
1147 #endif
1148 				}
1149 				sbuf_printf(&descrsb, ":%hu (proto %u)",
1150 				    ntohs(sotoinpcb(head)->inp_inc.inc_lport),
1151 				    head->so_proto->pr_protocol);
1152 				break;
1153 #endif /* INET || INET6 */
1154 			case AF_UNIX:
1155 				sbuf_cat(&descrsb, localprefix);
1156 				if (sotounpcb(head)->unp_addr != NULL)
1157 					len =
1158 					    sotounpcb(head)->unp_addr->sun_len -
1159 					    offsetof(struct sockaddr_un,
1160 					    sun_path);
1161 				else
1162 					len = 0;
1163 				if (len > 0)
1164 					sbuf_bcat(&descrsb,
1165 					    sotounpcb(head)->unp_addr->sun_path,
1166 					    len);
1167 				else
1168 					sbuf_cat(&descrsb, "(unknown)");
1169 				break;
1170 			}
1171 
1172 			/*
1173 			 * If we can't print something more specific, at least
1174 			 * print the domain name.
1175 			 */
1176 			if (sbuf_finish(&descrsb) != 0 ||
1177 			    sbuf_len(&descrsb) <= 0) {
1178 				sbuf_clear(&descrsb);
1179 				sbuf_cat(&descrsb,
1180 				    head->so_proto->pr_domain->dom_name ?:
1181 				    "unknown");
1182 				sbuf_finish(&descrsb);
1183 			}
1184 			KASSERT(sbuf_len(&descrsb) > 0,
1185 			    ("%s: sbuf creation failed", __func__));
1186 			/*
1187 			 * Preserve the historic listen queue overflow log
1188 			 * message, that starts with "sonewconn:".  It has
1189 			 * been known to sysadmins for years and also test
1190 			 * sys/kern/sonewconn_overflow checks for it.
1191 			 */
1192 			if (head->so_cred == 0) {
1193 				log(LOG_PRI(sooverprio),
1194 				    "sonewconn: pcb %p (%s): "
1195 				    "Listen queue overflow: %i already in "
1196 				    "queue awaiting acceptance (%d "
1197 				    "occurrences)\n", head->so_pcb,
1198 				    sbuf_data(&descrsb),
1199 			    	qlen, overcount);
1200 			} else {
1201 				log(LOG_PRI(sooverprio),
1202 				    "sonewconn: pcb %p (%s): "
1203 				    "Listen queue overflow: "
1204 				    "%i already in queue awaiting acceptance "
1205 				    "(%d occurrences), euid %d, rgid %d, jail %s\n",
1206 				    head->so_pcb, sbuf_data(&descrsb), qlen,
1207 				    overcount, head->so_cred->cr_uid,
1208 				    head->so_cred->cr_rgid,
1209 				    head->so_cred->cr_prison ?
1210 					head->so_cred->cr_prison->pr_name :
1211 					"not_jailed");
1212 			}
1213 			sbuf_delete(&descrsb);
1214 
1215 			overcount = 0;
1216 		}
1217 
1218 		return (NULL);
1219 	}
1220 	SOLISTEN_UNLOCK(head);
1221 	VNET_ASSERT(head->so_vnet != NULL, ("%s: so %p vnet is NULL",
1222 	    __func__, head));
1223 	so = soalloc(head->so_vnet);
1224 	if (so == NULL) {
1225 		log(LOG_DEBUG, "%s: pcb %p: New socket allocation failure: "
1226 		    "limit reached or out of memory\n",
1227 		    __func__, head->so_pcb);
1228 		return (NULL);
1229 	}
1230 	so->so_listen = head;
1231 	so->so_type = head->so_type;
1232 	/*
1233 	 * POSIX is ambiguous on what options an accept(2)ed socket should
1234 	 * inherit from the listener.  Words "create a new socket" may be
1235 	 * interpreted as not inheriting anything.  Best programming practice
1236 	 * for application developers is to not rely on such inheritance.
1237 	 * FreeBSD had historically inherited all so_options excluding
1238 	 * SO_ACCEPTCONN, which virtually means all SOL_SOCKET level options,
1239 	 * including those completely irrelevant to a new born socket.  For
1240 	 * compatibility with older versions we will inherit a list of
1241 	 * meaningful options.
1242 	 * The crucial bit to inherit is SO_ACCEPTFILTER.  We need it present
1243 	 * in the child socket for soisconnected() promoting socket from the
1244 	 * incomplete queue to complete.  It will be cleared before the child
1245 	 * gets available to accept(2).
1246 	 */
1247 	so->so_options = head->so_options & (SO_ACCEPTFILTER | SO_KEEPALIVE |
1248 	    SO_DONTROUTE | SO_LINGER | SO_OOBINLINE | SO_NOSIGPIPE);
1249 	so->so_linger = head->so_linger;
1250 	so->so_state = head->so_state;
1251 	so->so_fibnum = head->so_fibnum;
1252 	so->so_proto = head->so_proto;
1253 	so->so_cred = crhold(head->so_cred);
1254 #ifdef SOCKET_HHOOK
1255 	if (V_socket_hhh[HHOOK_SOCKET_NEWCONN]->hhh_nhooks > 0) {
1256 		if (hhook_run_socket(so, head, HHOOK_SOCKET_NEWCONN)) {
1257 			sodealloc(so);
1258 			log(LOG_DEBUG, "%s: hhook run failed\n", __func__);
1259 			return (NULL);
1260 		}
1261 	}
1262 #endif
1263 #ifdef MAC
1264 	mac_socket_newconn(head, so);
1265 #endif
1266 	knlist_init(&so->so_rdsel.si_note, so, so_rdknl_lock, so_rdknl_unlock,
1267 	    so_rdknl_assert_lock);
1268 	knlist_init(&so->so_wrsel.si_note, so, so_wrknl_lock, so_wrknl_unlock,
1269 	    so_wrknl_assert_lock);
1270 	so->so_rcv.sb_lowat = head->sol_sbrcv_lowat;
1271 	so->so_snd.sb_lowat = head->sol_sbsnd_lowat;
1272 	so->so_rcv.sb_timeo = head->sol_sbrcv_timeo;
1273 	so->so_snd.sb_timeo = head->sol_sbsnd_timeo;
1274 	so->so_rcv.sb_flags = head->sol_sbrcv_flags & SB_AUTOSIZE;
1275 	so->so_snd.sb_flags = head->sol_sbsnd_flags &
1276 	    (SB_AUTOSIZE | SB_AUTOLOWAT);
1277 
1278 	return (so);
1279 }
1280 
1281 /* Connstatus may be 0 or SS_ISCONNECTED. */
1282 struct socket *
1283 sonewconn(struct socket *head, int connstatus)
1284 {
1285 	struct socket *so;
1286 
1287 	if ((so = solisten_clone(head)) == NULL)
1288 		return (NULL);
1289 
1290 	if (soattach(so, 0, NULL, head) != 0) {
1291 		sodealloc(so);
1292 		log(LOG_DEBUG, "%s: pcb %p: pr_attach() failed\n",
1293 		    __func__, head->so_pcb);
1294 		return (NULL);
1295 	}
1296 
1297 	(void)solisten_enqueue(so, connstatus);
1298 
1299 	return (so);
1300 }
1301 
1302 /*
1303  * Enqueue socket cloned by solisten_clone() to the listen queue of the
1304  * listener it has been cloned from.
1305  *
1306  * Return 'true' if socket landed on complete queue, otherwise 'false'.
1307  */
1308 bool
1309 solisten_enqueue(struct socket *so, int connstatus)
1310 {
1311 	struct socket *head = so->so_listen;
1312 
1313 	MPASS(refcount_load(&so->so_count) == 0);
1314 	refcount_init(&so->so_count, 1);
1315 
1316 	SOLISTEN_LOCK(head);
1317 	if (head->sol_accept_filter != NULL)
1318 		connstatus = 0;
1319 	so->so_state |= connstatus;
1320 	soref(head); /* A socket on (in)complete queue refs head. */
1321 	if (connstatus) {
1322 		TAILQ_INSERT_TAIL(&head->sol_comp, so, so_list);
1323 		so->so_qstate = SQ_COMP;
1324 		head->sol_qlen++;
1325 		solisten_wakeup(head);	/* unlocks */
1326 		return (true);
1327 	} else {
1328 		/*
1329 		 * Keep removing sockets from the head until there's room for
1330 		 * us to insert on the tail.  In pre-locking revisions, this
1331 		 * was a simple if(), but as we could be racing with other
1332 		 * threads and soabort() requires dropping locks, we must
1333 		 * loop waiting for the condition to be true.
1334 		 */
1335 		while (head->sol_incqlen > head->sol_qlimit) {
1336 			struct socket *sp;
1337 
1338 			sp = TAILQ_FIRST(&head->sol_incomp);
1339 			TAILQ_REMOVE(&head->sol_incomp, sp, so_list);
1340 			head->sol_incqlen--;
1341 			SOCK_LOCK(sp);
1342 			sp->so_qstate = SQ_NONE;
1343 			sp->so_listen = NULL;
1344 			SOCK_UNLOCK(sp);
1345 			sorele_locked(head);	/* does SOLISTEN_UNLOCK, head stays */
1346 			soabort(sp);
1347 			SOLISTEN_LOCK(head);
1348 		}
1349 		TAILQ_INSERT_TAIL(&head->sol_incomp, so, so_list);
1350 		so->so_qstate = SQ_INCOMP;
1351 		head->sol_incqlen++;
1352 		SOLISTEN_UNLOCK(head);
1353 		return (false);
1354 	}
1355 }
1356 
1357 #if defined(SCTP) || defined(SCTP_SUPPORT)
1358 /*
1359  * Socket part of sctp_peeloff().  Create a new socket for an
1360  * association.  The new socket is returned with a reference.
1361  *
1362  * XXXGL: reduce copy-paste with solisten_clone().
1363  */
1364 struct socket *
1365 sopeeloff(struct socket *head, struct protosw *so_proto)
1366 {
1367 	struct socket *so;
1368 
1369 	VNET_ASSERT(head->so_vnet != NULL, ("%s:%d so_vnet is NULL, head=%p",
1370 	    __func__, __LINE__, head));
1371 	KASSERT(head->so_type == SOCK_SEQPACKET,
1372 	    ("%s: unexpecte so_type: %d", __func__, head->so_type));
1373 	so = soalloc(head->so_vnet);
1374 	if (so == NULL) {
1375 		log(LOG_DEBUG, "%s: pcb %p: New socket allocation failure: "
1376 		    "limit reached or out of memory\n",
1377 		    __func__, head->so_pcb);
1378 		return (NULL);
1379 	}
1380 	so->so_type = SOCK_STREAM;
1381 	so->so_options = head->so_options;
1382 	so->so_linger = head->so_linger;
1383 	so->so_state = (head->so_state & SS_NBIO) | SS_ISCONNECTED;
1384 	so->so_fibnum = head->so_fibnum;
1385 	so->so_proto = so_proto;
1386 	so->so_cred = crhold(head->so_cred);
1387 #ifdef MAC
1388 	mac_socket_newconn(head, so);
1389 #endif
1390 	knlist_init(&so->so_rdsel.si_note, so, so_rdknl_lock, so_rdknl_unlock,
1391 	    so_rdknl_assert_lock);
1392 	knlist_init(&so->so_wrsel.si_note, so, so_wrknl_lock, so_wrknl_unlock,
1393 	    so_wrknl_assert_lock);
1394 	if (soattach(so, 0, NULL, head)) {
1395 		sodealloc(so);
1396 		log(LOG_DEBUG, "%s: pcb %p: pr_attach() failed\n",
1397 		    __func__, head->so_pcb);
1398 		return (NULL);
1399 	}
1400 	so->so_rcv.sb_lowat = head->so_rcv.sb_lowat;
1401 	so->so_snd.sb_lowat = head->so_snd.sb_lowat;
1402 	so->so_rcv.sb_timeo = head->so_rcv.sb_timeo;
1403 	so->so_snd.sb_timeo = head->so_snd.sb_timeo;
1404 	so->so_rcv.sb_flags |= head->so_rcv.sb_flags & SB_AUTOSIZE;
1405 	so->so_snd.sb_flags |= head->so_snd.sb_flags & SB_AUTOSIZE;
1406 
1407 	soref(so);
1408 
1409 	return (so);
1410 }
1411 #endif	/* SCTP */
1412 
1413 int
1414 sobind(struct socket *so, struct sockaddr *nam, struct thread *td)
1415 {
1416 	int error;
1417 
1418 	CURVNET_SET(so->so_vnet);
1419 	error = so->so_proto->pr_bind(so, nam, td);
1420 	CURVNET_RESTORE();
1421 	return (error);
1422 }
1423 
1424 int
1425 sobindat(int fd, struct socket *so, struct sockaddr *nam, struct thread *td)
1426 {
1427 	int error;
1428 
1429 	CURVNET_SET(so->so_vnet);
1430 	error = so->so_proto->pr_bindat(fd, so, nam, td);
1431 	CURVNET_RESTORE();
1432 	return (error);
1433 }
1434 
1435 /*
1436  * solisten() transitions a socket from a non-listening state to a listening
1437  * state, but can also be used to update the listen queue depth on an
1438  * existing listen socket.  The protocol will call back into the sockets
1439  * layer using solisten_proto_check() and solisten_proto() to check and set
1440  * socket-layer listen state.  Call backs are used so that the protocol can
1441  * acquire both protocol and socket layer locks in whatever order is required
1442  * by the protocol.
1443  *
1444  * Protocol implementors are advised to hold the socket lock across the
1445  * socket-layer test and set to avoid races at the socket layer.
1446  */
1447 int
1448 solisten(struct socket *so, int backlog, struct thread *td)
1449 {
1450 	int error;
1451 
1452 	CURVNET_SET(so->so_vnet);
1453 	error = so->so_proto->pr_listen(so, backlog, td);
1454 	CURVNET_RESTORE();
1455 	return (error);
1456 }
1457 
1458 /*
1459  * Prepare for a call to solisten_proto().  Acquire all socket buffer locks in
1460  * order to interlock with socket I/O.
1461  */
1462 int
1463 solisten_proto_check(struct socket *so)
1464 {
1465 	SOCK_LOCK_ASSERT(so);
1466 
1467 	if ((so->so_state & (SS_ISCONNECTED | SS_ISCONNECTING |
1468 	    SS_ISDISCONNECTING)) != 0)
1469 		return (EINVAL);
1470 
1471 	/*
1472 	 * Sleeping is not permitted here, so simply fail if userspace is
1473 	 * attempting to transmit or receive on the socket.  This kind of
1474 	 * transient failure is not ideal, but it should occur only if userspace
1475 	 * is misusing the socket interfaces.
1476 	 */
1477 	if (!sx_try_xlock(&so->so_snd_sx))
1478 		return (EAGAIN);
1479 	if (!sx_try_xlock(&so->so_rcv_sx)) {
1480 		sx_xunlock(&so->so_snd_sx);
1481 		return (EAGAIN);
1482 	}
1483 	mtx_lock(&so->so_snd_mtx);
1484 	mtx_lock(&so->so_rcv_mtx);
1485 
1486 	/* Interlock with soo_aio_queue() and KTLS. */
1487 	if (!SOLISTENING(so)) {
1488 		bool ktls;
1489 
1490 #ifdef KERN_TLS
1491 		ktls = so->so_snd.sb_tls_info != NULL ||
1492 		    so->so_rcv.sb_tls_info != NULL;
1493 #else
1494 		ktls = false;
1495 #endif
1496 		if (ktls ||
1497 		    (so->so_snd.sb_flags & (SB_AIO | SB_AIO_RUNNING)) != 0 ||
1498 		    (so->so_rcv.sb_flags & (SB_AIO | SB_AIO_RUNNING)) != 0) {
1499 			solisten_proto_abort(so);
1500 			return (EINVAL);
1501 		}
1502 	}
1503 
1504 	return (0);
1505 }
1506 
1507 /*
1508  * Undo the setup done by solisten_proto_check().
1509  */
1510 void
1511 solisten_proto_abort(struct socket *so)
1512 {
1513 	mtx_unlock(&so->so_snd_mtx);
1514 	mtx_unlock(&so->so_rcv_mtx);
1515 	sx_xunlock(&so->so_snd_sx);
1516 	sx_xunlock(&so->so_rcv_sx);
1517 }
1518 
1519 void
1520 solisten_proto(struct socket *so, int backlog)
1521 {
1522 	int sbrcv_lowat, sbsnd_lowat;
1523 	u_int sbrcv_hiwat, sbsnd_hiwat;
1524 	short sbrcv_flags, sbsnd_flags;
1525 	sbintime_t sbrcv_timeo, sbsnd_timeo;
1526 
1527 	SOCK_LOCK_ASSERT(so);
1528 	KASSERT((so->so_state & (SS_ISCONNECTED | SS_ISCONNECTING |
1529 	    SS_ISDISCONNECTING)) == 0,
1530 	    ("%s: bad socket state %p", __func__, so));
1531 
1532 	if (SOLISTENING(so))
1533 		goto listening;
1534 
1535 	/*
1536 	 * Change this socket to listening state.
1537 	 */
1538 	sbrcv_lowat = so->so_rcv.sb_lowat;
1539 	sbsnd_lowat = so->so_snd.sb_lowat;
1540 	sbrcv_hiwat = so->so_rcv.sb_hiwat;
1541 	sbsnd_hiwat = so->so_snd.sb_hiwat;
1542 	sbrcv_flags = so->so_rcv.sb_flags;
1543 	sbsnd_flags = so->so_snd.sb_flags;
1544 	sbrcv_timeo = so->so_rcv.sb_timeo;
1545 	sbsnd_timeo = so->so_snd.sb_timeo;
1546 
1547 #ifdef MAC
1548 	mac_socketpeer_label_free(so->so_peerlabel);
1549 #endif
1550 
1551 	if (!(so->so_proto->pr_flags & PR_SOCKBUF)) {
1552 		sbdestroy(so, SO_SND);
1553 		sbdestroy(so, SO_RCV);
1554 	}
1555 
1556 #ifdef INVARIANTS
1557 	bzero(&so->so_rcv,
1558 	    sizeof(struct socket) - offsetof(struct socket, so_rcv));
1559 #endif
1560 
1561 	so->sol_sbrcv_lowat = sbrcv_lowat;
1562 	so->sol_sbsnd_lowat = sbsnd_lowat;
1563 	so->sol_sbrcv_hiwat = sbrcv_hiwat;
1564 	so->sol_sbsnd_hiwat = sbsnd_hiwat;
1565 	so->sol_sbrcv_flags = sbrcv_flags;
1566 	so->sol_sbsnd_flags = sbsnd_flags;
1567 	so->sol_sbrcv_timeo = sbrcv_timeo;
1568 	so->sol_sbsnd_timeo = sbsnd_timeo;
1569 
1570 	so->sol_qlen = so->sol_incqlen = 0;
1571 	TAILQ_INIT(&so->sol_incomp);
1572 	TAILQ_INIT(&so->sol_comp);
1573 
1574 	so->sol_accept_filter = NULL;
1575 	so->sol_accept_filter_arg = NULL;
1576 	so->sol_accept_filter_str = NULL;
1577 
1578 	so->sol_upcall = NULL;
1579 	so->sol_upcallarg = NULL;
1580 
1581 	so->so_options |= SO_ACCEPTCONN;
1582 
1583 listening:
1584 	if (backlog < 0 || backlog > V_somaxconn)
1585 		backlog = V_somaxconn;
1586 	so->sol_qlimit = backlog;
1587 
1588 	mtx_unlock(&so->so_snd_mtx);
1589 	mtx_unlock(&so->so_rcv_mtx);
1590 	sx_xunlock(&so->so_snd_sx);
1591 	sx_xunlock(&so->so_rcv_sx);
1592 }
1593 
1594 /*
1595  * Wakeup listeners/subsystems once we have a complete connection.
1596  * Enters with lock, returns unlocked.
1597  */
1598 void
1599 solisten_wakeup(struct socket *sol)
1600 {
1601 
1602 	if (sol->sol_upcall != NULL)
1603 		(void )sol->sol_upcall(sol, sol->sol_upcallarg, M_NOWAIT);
1604 	else {
1605 		selwakeuppri(&sol->so_rdsel, PSOCK);
1606 		KNOTE_LOCKED(&sol->so_rdsel.si_note, 0);
1607 	}
1608 	SOLISTEN_UNLOCK(sol);
1609 	wakeup_one(&sol->sol_comp);
1610 	if ((sol->so_state & SS_ASYNC) && sol->so_sigio != NULL)
1611 		pgsigio(&sol->so_sigio, SIGIO, 0);
1612 }
1613 
1614 /*
1615  * Return single connection off a listening socket queue.  Main consumer of
1616  * the function is kern_accept4().  Some modules, that do their own accept
1617  * management also use the function.  The socket reference held by the
1618  * listen queue is handed to the caller.
1619  *
1620  * Listening socket must be locked on entry and is returned unlocked on
1621  * return.
1622  * The flags argument is set of accept4(2) flags and ACCEPT4_INHERIT.
1623  */
1624 int
1625 solisten_dequeue(struct socket *head, struct socket **ret, int flags)
1626 {
1627 	struct socket *so;
1628 	int error;
1629 
1630 	SOLISTEN_LOCK_ASSERT(head);
1631 
1632 	while (!(head->so_state & SS_NBIO) && TAILQ_EMPTY(&head->sol_comp) &&
1633 	    head->so_error == 0) {
1634 		error = msleep(&head->sol_comp, SOCK_MTX(head), PSOCK | PCATCH,
1635 		    "accept", 0);
1636 		if (error != 0) {
1637 			SOLISTEN_UNLOCK(head);
1638 			return (error);
1639 		}
1640 	}
1641 	if (head->so_error) {
1642 		error = head->so_error;
1643 		head->so_error = 0;
1644 	} else if ((head->so_state & SS_NBIO) && TAILQ_EMPTY(&head->sol_comp))
1645 		error = EWOULDBLOCK;
1646 	else
1647 		error = 0;
1648 	if (error) {
1649 		SOLISTEN_UNLOCK(head);
1650 		return (error);
1651 	}
1652 	so = TAILQ_FIRST(&head->sol_comp);
1653 	SOCK_LOCK(so);
1654 	KASSERT(so->so_qstate == SQ_COMP,
1655 	    ("%s: so %p not SQ_COMP", __func__, so));
1656 	head->sol_qlen--;
1657 	so->so_qstate = SQ_NONE;
1658 	so->so_listen = NULL;
1659 	TAILQ_REMOVE(&head->sol_comp, so, so_list);
1660 	if (flags & ACCEPT4_INHERIT)
1661 		so->so_state |= (head->so_state & SS_NBIO);
1662 	else
1663 		so->so_state |= (flags & SOCK_NONBLOCK) ? SS_NBIO : 0;
1664 	SOCK_UNLOCK(so);
1665 	sorele_locked(head);
1666 
1667 	*ret = so;
1668 	return (0);
1669 }
1670 
1671 static struct so_splice *
1672 so_splice_alloc(off_t max)
1673 {
1674 	struct so_splice *sp;
1675 
1676 	sp = uma_zalloc(splice_zone, M_WAITOK);
1677 	sp->src = NULL;
1678 	sp->dst = NULL;
1679 	sp->max = max > 0 ? max : -1;
1680 	sp->wq_index = atomic_fetchadd_32(&splice_index, 1) % splice_num_wq;
1681 	sp->state = SPLICE_INIT;
1682 	TIMEOUT_TASK_INIT(taskqueue_thread, &sp->timeout, 0, so_splice_timeout,
1683 	    sp);
1684 	return (sp);
1685 }
1686 
1687 static void
1688 so_splice_free(struct so_splice *sp)
1689 {
1690 	KASSERT(sp->state == SPLICE_CLOSED,
1691 	    ("so_splice_free: sp %p not closed", sp));
1692 	uma_zfree(splice_zone, sp);
1693 }
1694 
1695 static void
1696 so_splice_timeout(void *arg, int pending __unused)
1697 {
1698 	struct so_splice *sp;
1699 
1700 	sp = arg;
1701 	(void)so_unsplice(sp->src, true);
1702 }
1703 
1704 /*
1705  * Splice the output from so to the input of so2.
1706  */
1707 static int
1708 so_splice(struct socket *so, struct socket *so2, struct splice *splice)
1709 {
1710 	struct so_splice *sp;
1711 	int error;
1712 
1713 	if (splice->sp_max < 0)
1714 		return (EINVAL);
1715 	/* Handle only TCP for now; TODO: other streaming protos */
1716 	if (so->so_proto->pr_protocol != IPPROTO_TCP ||
1717 	    so2->so_proto->pr_protocol != IPPROTO_TCP)
1718 		return (EPROTONOSUPPORT);
1719 	if (so->so_vnet != so2->so_vnet)
1720 		return (EINVAL);
1721 
1722 	/* so_splice_xfer() assumes that we're using these implementations. */
1723 	KASSERT(so->so_proto->pr_sosend == sosend_generic,
1724 	    ("so_splice: sosend not sosend_generic"));
1725 	KASSERT(so2->so_proto->pr_soreceive == soreceive_generic ||
1726 	    so2->so_proto->pr_soreceive == soreceive_stream,
1727 	    ("so_splice: soreceive not soreceive_generic/stream"));
1728 
1729 	sp = so_splice_alloc(splice->sp_max);
1730 	so->so_splice_sent = 0;
1731 	sp->src = so;
1732 	sp->dst = so2;
1733 
1734 	error = 0;
1735 	SOCK_LOCK(so);
1736 	if (SOLISTENING(so))
1737 		error = EINVAL;
1738 	else if ((so->so_state & (SS_ISCONNECTED | SS_ISCONNECTING)) == 0)
1739 		error = ENOTCONN;
1740 	else if (so->so_splice != NULL)
1741 		error = EBUSY;
1742 	if (error != 0) {
1743 		SOCK_UNLOCK(so);
1744 		uma_zfree(splice_zone, sp);
1745 		return (error);
1746 	}
1747 	SOCK_RECVBUF_LOCK(so);
1748 	if (so->so_rcv.sb_tls_info != NULL) {
1749 		SOCK_RECVBUF_UNLOCK(so);
1750 		SOCK_UNLOCK(so);
1751 		uma_zfree(splice_zone, sp);
1752 		return (EINVAL);
1753 	}
1754 	so->so_rcv.sb_flags |= SB_SPLICED;
1755 	so->so_splice = sp;
1756 	soref(so);
1757 	SOCK_RECVBUF_UNLOCK(so);
1758 	SOCK_UNLOCK(so);
1759 
1760 	error = 0;
1761 	SOCK_LOCK(so2);
1762 	if (SOLISTENING(so2))
1763 		error = EINVAL;
1764 	else if ((so2->so_state & (SS_ISCONNECTED | SS_ISCONNECTING)) == 0)
1765 		error = ENOTCONN;
1766 	else if (so2->so_splice_back != NULL)
1767 		error = EBUSY;
1768 	if (error != 0) {
1769 		SOCK_UNLOCK(so2);
1770 		mtx_lock(&sp->mtx);
1771 		sp->dst = NULL;
1772 		sp->state = SPLICE_EXCEPTION;
1773 		mtx_unlock(&sp->mtx);
1774 		so_unsplice(so, false);
1775 		return (error);
1776 	}
1777 	SOCK_SENDBUF_LOCK(so2);
1778 	if (so2->so_snd.sb_tls_info != NULL) {
1779 		SOCK_SENDBUF_UNLOCK(so2);
1780 		SOCK_UNLOCK(so2);
1781 		mtx_lock(&sp->mtx);
1782 		sp->dst = NULL;
1783 		sp->state = SPLICE_EXCEPTION;
1784 		mtx_unlock(&sp->mtx);
1785 		so_unsplice(so, false);
1786 		return (EINVAL);
1787 	}
1788 	so2->so_snd.sb_flags |= SB_SPLICED;
1789 	so2->so_splice_back = sp;
1790 	soref(so2);
1791 	mtx_lock(&sp->mtx);
1792 	SOCK_SENDBUF_UNLOCK(so2);
1793 	SOCK_UNLOCK(so2);
1794 
1795 	if (splice->sp_idle.tv_sec != 0 || splice->sp_idle.tv_usec != 0) {
1796 		taskqueue_enqueue_timeout_sbt(taskqueue_thread, &sp->timeout,
1797 		    tvtosbt(splice->sp_idle), 0, C_PREL(4));
1798 	}
1799 
1800 	/*
1801 	 * Transfer any data already present in the socket buffer.
1802 	 */
1803 	KASSERT(sp->state == SPLICE_INIT,
1804 	    ("so_splice: splice %p state %d", sp, sp->state));
1805 	sp->state = SPLICE_QUEUED;
1806 	so_splice_xfer(sp);
1807 	return (0);
1808 }
1809 
1810 static int
1811 so_unsplice(struct socket *so, bool timeout)
1812 {
1813 	struct socket *so2;
1814 	struct so_splice *sp;
1815 	bool drain;
1816 
1817 	/*
1818 	 * First unset SB_SPLICED and hide the splice structure so that
1819 	 * wakeup routines will stop enqueuing work.  This also ensures that
1820 	 * a only a single thread will proceed with the unsplice.
1821 	 */
1822 	SOCK_LOCK(so);
1823 	if (SOLISTENING(so)) {
1824 		SOCK_UNLOCK(so);
1825 		return (EINVAL);
1826 	}
1827 	SOCK_RECVBUF_LOCK(so);
1828 	if ((so->so_rcv.sb_flags & SB_SPLICED) == 0) {
1829 		SOCK_RECVBUF_UNLOCK(so);
1830 		SOCK_UNLOCK(so);
1831 		return (ENOTCONN);
1832 	}
1833 	sp = so->so_splice;
1834 	mtx_lock(&sp->mtx);
1835 	if (sp->state == SPLICE_INIT) {
1836 		/*
1837 		 * A splice is in the middle of being set up.
1838 		 */
1839 		mtx_unlock(&sp->mtx);
1840 		SOCK_RECVBUF_UNLOCK(so);
1841 		SOCK_UNLOCK(so);
1842 		return (ENOTCONN);
1843 	}
1844 	mtx_unlock(&sp->mtx);
1845 	so->so_rcv.sb_flags &= ~SB_SPLICED;
1846 	so->so_splice = NULL;
1847 	SOCK_RECVBUF_UNLOCK(so);
1848 	SOCK_UNLOCK(so);
1849 
1850 	so2 = sp->dst;
1851 	if (so2 != NULL) {
1852 		SOCK_LOCK(so2);
1853 		KASSERT(!SOLISTENING(so2), ("%s: so2 is listening", __func__));
1854 		SOCK_SENDBUF_LOCK(so2);
1855 		KASSERT((so2->so_snd.sb_flags & SB_SPLICED) != 0,
1856 		    ("%s: so2 is not spliced", __func__));
1857 		KASSERT(so2->so_splice_back == sp,
1858 		    ("%s: so_splice_back != sp", __func__));
1859 		so2->so_snd.sb_flags &= ~SB_SPLICED;
1860 		so2->so_splice_back = NULL;
1861 		SOCK_SENDBUF_UNLOCK(so2);
1862 		SOCK_UNLOCK(so2);
1863 	}
1864 
1865 	/*
1866 	 * No new work is being enqueued.  The worker thread might be
1867 	 * splicing data right now, in which case we want to wait for it to
1868 	 * finish before proceeding.
1869 	 */
1870 	mtx_lock(&sp->mtx);
1871 	switch (sp->state) {
1872 	case SPLICE_QUEUED:
1873 	case SPLICE_RUNNING:
1874 		sp->state = SPLICE_CLOSING;
1875 		while (sp->state == SPLICE_CLOSING)
1876 			msleep(sp, &sp->mtx, PSOCK, "unsplice", 0);
1877 		break;
1878 	case SPLICE_INIT:
1879 	case SPLICE_IDLE:
1880 	case SPLICE_EXCEPTION:
1881 		sp->state = SPLICE_CLOSED;
1882 		break;
1883 	default:
1884 		__assert_unreachable();
1885 	}
1886 	if (!timeout) {
1887 		drain = taskqueue_cancel_timeout(taskqueue_thread, &sp->timeout,
1888 		    NULL) != 0;
1889 	} else {
1890 		drain = false;
1891 	}
1892 	mtx_unlock(&sp->mtx);
1893 	if (drain)
1894 		taskqueue_drain_timeout(taskqueue_thread, &sp->timeout);
1895 
1896 	/*
1897 	 * Now we hold the sole reference to the splice structure.
1898 	 * Clean up: signal userspace and release socket references.
1899 	 */
1900 	sorwakeup(so);
1901 	CURVNET_SET(so->so_vnet);
1902 	sorele(so);
1903 	if (so2 != NULL) {
1904 		sowwakeup(so2);
1905 		sorele(so2);
1906 	}
1907 	CURVNET_RESTORE();
1908 	so_splice_free(sp);
1909 	return (0);
1910 }
1911 
1912 /*
1913  * Free socket upon release of the very last reference.
1914  */
1915 static void
1916 sofree(struct socket *so)
1917 {
1918 	struct protosw *pr = so->so_proto;
1919 
1920 	SOCK_LOCK_ASSERT(so);
1921 	KASSERT(refcount_load(&so->so_count) == 0,
1922 	    ("%s: so %p has references", __func__, so));
1923 	KASSERT(SOLISTENING(so) || so->so_qstate == SQ_NONE,
1924 	    ("%s: so %p is on listen queue", __func__, so));
1925 	KASSERT(SOLISTENING(so) || (so->so_rcv.sb_flags & SB_SPLICED) == 0,
1926 	    ("%s: so %p rcvbuf is spliced", __func__, so));
1927 	KASSERT(SOLISTENING(so) || (so->so_snd.sb_flags & SB_SPLICED) == 0,
1928 	    ("%s: so %p sndbuf is spliced", __func__, so));
1929 	KASSERT(so->so_splice == NULL && so->so_splice_back == NULL,
1930 	    ("%s: so %p has spliced data", __func__, so));
1931 
1932 	SOCK_UNLOCK(so);
1933 
1934 	if (so->so_dtor != NULL)
1935 		so->so_dtor(so);
1936 
1937 	VNET_SO_ASSERT(so);
1938 	if (pr->pr_detach != NULL)
1939 		pr->pr_detach(so);
1940 
1941 	if (!(pr->pr_flags & PR_SOCKBUF) && !SOLISTENING(so)) {
1942 		/*
1943 		 * From this point on, we assume that no other references to
1944 		 * this socket exist anywhere else in the stack.  Therefore,
1945 		 * no locks need to be acquired or held.
1946 		 */
1947 #ifdef INVARIANTS
1948 		SOCK_SENDBUF_LOCK(so);
1949 		SOCK_RECVBUF_LOCK(so);
1950 #endif
1951 		sbdestroy(so, SO_SND);
1952 		sbdestroy(so, SO_RCV);
1953 #ifdef INVARIANTS
1954 		SOCK_SENDBUF_UNLOCK(so);
1955 		SOCK_RECVBUF_UNLOCK(so);
1956 #endif
1957 		mtx_destroy(&so->so_snd_mtx);
1958 		mtx_destroy(&so->so_rcv_mtx);
1959 	}
1960 	seldrain(&so->so_rdsel);
1961 	seldrain(&so->so_wrsel);
1962 	knlist_destroy(&so->so_rdsel.si_note);
1963 	knlist_destroy(&so->so_wrsel.si_note);
1964 	sodealloc(so);
1965 }
1966 
1967 /*
1968  * Release a reference on a socket while holding the socket lock.
1969  * Unlocks the socket lock before returning.
1970  */
1971 void
1972 sorele_locked(struct socket *so)
1973 {
1974 	SOCK_LOCK_ASSERT(so);
1975 	if (refcount_release(&so->so_count))
1976 		sofree(so);
1977 	else
1978 		SOCK_UNLOCK(so);
1979 }
1980 
1981 /*
1982  * Close a socket on last file table reference removal.  Initiate disconnect
1983  * if connected.  Free socket when disconnect complete.
1984  *
1985  * This function will sorele() the socket.  Note that soclose() may be called
1986  * prior to the ref count reaching zero.  The actual socket structure will
1987  * not be freed until the ref count reaches zero.
1988  */
1989 int
1990 soclose(struct socket *so)
1991 {
1992 	struct accept_queue lqueue;
1993 	int error = 0;
1994 	bool listening, last __diagused;
1995 
1996 	CURVNET_SET(so->so_vnet);
1997 	funsetown(&so->so_sigio);
1998 	if (so->so_state & SS_ISCONNECTED) {
1999 		if ((so->so_state & SS_ISDISCONNECTING) == 0) {
2000 			error = sodisconnect(so);
2001 			if (error) {
2002 				if (error == ENOTCONN)
2003 					error = 0;
2004 				goto drop;
2005 			}
2006 		}
2007 
2008 		if ((so->so_options & SO_LINGER) != 0 && so->so_linger != 0) {
2009 			if ((so->so_state & SS_ISDISCONNECTING) &&
2010 			    (so->so_state & SS_NBIO))
2011 				goto drop;
2012 			while (so->so_state & SS_ISCONNECTED) {
2013 				error = tsleep(&so->so_timeo,
2014 				    PSOCK | PCATCH, "soclos",
2015 				    so->so_linger * hz);
2016 				if (error)
2017 					break;
2018 			}
2019 		}
2020 	}
2021 
2022 drop:
2023 	if (so->so_proto->pr_close != NULL)
2024 		so->so_proto->pr_close(so);
2025 
2026 	SOCK_LOCK(so);
2027 	if ((listening = SOLISTENING(so))) {
2028 		struct socket *sp;
2029 
2030 		TAILQ_INIT(&lqueue);
2031 		TAILQ_SWAP(&lqueue, &so->sol_incomp, socket, so_list);
2032 		TAILQ_CONCAT(&lqueue, &so->sol_comp, so_list);
2033 
2034 		so->sol_qlen = so->sol_incqlen = 0;
2035 
2036 		TAILQ_FOREACH(sp, &lqueue, so_list) {
2037 			SOCK_LOCK(sp);
2038 			sp->so_qstate = SQ_NONE;
2039 			sp->so_listen = NULL;
2040 			SOCK_UNLOCK(sp);
2041 			last = refcount_release(&so->so_count);
2042 			KASSERT(!last, ("%s: released last reference for %p",
2043 			    __func__, so));
2044 		}
2045 	}
2046 	sorele_locked(so);
2047 	if (listening) {
2048 		struct socket *sp, *tsp;
2049 
2050 		TAILQ_FOREACH_SAFE(sp, &lqueue, so_list, tsp)
2051 			soabort(sp);
2052 	}
2053 	CURVNET_RESTORE();
2054 	return (error);
2055 }
2056 
2057 /*
2058  * soabort() is used to abruptly tear down a connection, such as when a
2059  * resource limit is reached (listen queue depth exceeded), or if a listen
2060  * socket is closed while there are sockets waiting to be accepted.
2061  *
2062  * This interface is tricky, because it is called on an unreferenced socket,
2063  * and must be called only by a thread that has actually removed the socket
2064  * from the listen queue it was on.  Likely this thread holds the last
2065  * reference on the socket and soabort() will proceed with sofree().  But
2066  * it might be not the last, as the sockets on the listen queues are seen
2067  * from the protocol side.
2068  *
2069  * This interface will call into the protocol code, so must not be called
2070  * with any socket locks held.  Protocols do call it while holding their own
2071  * recursible protocol mutexes, but this is something that should be subject
2072  * to review in the future.
2073  *
2074  * Usually socket should have a single reference left, but this is not a
2075  * requirement.  In the past, when we have had named references for file
2076  * descriptor and protocol, we asserted that none of them are being held.
2077  */
2078 void
2079 soabort(struct socket *so)
2080 {
2081 
2082 	VNET_SO_ASSERT(so);
2083 
2084 	if (so->so_proto->pr_abort != NULL)
2085 		so->so_proto->pr_abort(so);
2086 	SOCK_LOCK(so);
2087 	sorele_locked(so);
2088 }
2089 
2090 int
2091 soaccept(struct socket *so, struct sockaddr *sa)
2092 {
2093 #ifdef INVARIANTS
2094 	u_char len = sa->sa_len;
2095 #endif
2096 	int error;
2097 
2098 	CURVNET_SET(so->so_vnet);
2099 	error = so->so_proto->pr_accept(so, sa);
2100 	KASSERT(sa->sa_len <= len,
2101 	    ("%s: protocol %p sockaddr overflow", __func__, so->so_proto));
2102 	CURVNET_RESTORE();
2103 	return (error);
2104 }
2105 
2106 int
2107 sopeeraddr(struct socket *so, struct sockaddr *sa)
2108 {
2109 #ifdef INVARIANTS
2110 	u_char len = sa->sa_len;
2111 #endif
2112 	int error;
2113 
2114 	CURVNET_ASSERT_SET();
2115 
2116 	error = so->so_proto->pr_peeraddr(so, sa);
2117 	KASSERT(sa->sa_len <= len,
2118 	    ("%s: protocol %p sockaddr overflow", __func__, so->so_proto));
2119 
2120 	return (error);
2121 }
2122 
2123 int
2124 sosockaddr(struct socket *so, struct sockaddr *sa)
2125 {
2126 #ifdef INVARIANTS
2127 	u_char len = sa->sa_len;
2128 #endif
2129 	int error;
2130 
2131 	CURVNET_SET(so->so_vnet);
2132 	error = so->so_proto->pr_sockaddr(so, sa);
2133 	KASSERT(sa->sa_len <= len,
2134 	    ("%s: protocol %p sockaddr overflow", __func__, so->so_proto));
2135 	CURVNET_RESTORE();
2136 
2137 	return (error);
2138 }
2139 
2140 int
2141 soconnect(struct socket *so, struct sockaddr *nam, struct thread *td)
2142 {
2143 
2144 	return (soconnectat(AT_FDCWD, so, nam, td));
2145 }
2146 
2147 int
2148 soconnectat(int fd, struct socket *so, struct sockaddr *nam, struct thread *td)
2149 {
2150 	int error;
2151 
2152 	CURVNET_SET(so->so_vnet);
2153 
2154 	/*
2155 	 * If protocol is connection-based, can only connect once.
2156 	 * Otherwise, if connected, try to disconnect first.  This allows
2157 	 * user to disconnect by connecting to, e.g., a null address.
2158 	 *
2159 	 * Note, this check is racy and may need to be re-evaluated at the
2160 	 * protocol layer.
2161 	 */
2162 	if (so->so_state & (SS_ISCONNECTED|SS_ISCONNECTING) &&
2163 	    ((so->so_proto->pr_flags & PR_CONNREQUIRED) ||
2164 	    (error = sodisconnect(so)))) {
2165 		error = EISCONN;
2166 	} else {
2167 		/*
2168 		 * Prevent accumulated error from previous connection from
2169 		 * biting us.
2170 		 */
2171 		so->so_error = 0;
2172 		if (fd == AT_FDCWD) {
2173 			error = so->so_proto->pr_connect(so, nam, td);
2174 		} else {
2175 			error = so->so_proto->pr_connectat(fd, so, nam, td);
2176 		}
2177 	}
2178 	CURVNET_RESTORE();
2179 
2180 	return (error);
2181 }
2182 
2183 int
2184 soconnect2(struct socket *so1, struct socket *so2)
2185 {
2186 	int error;
2187 
2188 	CURVNET_SET(so1->so_vnet);
2189 	error = so1->so_proto->pr_connect2(so1, so2);
2190 	CURVNET_RESTORE();
2191 	return (error);
2192 }
2193 
2194 int
2195 sodisconnect(struct socket *so)
2196 {
2197 	int error;
2198 
2199 	if ((so->so_state & SS_ISCONNECTED) == 0)
2200 		return (ENOTCONN);
2201 	if (so->so_state & SS_ISDISCONNECTING)
2202 		return (EALREADY);
2203 	VNET_SO_ASSERT(so);
2204 	error = so->so_proto->pr_disconnect(so);
2205 	return (error);
2206 }
2207 
2208 int
2209 sosend_dgram(struct socket *so, struct sockaddr *addr, struct uio *uio,
2210     struct mbuf *top, struct mbuf *control, int flags, struct thread *td)
2211 {
2212 	long space;
2213 	ssize_t resid;
2214 	int clen = 0, error, dontroute;
2215 
2216 	KASSERT(so->so_type == SOCK_DGRAM, ("sosend_dgram: !SOCK_DGRAM"));
2217 	KASSERT(so->so_proto->pr_flags & PR_ATOMIC,
2218 	    ("sosend_dgram: !PR_ATOMIC"));
2219 
2220 	if (uio != NULL)
2221 		resid = uio->uio_resid;
2222 	else
2223 		resid = top->m_pkthdr.len;
2224 	/*
2225 	 * In theory resid should be unsigned.  However, space must be
2226 	 * signed, as it might be less than 0 if we over-committed, and we
2227 	 * must use a signed comparison of space and resid.  On the other
2228 	 * hand, a negative resid causes us to loop sending 0-length
2229 	 * segments to the protocol.
2230 	 */
2231 	if (resid < 0) {
2232 		error = EINVAL;
2233 		goto out;
2234 	}
2235 
2236 	dontroute =
2237 	    (flags & MSG_DONTROUTE) && (so->so_options & SO_DONTROUTE) == 0;
2238 	if (td != NULL)
2239 		td->td_ru.ru_msgsnd++;
2240 	if (control != NULL)
2241 		clen = control->m_len;
2242 
2243 	SOCKBUF_LOCK(&so->so_snd);
2244 	if (so->so_snd.sb_state & SBS_CANTSENDMORE) {
2245 		SOCKBUF_UNLOCK(&so->so_snd);
2246 		error = EPIPE;
2247 		goto out;
2248 	}
2249 	if (so->so_error) {
2250 		error = so->so_error;
2251 		so->so_error = 0;
2252 		SOCKBUF_UNLOCK(&so->so_snd);
2253 		goto out;
2254 	}
2255 	if ((so->so_state & SS_ISCONNECTED) == 0) {
2256 		/*
2257 		 * `sendto' and `sendmsg' is allowed on a connection-based
2258 		 * socket if it supports implied connect.  Return ENOTCONN if
2259 		 * not connected and no address is supplied.
2260 		 */
2261 		if ((so->so_proto->pr_flags & PR_CONNREQUIRED) &&
2262 		    (so->so_proto->pr_flags & PR_IMPLOPCL) == 0) {
2263 			if (!(resid == 0 && clen != 0)) {
2264 				SOCKBUF_UNLOCK(&so->so_snd);
2265 				error = ENOTCONN;
2266 				goto out;
2267 			}
2268 		} else if (addr == NULL) {
2269 			if (so->so_proto->pr_flags & PR_CONNREQUIRED)
2270 				error = ENOTCONN;
2271 			else
2272 				error = EDESTADDRREQ;
2273 			SOCKBUF_UNLOCK(&so->so_snd);
2274 			goto out;
2275 		}
2276 	}
2277 
2278 	/*
2279 	 * Do we need MSG_OOB support in SOCK_DGRAM?  Signs here may be a
2280 	 * problem and need fixing.
2281 	 */
2282 	space = sbspace(&so->so_snd);
2283 	if (flags & MSG_OOB)
2284 		space += 1024;
2285 	space -= clen;
2286 	SOCKBUF_UNLOCK(&so->so_snd);
2287 	if (resid > space) {
2288 		error = EMSGSIZE;
2289 		goto out;
2290 	}
2291 	if (uio == NULL) {
2292 		resid = 0;
2293 		if (flags & MSG_EOR)
2294 			top->m_flags |= M_EOR;
2295 	} else {
2296 		/*
2297 		 * Copy the data from userland into a mbuf chain.
2298 		 * If no data is to be copied in, a single empty mbuf
2299 		 * is returned.
2300 		 */
2301 		top = m_uiotombuf(uio, M_WAITOK, space, max_hdr,
2302 		    (M_PKTHDR | ((flags & MSG_EOR) ? M_EOR : 0)));
2303 		if (top == NULL) {
2304 			error = EFAULT;	/* only possible error */
2305 			goto out;
2306 		}
2307 		space -= resid - uio->uio_resid;
2308 		resid = uio->uio_resid;
2309 	}
2310 	KASSERT(resid == 0, ("sosend_dgram: resid != 0"));
2311 	/*
2312 	 * XXXRW: Frobbing SO_DONTROUTE here is even worse without sblock
2313 	 * than with.
2314 	 */
2315 	if (dontroute) {
2316 		SOCK_LOCK(so);
2317 		so->so_options |= SO_DONTROUTE;
2318 		SOCK_UNLOCK(so);
2319 	}
2320 	/*
2321 	 * XXX all the SBS_CANTSENDMORE checks previously done could be out
2322 	 * of date.  We could have received a reset packet in an interrupt or
2323 	 * maybe we slept while doing page faults in uiomove() etc.  We could
2324 	 * probably recheck again inside the locking protection here, but
2325 	 * there are probably other places that this also happens.  We must
2326 	 * rethink this.
2327 	 */
2328 	VNET_SO_ASSERT(so);
2329 	error = so->so_proto->pr_send(so, (flags & MSG_OOB) ? PRUS_OOB :
2330 	/*
2331 	 * If the user set MSG_EOF, the protocol understands this flag and
2332 	 * nothing left to send then use PRU_SEND_EOF instead of PRU_SEND.
2333 	 */
2334 	    ((flags & MSG_EOF) &&
2335 	     (so->so_proto->pr_flags & PR_IMPLOPCL) &&
2336 	     (resid <= 0)) ?
2337 		PRUS_EOF :
2338 		/* If there is more to send set PRUS_MORETOCOME */
2339 		(flags & MSG_MORETOCOME) ||
2340 		(resid > 0 && space > 0) ? PRUS_MORETOCOME : 0,
2341 		top, addr, control, td);
2342 	if (dontroute) {
2343 		SOCK_LOCK(so);
2344 		so->so_options &= ~SO_DONTROUTE;
2345 		SOCK_UNLOCK(so);
2346 	}
2347 	clen = 0;
2348 	control = NULL;
2349 	top = NULL;
2350 out:
2351 	if (top != NULL)
2352 		m_freem(top);
2353 	if (control != NULL)
2354 		m_freem(control);
2355 	return (error);
2356 }
2357 
2358 /*
2359  * Send on a socket.  If send must go all at once and message is larger than
2360  * send buffering, then hard error.  Lock against other senders.  If must go
2361  * all at once and not enough room now, then inform user that this would
2362  * block and do nothing.  Otherwise, if nonblocking, send as much as
2363  * possible.  The data to be sent is described by "uio" if nonzero, otherwise
2364  * by the mbuf chain "top" (which must be null if uio is not).  Data provided
2365  * in mbuf chain must be small enough to send all at once.
2366  *
2367  * Returns nonzero on error, timeout or signal; callers must check for short
2368  * counts if EINTR/ERESTART are returned.  Data and control buffers are freed
2369  * on return.
2370  */
2371 static int
2372 sosend_generic_locked(struct socket *so, struct sockaddr *addr, struct uio *uio,
2373     struct mbuf *top, struct mbuf *control, int flags, struct thread *td)
2374 {
2375 	long space;
2376 	ssize_t resid;
2377 	int clen = 0, error, dontroute;
2378 	int atomic = sosendallatonce(so) || top;
2379 	int pr_send_flag;
2380 #ifdef KERN_TLS
2381 	struct ktls_session *tls;
2382 	int tls_enq_cnt, tls_send_flag;
2383 	uint8_t tls_rtype;
2384 
2385 	tls = NULL;
2386 	tls_rtype = TLS_RLTYPE_APP;
2387 #endif
2388 
2389 	SOCK_IO_SEND_ASSERT_LOCKED(so);
2390 
2391 	if (uio != NULL)
2392 		resid = uio->uio_resid;
2393 	else if ((top->m_flags & M_PKTHDR) != 0)
2394 		resid = top->m_pkthdr.len;
2395 	else
2396 		resid = m_length(top, NULL);
2397 	/*
2398 	 * In theory resid should be unsigned.  However, space must be
2399 	 * signed, as it might be less than 0 if we over-committed, and we
2400 	 * must use a signed comparison of space and resid.  On the other
2401 	 * hand, a negative resid causes us to loop sending 0-length
2402 	 * segments to the protocol.
2403 	 *
2404 	 * Also check to make sure that MSG_EOR isn't used on SOCK_STREAM
2405 	 * type sockets since that's an error.
2406 	 */
2407 	if (resid < 0 || (so->so_type == SOCK_STREAM && (flags & MSG_EOR))) {
2408 		error = EINVAL;
2409 		goto out;
2410 	}
2411 
2412 	dontroute =
2413 	    (flags & MSG_DONTROUTE) && (so->so_options & SO_DONTROUTE) == 0 &&
2414 	    (so->so_proto->pr_flags & PR_ATOMIC);
2415 	if (td != NULL)
2416 		td->td_ru.ru_msgsnd++;
2417 	if (control != NULL)
2418 		clen = control->m_len;
2419 
2420 #ifdef KERN_TLS
2421 	tls_send_flag = 0;
2422 	tls = ktls_hold(so->so_snd.sb_tls_info);
2423 	if (tls != NULL) {
2424 		if (tls->mode == TCP_TLS_MODE_SW)
2425 			tls_send_flag = PRUS_NOTREADY;
2426 
2427 		if (control != NULL) {
2428 			struct cmsghdr *cm = mtod(control, struct cmsghdr *);
2429 
2430 			if (clen >= sizeof(*cm) &&
2431 			    cm->cmsg_type == TLS_SET_RECORD_TYPE) {
2432 				tls_rtype = *((uint8_t *)CMSG_DATA(cm));
2433 				clen = 0;
2434 				m_freem(control);
2435 				control = NULL;
2436 				atomic = 1;
2437 			}
2438 		}
2439 
2440 		if (resid == 0 && !ktls_permit_empty_frames(tls)) {
2441 			error = EINVAL;
2442 			goto out;
2443 		}
2444 	}
2445 #endif
2446 
2447 restart:
2448 	do {
2449 		SOCKBUF_LOCK(&so->so_snd);
2450 		if (so->so_snd.sb_state & SBS_CANTSENDMORE) {
2451 			SOCKBUF_UNLOCK(&so->so_snd);
2452 			error = EPIPE;
2453 			goto out;
2454 		}
2455 		if (so->so_error) {
2456 			error = so->so_error;
2457 			so->so_error = 0;
2458 			SOCKBUF_UNLOCK(&so->so_snd);
2459 			goto out;
2460 		}
2461 		if ((so->so_state & SS_ISCONNECTED) == 0) {
2462 			/*
2463 			 * `sendto' and `sendmsg' is allowed on a connection-
2464 			 * based socket if it supports implied connect.
2465 			 * Return ENOTCONN if not connected and no address is
2466 			 * supplied.
2467 			 */
2468 			if ((so->so_proto->pr_flags & PR_CONNREQUIRED) &&
2469 			    (so->so_proto->pr_flags & PR_IMPLOPCL) == 0) {
2470 				if (!(resid == 0 && clen != 0)) {
2471 					SOCKBUF_UNLOCK(&so->so_snd);
2472 					error = ENOTCONN;
2473 					goto out;
2474 				}
2475 			} else if (addr == NULL) {
2476 				SOCKBUF_UNLOCK(&so->so_snd);
2477 				if (so->so_proto->pr_flags & PR_CONNREQUIRED)
2478 					error = ENOTCONN;
2479 				else
2480 					error = EDESTADDRREQ;
2481 				goto out;
2482 			}
2483 		}
2484 		space = sbspace(&so->so_snd);
2485 		if (flags & MSG_OOB)
2486 			space += 1024;
2487 		if ((atomic && resid > so->so_snd.sb_hiwat) ||
2488 		    clen > so->so_snd.sb_hiwat) {
2489 			SOCKBUF_UNLOCK(&so->so_snd);
2490 			error = EMSGSIZE;
2491 			goto out;
2492 		}
2493 		if (space < resid + clen &&
2494 		    (atomic || space < so->so_snd.sb_lowat || space < clen)) {
2495 			if ((so->so_state & SS_NBIO) ||
2496 			    (flags & (MSG_NBIO | MSG_DONTWAIT)) != 0) {
2497 				SOCKBUF_UNLOCK(&so->so_snd);
2498 				error = EWOULDBLOCK;
2499 				goto out;
2500 			}
2501 			error = sbwait(so, SO_SND);
2502 			SOCKBUF_UNLOCK(&so->so_snd);
2503 			if (error)
2504 				goto out;
2505 			goto restart;
2506 		}
2507 		SOCKBUF_UNLOCK(&so->so_snd);
2508 		space -= clen;
2509 		do {
2510 			if (uio == NULL) {
2511 				resid = 0;
2512 				if (flags & MSG_EOR)
2513 					top->m_flags |= M_EOR;
2514 #ifdef KERN_TLS
2515 				if (tls != NULL) {
2516 					ktls_frame(top, tls, &tls_enq_cnt,
2517 					    tls_rtype);
2518 					tls_rtype = TLS_RLTYPE_APP;
2519 				}
2520 #endif
2521 			} else {
2522 				/*
2523 				 * Copy the data from userland into a mbuf
2524 				 * chain.  If resid is 0, which can happen
2525 				 * only if we have control to send, then
2526 				 * a single empty mbuf is returned.  This
2527 				 * is a workaround to prevent protocol send
2528 				 * methods to panic.
2529 				 */
2530 #ifdef KERN_TLS
2531 				if (tls != NULL) {
2532 					top = m_uiotombuf(uio, M_WAITOK, space,
2533 					    tls->params.max_frame_len,
2534 					    M_EXTPG |
2535 					    ((flags & MSG_EOR) ? M_EOR : 0));
2536 					if (top != NULL) {
2537 						ktls_frame(top, tls,
2538 						    &tls_enq_cnt, tls_rtype);
2539 					}
2540 					tls_rtype = TLS_RLTYPE_APP;
2541 				} else
2542 #endif
2543 					top = m_uiotombuf(uio, M_WAITOK, space,
2544 					    (atomic ? max_hdr : 0),
2545 					    (atomic ? M_PKTHDR : 0) |
2546 					    ((flags & MSG_EOR) ? M_EOR : 0));
2547 				if (top == NULL) {
2548 					error = EFAULT; /* only possible error */
2549 					goto out;
2550 				}
2551 				space -= resid - uio->uio_resid;
2552 				resid = uio->uio_resid;
2553 			}
2554 			if (dontroute) {
2555 				SOCK_LOCK(so);
2556 				so->so_options |= SO_DONTROUTE;
2557 				SOCK_UNLOCK(so);
2558 			}
2559 			/*
2560 			 * XXX all the SBS_CANTSENDMORE checks previously
2561 			 * done could be out of date.  We could have received
2562 			 * a reset packet in an interrupt or maybe we slept
2563 			 * while doing page faults in uiomove() etc.  We
2564 			 * could probably recheck again inside the locking
2565 			 * protection here, but there are probably other
2566 			 * places that this also happens.  We must rethink
2567 			 * this.
2568 			 */
2569 			VNET_SO_ASSERT(so);
2570 
2571 			pr_send_flag = (flags & MSG_OOB) ? PRUS_OOB :
2572 			/*
2573 			 * If the user set MSG_EOF, the protocol understands
2574 			 * this flag and nothing left to send then use
2575 			 * PRU_SEND_EOF instead of PRU_SEND.
2576 			 */
2577 			    ((flags & MSG_EOF) &&
2578 			     (so->so_proto->pr_flags & PR_IMPLOPCL) &&
2579 			     (resid <= 0)) ?
2580 				PRUS_EOF :
2581 			/* If there is more to send set PRUS_MORETOCOME. */
2582 			    (flags & MSG_MORETOCOME) ||
2583 			    (resid > 0 && space > 0) ? PRUS_MORETOCOME : 0;
2584 
2585 #ifdef KERN_TLS
2586 			pr_send_flag |= tls_send_flag;
2587 #endif
2588 
2589 			error = so->so_proto->pr_send(so, pr_send_flag, top,
2590 			    addr, control, td);
2591 
2592 			if (dontroute) {
2593 				SOCK_LOCK(so);
2594 				so->so_options &= ~SO_DONTROUTE;
2595 				SOCK_UNLOCK(so);
2596 			}
2597 
2598 #ifdef KERN_TLS
2599 			if (tls != NULL && tls->mode == TCP_TLS_MODE_SW) {
2600 				if (error != 0) {
2601 					m_freem(top);
2602 					top = NULL;
2603 				} else {
2604 					soref(so);
2605 					ktls_enqueue(top, so, tls_enq_cnt);
2606 				}
2607 			}
2608 #endif
2609 			clen = 0;
2610 			control = NULL;
2611 			top = NULL;
2612 			if (error)
2613 				goto out;
2614 		} while (resid && space > 0);
2615 	} while (resid);
2616 
2617 out:
2618 #ifdef KERN_TLS
2619 	if (tls != NULL)
2620 		ktls_free(tls);
2621 #endif
2622 	if (top != NULL)
2623 		m_freem(top);
2624 	if (control != NULL)
2625 		m_freem(control);
2626 	return (error);
2627 }
2628 
2629 int
2630 sosend_generic(struct socket *so, struct sockaddr *addr, struct uio *uio,
2631     struct mbuf *top, struct mbuf *control, int flags, struct thread *td)
2632 {
2633 	int error;
2634 
2635 	error = SOCK_IO_SEND_LOCK(so, SBLOCKWAIT(flags));
2636 	if (error)
2637 		return (error);
2638 	error = sosend_generic_locked(so, addr, uio, top, control, flags, td);
2639 	SOCK_IO_SEND_UNLOCK(so);
2640 	return (error);
2641 }
2642 
2643 /*
2644  * Send to a socket from a kernel thread.
2645  *
2646  * XXXGL: in almost all cases uio is NULL and the mbuf is supplied.
2647  * Exception is nfs/bootp_subr.c.  It is arguable that the VNET context needs
2648  * to be set at all.  This function should just boil down to a static inline
2649  * calling the protocol method.
2650  */
2651 int
2652 sosend(struct socket *so, struct sockaddr *addr, struct uio *uio,
2653     struct mbuf *top, struct mbuf *control, int flags, struct thread *td)
2654 {
2655 	int error;
2656 
2657 	CURVNET_SET(so->so_vnet);
2658 	error = so->so_proto->pr_sosend(so, addr, uio,
2659 	    top, control, flags, td);
2660 	CURVNET_RESTORE();
2661 	return (error);
2662 }
2663 
2664 /*
2665  * send(2), write(2) or aio_write(2) on a socket.
2666  */
2667 int
2668 sousrsend(struct socket *so, struct sockaddr *addr, struct uio *uio,
2669     struct mbuf *control, int flags, struct proc *userproc)
2670 {
2671 	struct thread *td;
2672 	ssize_t len;
2673 	int error;
2674 
2675 	td = uio->uio_td;
2676 	len = uio->uio_resid;
2677 	CURVNET_SET(so->so_vnet);
2678 	error = so->so_proto->pr_sosend(so, addr, uio, NULL, control, flags,
2679 	    td);
2680 	CURVNET_RESTORE();
2681 	if (error != 0) {
2682 		/*
2683 		 * Clear transient errors for stream protocols if they made
2684 		 * some progress.  Make exclusion for aio(4) that would
2685 		 * schedule a new write in case of EWOULDBLOCK and clear
2686 		 * error itself.  See soaio_process_job().
2687 		 */
2688 		if (uio->uio_resid != len &&
2689 		    (so->so_proto->pr_flags & PR_ATOMIC) == 0 &&
2690 		    userproc == NULL &&
2691 		    (error == ERESTART || error == EINTR ||
2692 		    error == EWOULDBLOCK))
2693 			error = 0;
2694 		/* Generation of SIGPIPE can be controlled per socket. */
2695 		if (error == EPIPE && (so->so_options & SO_NOSIGPIPE) == 0 &&
2696 		    (flags & MSG_NOSIGNAL) == 0) {
2697 			if (userproc != NULL) {
2698 				/* aio(4) job */
2699 				PROC_LOCK(userproc);
2700 				kern_psignal(userproc, SIGPIPE);
2701 				PROC_UNLOCK(userproc);
2702 			} else {
2703 				PROC_LOCK(td->td_proc);
2704 				tdsignal(td, SIGPIPE);
2705 				PROC_UNLOCK(td->td_proc);
2706 			}
2707 		}
2708 	}
2709 	return (error);
2710 }
2711 
2712 /*
2713  * The part of soreceive() that implements reading non-inline out-of-band
2714  * data from a socket.  For more complete comments, see soreceive(), from
2715  * which this code originated.
2716  *
2717  * Note that soreceive_rcvoob(), unlike the remainder of soreceive(), is
2718  * unable to return an mbuf chain to the caller.
2719  */
2720 static int
2721 soreceive_rcvoob(struct socket *so, struct uio *uio, int flags)
2722 {
2723 	struct protosw *pr = so->so_proto;
2724 	struct mbuf *m;
2725 	int error;
2726 
2727 	KASSERT(flags & MSG_OOB, ("soreceive_rcvoob: (flags & MSG_OOB) == 0"));
2728 	VNET_SO_ASSERT(so);
2729 
2730 	m = m_get(M_WAITOK, MT_DATA);
2731 	error = pr->pr_rcvoob(so, m, flags & MSG_PEEK);
2732 	if (error)
2733 		goto bad;
2734 	do {
2735 		error = uiomove(mtod(m, void *),
2736 		    (int) min(uio->uio_resid, m->m_len), uio);
2737 		m = m_free(m);
2738 	} while (uio->uio_resid && error == 0 && m);
2739 bad:
2740 	if (m != NULL)
2741 		m_freem(m);
2742 	return (error);
2743 }
2744 
2745 /*
2746  * Following replacement or removal of the first mbuf on the first mbuf chain
2747  * of a socket buffer, push necessary state changes back into the socket
2748  * buffer so that other consumers see the values consistently.  'nextrecord'
2749  * is the callers locally stored value of the original value of
2750  * sb->sb_mb->m_nextpkt which must be restored when the lead mbuf changes.
2751  * NOTE: 'nextrecord' may be NULL.
2752  */
2753 static __inline void
2754 sockbuf_pushsync(struct sockbuf *sb, struct mbuf *nextrecord)
2755 {
2756 
2757 	SOCKBUF_LOCK_ASSERT(sb);
2758 	/*
2759 	 * First, update for the new value of nextrecord.  If necessary, make
2760 	 * it the first record.
2761 	 */
2762 	if (sb->sb_mb != NULL)
2763 		sb->sb_mb->m_nextpkt = nextrecord;
2764 	else
2765 		sb->sb_mb = nextrecord;
2766 
2767 	/*
2768 	 * Now update any dependent socket buffer fields to reflect the new
2769 	 * state.  This is an expanded inline of SB_EMPTY_FIXUP(), with the
2770 	 * addition of a second clause that takes care of the case where
2771 	 * sb_mb has been updated, but remains the last record.
2772 	 */
2773 	if (sb->sb_mb == NULL) {
2774 		sb->sb_mbtail = NULL;
2775 		sb->sb_lastrecord = NULL;
2776 	} else if (sb->sb_mb->m_nextpkt == NULL)
2777 		sb->sb_lastrecord = sb->sb_mb;
2778 }
2779 
2780 /*
2781  * Implement receive operations on a socket.  We depend on the way that
2782  * records are added to the sockbuf by sbappend.  In particular, each record
2783  * (mbufs linked through m_next) must begin with an address if the protocol
2784  * so specifies, followed by an optional mbuf or mbufs containing ancillary
2785  * data, and then zero or more mbufs of data.  In order to allow parallelism
2786  * between network receive and copying to user space, as well as avoid
2787  * sleeping with a mutex held, we release the socket buffer mutex during the
2788  * user space copy.  Although the sockbuf is locked, new data may still be
2789  * appended, and thus we must maintain consistency of the sockbuf during that
2790  * time.
2791  *
2792  * The caller may receive the data as a single mbuf chain by supplying an
2793  * mbuf **mp for use in returning the chain.  The uio is then used only for
2794  * the count in uio_resid.
2795  */
2796 static int
2797 soreceive_generic_locked(struct socket *so, struct sockaddr **psa,
2798     struct uio *uio, struct mbuf **mp, struct mbuf **controlp, int *flagsp)
2799 {
2800 	struct mbuf *m;
2801 	int flags, error, offset;
2802 	ssize_t len;
2803 	struct protosw *pr = so->so_proto;
2804 	struct mbuf *nextrecord;
2805 	int moff, type = 0;
2806 	ssize_t orig_resid = uio->uio_resid;
2807 	bool report_real_len = false;
2808 
2809 	SOCK_IO_RECV_ASSERT_LOCKED(so);
2810 
2811 	error = 0;
2812 	if (flagsp != NULL) {
2813 		report_real_len = *flagsp & MSG_TRUNC;
2814 		*flagsp &= ~MSG_TRUNC;
2815 		flags = *flagsp &~ MSG_EOR;
2816 	} else
2817 		flags = 0;
2818 
2819 restart:
2820 	SOCKBUF_LOCK(&so->so_rcv);
2821 	m = so->so_rcv.sb_mb;
2822 	/*
2823 	 * If we have less data than requested, block awaiting more (subject
2824 	 * to any timeout) if:
2825 	 *   1. the current count is less than the low water mark, or
2826 	 *   2. MSG_DONTWAIT is not set
2827 	 */
2828 	if (m == NULL || (((flags & MSG_DONTWAIT) == 0 &&
2829 	    sbavail(&so->so_rcv) < uio->uio_resid) &&
2830 	    sbavail(&so->so_rcv) < so->so_rcv.sb_lowat &&
2831 	    m->m_nextpkt == NULL && (pr->pr_flags & PR_ATOMIC) == 0)) {
2832 		KASSERT(m != NULL || !sbavail(&so->so_rcv),
2833 		    ("receive: m == %p sbavail == %u",
2834 		    m, sbavail(&so->so_rcv)));
2835 		if (so->so_error || so->so_rerror) {
2836 			if (m != NULL)
2837 				goto dontblock;
2838 			if (so->so_error)
2839 				error = so->so_error;
2840 			else
2841 				error = so->so_rerror;
2842 			if ((flags & MSG_PEEK) == 0) {
2843 				if (so->so_error)
2844 					so->so_error = 0;
2845 				else
2846 					so->so_rerror = 0;
2847 			}
2848 			SOCKBUF_UNLOCK(&so->so_rcv);
2849 			goto release;
2850 		}
2851 		SOCKBUF_LOCK_ASSERT(&so->so_rcv);
2852 		if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
2853 			if (m != NULL)
2854 				goto dontblock;
2855 #ifdef KERN_TLS
2856 			else if (so->so_rcv.sb_tlsdcc == 0 &&
2857 			    so->so_rcv.sb_tlscc == 0) {
2858 #else
2859 			else {
2860 #endif
2861 				SOCKBUF_UNLOCK(&so->so_rcv);
2862 				goto release;
2863 			}
2864 		}
2865 		for (; m != NULL; m = m->m_next)
2866 			if (m->m_type == MT_OOBDATA  || (m->m_flags & M_EOR)) {
2867 				m = so->so_rcv.sb_mb;
2868 				goto dontblock;
2869 			}
2870 		if ((so->so_state & (SS_ISCONNECTING | SS_ISCONNECTED |
2871 		    SS_ISDISCONNECTING | SS_ISDISCONNECTED)) == 0 &&
2872 		    (so->so_proto->pr_flags & PR_CONNREQUIRED) != 0) {
2873 			SOCKBUF_UNLOCK(&so->so_rcv);
2874 			error = ENOTCONN;
2875 			goto release;
2876 		}
2877 		if (uio->uio_resid == 0 && !report_real_len) {
2878 			SOCKBUF_UNLOCK(&so->so_rcv);
2879 			goto release;
2880 		}
2881 		if ((so->so_state & SS_NBIO) ||
2882 		    (flags & (MSG_DONTWAIT|MSG_NBIO))) {
2883 			SOCKBUF_UNLOCK(&so->so_rcv);
2884 			error = EWOULDBLOCK;
2885 			goto release;
2886 		}
2887 		SBLASTRECORDCHK(&so->so_rcv);
2888 		SBLASTMBUFCHK(&so->so_rcv);
2889 		error = sbwait(so, SO_RCV);
2890 		SOCKBUF_UNLOCK(&so->so_rcv);
2891 		if (error)
2892 			goto release;
2893 		goto restart;
2894 	}
2895 dontblock:
2896 	/*
2897 	 * From this point onward, we maintain 'nextrecord' as a cache of the
2898 	 * pointer to the next record in the socket buffer.  We must keep the
2899 	 * various socket buffer pointers and local stack versions of the
2900 	 * pointers in sync, pushing out modifications before dropping the
2901 	 * socket buffer mutex, and re-reading them when picking it up.
2902 	 *
2903 	 * Otherwise, we will race with the network stack appending new data
2904 	 * or records onto the socket buffer by using inconsistent/stale
2905 	 * versions of the field, possibly resulting in socket buffer
2906 	 * corruption.
2907 	 *
2908 	 * By holding the high-level sblock(), we prevent simultaneous
2909 	 * readers from pulling off the front of the socket buffer.
2910 	 */
2911 	SOCKBUF_LOCK_ASSERT(&so->so_rcv);
2912 	if (uio->uio_td)
2913 		uio->uio_td->td_ru.ru_msgrcv++;
2914 	KASSERT(m == so->so_rcv.sb_mb, ("soreceive: m != so->so_rcv.sb_mb"));
2915 	SBLASTRECORDCHK(&so->so_rcv);
2916 	SBLASTMBUFCHK(&so->so_rcv);
2917 	nextrecord = m->m_nextpkt;
2918 	if (pr->pr_flags & PR_ADDR) {
2919 		KASSERT(m->m_type == MT_SONAME,
2920 		    ("m->m_type == %d", m->m_type));
2921 		orig_resid = 0;
2922 		if (psa != NULL)
2923 			*psa = sodupsockaddr(mtod(m, struct sockaddr *),
2924 			    M_NOWAIT);
2925 		if (flags & MSG_PEEK) {
2926 			m = m->m_next;
2927 		} else {
2928 			sbfree(&so->so_rcv, m);
2929 			so->so_rcv.sb_mb = m_free(m);
2930 			m = so->so_rcv.sb_mb;
2931 			sockbuf_pushsync(&so->so_rcv, nextrecord);
2932 		}
2933 	}
2934 
2935 	/*
2936 	 * Process one or more MT_CONTROL mbufs present before any data mbufs
2937 	 * in the first mbuf chain on the socket buffer.  If MSG_PEEK, we
2938 	 * just copy the data; if !MSG_PEEK, we call into the protocol to
2939 	 * perform externalization (or freeing if controlp == NULL).
2940 	 */
2941 	if (m != NULL && m->m_type == MT_CONTROL) {
2942 		struct mbuf *cm = NULL, *cmn;
2943 		struct mbuf **cme = &cm;
2944 #ifdef KERN_TLS
2945 		struct cmsghdr *cmsg;
2946 		struct tls_get_record tgr;
2947 
2948 		/*
2949 		 * For MSG_TLSAPPDATA, check for an alert record.
2950 		 * If found, return ENXIO without removing
2951 		 * it from the receive queue.  This allows a subsequent
2952 		 * call without MSG_TLSAPPDATA to receive it.
2953 		 * Note that, for TLS, there should only be a single
2954 		 * control mbuf with the TLS_GET_RECORD message in it.
2955 		 */
2956 		if (flags & MSG_TLSAPPDATA) {
2957 			cmsg = mtod(m, struct cmsghdr *);
2958 			if (cmsg->cmsg_type == TLS_GET_RECORD &&
2959 			    cmsg->cmsg_len == CMSG_LEN(sizeof(tgr))) {
2960 				memcpy(&tgr, CMSG_DATA(cmsg), sizeof(tgr));
2961 				if (__predict_false(tgr.tls_type ==
2962 				    TLS_RLTYPE_ALERT)) {
2963 					SOCKBUF_UNLOCK(&so->so_rcv);
2964 					error = ENXIO;
2965 					goto release;
2966 				}
2967 			}
2968 		}
2969 #endif
2970 
2971 		do {
2972 			if (flags & MSG_PEEK) {
2973 				if (controlp != NULL) {
2974 					*controlp = m_copym(m, 0, m->m_len,
2975 					    M_NOWAIT);
2976 					controlp = &(*controlp)->m_next;
2977 				}
2978 				m = m->m_next;
2979 			} else {
2980 				sbfree(&so->so_rcv, m);
2981 				so->so_rcv.sb_mb = m->m_next;
2982 				m->m_next = NULL;
2983 				*cme = m;
2984 				cme = &(*cme)->m_next;
2985 				m = so->so_rcv.sb_mb;
2986 			}
2987 		} while (m != NULL && m->m_type == MT_CONTROL);
2988 		if ((flags & MSG_PEEK) == 0)
2989 			sockbuf_pushsync(&so->so_rcv, nextrecord);
2990 		while (cm != NULL) {
2991 			cmn = cm->m_next;
2992 			cm->m_next = NULL;
2993 			if (controlp != NULL)
2994 				*controlp = cm;
2995 			else
2996 				m_freem(cm);
2997 			if (controlp != NULL) {
2998 				while (*controlp != NULL)
2999 					controlp = &(*controlp)->m_next;
3000 			}
3001 			cm = cmn;
3002 		}
3003 		if (m != NULL)
3004 			nextrecord = so->so_rcv.sb_mb->m_nextpkt;
3005 		else
3006 			nextrecord = so->so_rcv.sb_mb;
3007 		orig_resid = 0;
3008 	}
3009 	if (m != NULL) {
3010 		if ((flags & MSG_PEEK) == 0) {
3011 			KASSERT(m->m_nextpkt == nextrecord,
3012 			    ("soreceive: post-control, nextrecord !sync"));
3013 			if (nextrecord == NULL) {
3014 				KASSERT(so->so_rcv.sb_mb == m,
3015 				    ("soreceive: post-control, sb_mb!=m"));
3016 				KASSERT(so->so_rcv.sb_lastrecord == m,
3017 				    ("soreceive: post-control, lastrecord!=m"));
3018 			}
3019 		}
3020 		type = m->m_type;
3021 		if (type == MT_OOBDATA)
3022 			flags |= MSG_OOB;
3023 	} else {
3024 		if ((flags & MSG_PEEK) == 0) {
3025 			KASSERT(so->so_rcv.sb_mb == nextrecord,
3026 			    ("soreceive: sb_mb != nextrecord"));
3027 			if (so->so_rcv.sb_mb == NULL) {
3028 				KASSERT(so->so_rcv.sb_lastrecord == NULL,
3029 				    ("soreceive: sb_lastercord != NULL"));
3030 			}
3031 		}
3032 	}
3033 	SOCKBUF_LOCK_ASSERT(&so->so_rcv);
3034 	SBLASTRECORDCHK(&so->so_rcv);
3035 	SBLASTMBUFCHK(&so->so_rcv);
3036 
3037 	/*
3038 	 * Now continue to read any data mbufs off of the head of the socket
3039 	 * buffer until the read request is satisfied.  Note that 'type' is
3040 	 * used to store the type of any mbuf reads that have happened so far
3041 	 * such that soreceive() can stop reading if the type changes, which
3042 	 * causes soreceive() to return only one of regular data and inline
3043 	 * out-of-band data in a single socket receive operation.
3044 	 */
3045 	moff = 0;
3046 	offset = 0;
3047 	while (m != NULL && !(m->m_flags & M_NOTREADY) && uio->uio_resid > 0 &&
3048 	    error == 0) {
3049 		/*
3050 		 * If the type of mbuf has changed since the last mbuf
3051 		 * examined ('type'), end the receive operation.
3052 		 */
3053 		SOCKBUF_LOCK_ASSERT(&so->so_rcv);
3054 		if (m->m_type == MT_OOBDATA || m->m_type == MT_CONTROL) {
3055 			if (type != m->m_type)
3056 				break;
3057 		} else if (type == MT_OOBDATA)
3058 			break;
3059 		else
3060 		    KASSERT(m->m_type == MT_DATA,
3061 			("m->m_type == %d", m->m_type));
3062 		so->so_rcv.sb_state &= ~SBS_RCVATMARK;
3063 		len = uio->uio_resid;
3064 		if (so->so_oobmark && len > so->so_oobmark - offset)
3065 			len = so->so_oobmark - offset;
3066 		if (len > m->m_len - moff)
3067 			len = m->m_len - moff;
3068 		/*
3069 		 * If mp is set, just pass back the mbufs.  Otherwise copy
3070 		 * them out via the uio, then free.  Sockbuf must be
3071 		 * consistent here (points to current mbuf, it points to next
3072 		 * record) when we drop priority; we must note any additions
3073 		 * to the sockbuf when we block interrupts again.
3074 		 */
3075 		if (mp == NULL) {
3076 			SOCKBUF_LOCK_ASSERT(&so->so_rcv);
3077 			SBLASTRECORDCHK(&so->so_rcv);
3078 			SBLASTMBUFCHK(&so->so_rcv);
3079 			SOCKBUF_UNLOCK(&so->so_rcv);
3080 			if ((m->m_flags & M_EXTPG) != 0)
3081 				error = m_unmapped_uiomove(m, moff, uio,
3082 				    (int)len);
3083 			else
3084 				error = uiomove(mtod(m, char *) + moff,
3085 				    (int)len, uio);
3086 			SOCKBUF_LOCK(&so->so_rcv);
3087 			if (error) {
3088 				/*
3089 				 * The MT_SONAME mbuf has already been removed
3090 				 * from the record, so it is necessary to
3091 				 * remove the data mbufs, if any, to preserve
3092 				 * the invariant in the case of PR_ADDR that
3093 				 * requires MT_SONAME mbufs at the head of
3094 				 * each record.
3095 				 */
3096 				if (pr->pr_flags & PR_ATOMIC &&
3097 				    ((flags & MSG_PEEK) == 0))
3098 					(void)sbdroprecord_locked(&so->so_rcv);
3099 				SOCKBUF_UNLOCK(&so->so_rcv);
3100 				goto release;
3101 			}
3102 		} else
3103 			uio->uio_resid -= len;
3104 		SOCKBUF_LOCK_ASSERT(&so->so_rcv);
3105 		if (len == m->m_len - moff) {
3106 			if (m->m_flags & M_EOR)
3107 				flags |= MSG_EOR;
3108 			if (flags & MSG_PEEK) {
3109 				m = m->m_next;
3110 				moff = 0;
3111 			} else {
3112 				nextrecord = m->m_nextpkt;
3113 				sbfree(&so->so_rcv, m);
3114 				if (mp != NULL) {
3115 					m->m_nextpkt = NULL;
3116 					*mp = m;
3117 					mp = &m->m_next;
3118 					so->so_rcv.sb_mb = m = m->m_next;
3119 					*mp = NULL;
3120 				} else {
3121 					so->so_rcv.sb_mb = m_free(m);
3122 					m = so->so_rcv.sb_mb;
3123 				}
3124 				sockbuf_pushsync(&so->so_rcv, nextrecord);
3125 				SBLASTRECORDCHK(&so->so_rcv);
3126 				SBLASTMBUFCHK(&so->so_rcv);
3127 			}
3128 		} else {
3129 			if (flags & MSG_PEEK)
3130 				moff += len;
3131 			else {
3132 				if (mp != NULL) {
3133 					if (flags & MSG_DONTWAIT) {
3134 						*mp = m_copym(m, 0, len,
3135 						    M_NOWAIT);
3136 						if (*mp == NULL) {
3137 							/*
3138 							 * m_copym() couldn't
3139 							 * allocate an mbuf.
3140 							 * Adjust uio_resid back
3141 							 * (it was adjusted
3142 							 * down by len bytes,
3143 							 * which we didn't end
3144 							 * up "copying" over).
3145 							 */
3146 							uio->uio_resid += len;
3147 							break;
3148 						}
3149 					} else {
3150 						SOCKBUF_UNLOCK(&so->so_rcv);
3151 						*mp = m_copym(m, 0, len,
3152 						    M_WAITOK);
3153 						SOCKBUF_LOCK(&so->so_rcv);
3154 					}
3155 				}
3156 				sbcut_locked(&so->so_rcv, len);
3157 			}
3158 		}
3159 		SOCKBUF_LOCK_ASSERT(&so->so_rcv);
3160 		if (so->so_oobmark) {
3161 			if ((flags & MSG_PEEK) == 0) {
3162 				so->so_oobmark -= len;
3163 				if (so->so_oobmark == 0) {
3164 					so->so_rcv.sb_state |= SBS_RCVATMARK;
3165 					break;
3166 				}
3167 			} else {
3168 				offset += len;
3169 				if (offset == so->so_oobmark)
3170 					break;
3171 			}
3172 		}
3173 		if (flags & MSG_EOR)
3174 			break;
3175 		/*
3176 		 * If the MSG_WAITALL flag is set (for non-atomic socket), we
3177 		 * must not quit until "uio->uio_resid == 0" or an error
3178 		 * termination.  If a signal/timeout occurs, return with a
3179 		 * short count but without error.  Keep sockbuf locked
3180 		 * against other readers.
3181 		 */
3182 		while (flags & MSG_WAITALL && m == NULL && uio->uio_resid > 0 &&
3183 		    !sosendallatonce(so) && nextrecord == NULL) {
3184 			SOCKBUF_LOCK_ASSERT(&so->so_rcv);
3185 			if (so->so_error || so->so_rerror ||
3186 			    so->so_rcv.sb_state & SBS_CANTRCVMORE)
3187 				break;
3188 			/*
3189 			 * Notify the protocol that some data has been
3190 			 * drained before blocking.
3191 			 */
3192 			if (pr->pr_flags & PR_WANTRCVD) {
3193 				SOCKBUF_UNLOCK(&so->so_rcv);
3194 				VNET_SO_ASSERT(so);
3195 				pr->pr_rcvd(so, flags);
3196 				SOCKBUF_LOCK(&so->so_rcv);
3197 				if (__predict_false(so->so_rcv.sb_mb == NULL &&
3198 				    (so->so_error || so->so_rerror ||
3199 				    so->so_rcv.sb_state & SBS_CANTRCVMORE)))
3200 					break;
3201 			}
3202 			SBLASTRECORDCHK(&so->so_rcv);
3203 			SBLASTMBUFCHK(&so->so_rcv);
3204 			/*
3205 			 * We could receive some data while was notifying
3206 			 * the protocol. Skip blocking in this case.
3207 			 */
3208 			if (so->so_rcv.sb_mb == NULL) {
3209 				error = sbwait(so, SO_RCV);
3210 				if (error) {
3211 					SOCKBUF_UNLOCK(&so->so_rcv);
3212 					goto release;
3213 				}
3214 			}
3215 			m = so->so_rcv.sb_mb;
3216 			if (m != NULL)
3217 				nextrecord = m->m_nextpkt;
3218 		}
3219 	}
3220 
3221 	SOCKBUF_LOCK_ASSERT(&so->so_rcv);
3222 	if (m != NULL && pr->pr_flags & PR_ATOMIC) {
3223 		if (report_real_len)
3224 			uio->uio_resid -= m_length(m, NULL) - moff;
3225 		flags |= MSG_TRUNC;
3226 		if ((flags & MSG_PEEK) == 0)
3227 			(void) sbdroprecord_locked(&so->so_rcv);
3228 	}
3229 	if ((flags & MSG_PEEK) == 0) {
3230 		if (m == NULL) {
3231 			/*
3232 			 * First part is an inline SB_EMPTY_FIXUP().  Second
3233 			 * part makes sure sb_lastrecord is up-to-date if
3234 			 * there is still data in the socket buffer.
3235 			 */
3236 			so->so_rcv.sb_mb = nextrecord;
3237 			if (so->so_rcv.sb_mb == NULL) {
3238 				so->so_rcv.sb_mbtail = NULL;
3239 				so->so_rcv.sb_lastrecord = NULL;
3240 			} else if (nextrecord->m_nextpkt == NULL)
3241 				so->so_rcv.sb_lastrecord = nextrecord;
3242 		}
3243 		SBLASTRECORDCHK(&so->so_rcv);
3244 		SBLASTMBUFCHK(&so->so_rcv);
3245 		/*
3246 		 * If soreceive() is being done from the socket callback,
3247 		 * then don't need to generate ACK to peer to update window,
3248 		 * since ACK will be generated on return to TCP.
3249 		 */
3250 		if (!(flags & MSG_SOCALLBCK) &&
3251 		    (pr->pr_flags & PR_WANTRCVD)) {
3252 			SOCKBUF_UNLOCK(&so->so_rcv);
3253 			VNET_SO_ASSERT(so);
3254 			pr->pr_rcvd(so, flags);
3255 			SOCKBUF_LOCK(&so->so_rcv);
3256 		}
3257 	}
3258 	SOCKBUF_LOCK_ASSERT(&so->so_rcv);
3259 	if (orig_resid == uio->uio_resid && orig_resid &&
3260 	    (flags & MSG_EOR) == 0 && (so->so_rcv.sb_state & SBS_CANTRCVMORE) == 0) {
3261 		SOCKBUF_UNLOCK(&so->so_rcv);
3262 		goto restart;
3263 	}
3264 	SOCKBUF_UNLOCK(&so->so_rcv);
3265 
3266 	if (flagsp != NULL)
3267 		*flagsp |= flags;
3268 release:
3269 	return (error);
3270 }
3271 
3272 int
3273 soreceive_generic(struct socket *so, struct sockaddr **psa, struct uio *uio,
3274     struct mbuf **mp, struct mbuf **controlp, int *flagsp)
3275 {
3276 	int error, flags;
3277 
3278 	if (psa != NULL)
3279 		*psa = NULL;
3280 	if (controlp != NULL)
3281 		*controlp = NULL;
3282 	if (flagsp != NULL) {
3283 		flags = *flagsp;
3284 		if ((flags & MSG_OOB) != 0)
3285 			return (soreceive_rcvoob(so, uio, flags));
3286 	} else {
3287 		flags = 0;
3288 	}
3289 	if (mp != NULL)
3290 		*mp = NULL;
3291 
3292 	error = SOCK_IO_RECV_LOCK(so, SBLOCKWAIT(flags));
3293 	if (error)
3294 		return (error);
3295 	error = soreceive_generic_locked(so, psa, uio, mp, controlp, flagsp);
3296 	SOCK_IO_RECV_UNLOCK(so);
3297 	return (error);
3298 }
3299 
3300 /*
3301  * Optimized version of soreceive() for stream (TCP) sockets.
3302  */
3303 static int
3304 soreceive_stream_locked(struct socket *so, struct sockbuf *sb,
3305     struct sockaddr **psa, struct uio *uio, struct mbuf **mp0,
3306     struct mbuf **controlp, int flags)
3307 {
3308 	int len = 0, error = 0, oresid;
3309 	struct mbuf *m, *n = NULL;
3310 
3311 	SOCK_IO_RECV_ASSERT_LOCKED(so);
3312 
3313 	/* Easy one, no space to copyout anything. */
3314 	if (uio->uio_resid == 0)
3315 		return (EINVAL);
3316 	oresid = uio->uio_resid;
3317 
3318 	SOCKBUF_LOCK(sb);
3319 	/* We will never ever get anything unless we are or were connected. */
3320 	if (!(so->so_state & (SS_ISCONNECTED|SS_ISDISCONNECTED))) {
3321 		error = ENOTCONN;
3322 		goto out;
3323 	}
3324 
3325 restart:
3326 	SOCKBUF_LOCK_ASSERT(&so->so_rcv);
3327 
3328 	/* Abort if socket has reported problems. */
3329 	if (so->so_error) {
3330 		if (sbavail(sb) > 0)
3331 			goto deliver;
3332 		if (oresid > uio->uio_resid)
3333 			goto out;
3334 		error = so->so_error;
3335 		if (!(flags & MSG_PEEK))
3336 			so->so_error = 0;
3337 		goto out;
3338 	}
3339 
3340 	/* Door is closed.  Deliver what is left, if any. */
3341 	if (sb->sb_state & SBS_CANTRCVMORE) {
3342 		if (sbavail(sb) > 0)
3343 			goto deliver;
3344 		else
3345 			goto out;
3346 	}
3347 
3348 	/* Socket buffer is empty and we shall not block. */
3349 	if (sbavail(sb) == 0 &&
3350 	    ((so->so_state & SS_NBIO) || (flags & (MSG_DONTWAIT|MSG_NBIO)))) {
3351 		error = EAGAIN;
3352 		goto out;
3353 	}
3354 
3355 	/* Socket buffer got some data that we shall deliver now. */
3356 	if (sbavail(sb) > 0 && !(flags & MSG_WAITALL) &&
3357 	    ((so->so_state & SS_NBIO) ||
3358 	     (flags & (MSG_DONTWAIT|MSG_NBIO)) ||
3359 	     sbavail(sb) >= sb->sb_lowat ||
3360 	     sbavail(sb) >= uio->uio_resid ||
3361 	     sbavail(sb) >= sb->sb_hiwat) ) {
3362 		goto deliver;
3363 	}
3364 
3365 	/* On MSG_WAITALL we must wait until all data or error arrives. */
3366 	if ((flags & MSG_WAITALL) &&
3367 	    (sbavail(sb) >= uio->uio_resid || sbavail(sb) >= sb->sb_hiwat))
3368 		goto deliver;
3369 
3370 	/*
3371 	 * Wait and block until (more) data comes in.
3372 	 * NB: Drops the sockbuf lock during wait.
3373 	 */
3374 	error = sbwait(so, SO_RCV);
3375 	if (error)
3376 		goto out;
3377 	goto restart;
3378 
3379 deliver:
3380 	SOCKBUF_LOCK_ASSERT(&so->so_rcv);
3381 	KASSERT(sbavail(sb) > 0, ("%s: sockbuf empty", __func__));
3382 	KASSERT(sb->sb_mb != NULL, ("%s: sb_mb == NULL", __func__));
3383 
3384 	/* Statistics. */
3385 	if (uio->uio_td)
3386 		uio->uio_td->td_ru.ru_msgrcv++;
3387 
3388 	/* Fill uio until full or current end of socket buffer is reached. */
3389 	len = min(uio->uio_resid, sbavail(sb));
3390 	if (mp0 != NULL) {
3391 		/* Dequeue as many mbufs as possible. */
3392 		if (!(flags & MSG_PEEK) && len >= sb->sb_mb->m_len) {
3393 			if (*mp0 == NULL)
3394 				*mp0 = sb->sb_mb;
3395 			else
3396 				m_cat(*mp0, sb->sb_mb);
3397 			for (m = sb->sb_mb;
3398 			     m != NULL && m->m_len <= len;
3399 			     m = m->m_next) {
3400 				KASSERT(!(m->m_flags & M_NOTREADY),
3401 				    ("%s: m %p not available", __func__, m));
3402 				len -= m->m_len;
3403 				uio->uio_resid -= m->m_len;
3404 				sbfree(sb, m);
3405 				n = m;
3406 			}
3407 			n->m_next = NULL;
3408 			sb->sb_mb = m;
3409 			sb->sb_lastrecord = sb->sb_mb;
3410 			if (sb->sb_mb == NULL)
3411 				SB_EMPTY_FIXUP(sb);
3412 		}
3413 		/* Copy the remainder. */
3414 		if (len > 0) {
3415 			KASSERT(sb->sb_mb != NULL,
3416 			    ("%s: len > 0 && sb->sb_mb empty", __func__));
3417 
3418 			m = m_copym(sb->sb_mb, 0, len, M_NOWAIT);
3419 			if (m == NULL)
3420 				len = 0;	/* Don't flush data from sockbuf. */
3421 			else
3422 				uio->uio_resid -= len;
3423 			if (*mp0 != NULL)
3424 				m_cat(*mp0, m);
3425 			else
3426 				*mp0 = m;
3427 			if (*mp0 == NULL) {
3428 				error = ENOBUFS;
3429 				goto out;
3430 			}
3431 		}
3432 	} else {
3433 		/* NB: Must unlock socket buffer as uiomove may sleep. */
3434 		SOCKBUF_UNLOCK(sb);
3435 		error = m_mbuftouio(uio, sb->sb_mb, len);
3436 		SOCKBUF_LOCK(sb);
3437 		if (error)
3438 			goto out;
3439 	}
3440 	SBLASTRECORDCHK(sb);
3441 	SBLASTMBUFCHK(sb);
3442 
3443 	/*
3444 	 * Remove the delivered data from the socket buffer unless we
3445 	 * were only peeking.
3446 	 */
3447 	if (!(flags & MSG_PEEK)) {
3448 		if (len > 0)
3449 			sbdrop_locked(sb, len);
3450 
3451 		/* Notify protocol that we drained some data. */
3452 		if ((so->so_proto->pr_flags & PR_WANTRCVD) &&
3453 		    (((flags & MSG_WAITALL) && uio->uio_resid > 0) ||
3454 		     !(flags & MSG_SOCALLBCK))) {
3455 			SOCKBUF_UNLOCK(sb);
3456 			VNET_SO_ASSERT(so);
3457 			so->so_proto->pr_rcvd(so, flags);
3458 			SOCKBUF_LOCK(sb);
3459 		}
3460 	}
3461 
3462 	/*
3463 	 * For MSG_WAITALL we may have to loop again and wait for
3464 	 * more data to come in.
3465 	 */
3466 	if ((flags & MSG_WAITALL) && uio->uio_resid > 0)
3467 		goto restart;
3468 out:
3469 	SBLASTRECORDCHK(sb);
3470 	SBLASTMBUFCHK(sb);
3471 	SOCKBUF_UNLOCK(sb);
3472 	return (error);
3473 }
3474 
3475 int
3476 soreceive_stream(struct socket *so, struct sockaddr **psa, struct uio *uio,
3477     struct mbuf **mp0, struct mbuf **controlp, int *flagsp)
3478 {
3479 	struct sockbuf *sb;
3480 	int error, flags;
3481 
3482 	sb = &so->so_rcv;
3483 
3484 	/* We only do stream sockets. */
3485 	if (so->so_type != SOCK_STREAM)
3486 		return (EINVAL);
3487 	if (psa != NULL)
3488 		*psa = NULL;
3489 	if (flagsp != NULL)
3490 		flags = *flagsp & ~MSG_EOR;
3491 	else
3492 		flags = 0;
3493 	if (controlp != NULL)
3494 		*controlp = NULL;
3495 	if (flags & MSG_OOB)
3496 		return (soreceive_rcvoob(so, uio, flags));
3497 	if (mp0 != NULL)
3498 		*mp0 = NULL;
3499 
3500 #ifdef KERN_TLS
3501 	/*
3502 	 * KTLS store TLS records as records with a control message to
3503 	 * describe the framing.
3504 	 *
3505 	 * We check once here before acquiring locks to optimize the
3506 	 * common case.
3507 	 */
3508 	if (sb->sb_tls_info != NULL)
3509 		return (soreceive_generic(so, psa, uio, mp0, controlp,
3510 		    flagsp));
3511 #endif
3512 
3513 	/*
3514 	 * Prevent other threads from reading from the socket.  This lock may be
3515 	 * dropped in order to sleep waiting for data to arrive.
3516 	 */
3517 	error = SOCK_IO_RECV_LOCK(so, SBLOCKWAIT(flags));
3518 	if (error)
3519 		return (error);
3520 #ifdef KERN_TLS
3521 	if (__predict_false(sb->sb_tls_info != NULL)) {
3522 		SOCK_IO_RECV_UNLOCK(so);
3523 		return (soreceive_generic(so, psa, uio, mp0, controlp,
3524 		    flagsp));
3525 	}
3526 #endif
3527 	error = soreceive_stream_locked(so, sb, psa, uio, mp0, controlp, flags);
3528 	SOCK_IO_RECV_UNLOCK(so);
3529 	return (error);
3530 }
3531 
3532 /*
3533  * Optimized version of soreceive() for simple datagram cases from userspace.
3534  * Unlike in the stream case, we're able to drop a datagram if copyout()
3535  * fails, and because we handle datagrams atomically, we don't need to use a
3536  * sleep lock to prevent I/O interlacing.
3537  */
3538 int
3539 soreceive_dgram(struct socket *so, struct sockaddr **psa, struct uio *uio,
3540     struct mbuf **mp0, struct mbuf **controlp, int *flagsp)
3541 {
3542 	struct mbuf *m, *m2;
3543 	int flags, error;
3544 	ssize_t len;
3545 	struct protosw *pr = so->so_proto;
3546 	struct mbuf *nextrecord;
3547 
3548 	if (psa != NULL)
3549 		*psa = NULL;
3550 	if (controlp != NULL)
3551 		*controlp = NULL;
3552 	if (flagsp != NULL)
3553 		flags = *flagsp &~ MSG_EOR;
3554 	else
3555 		flags = 0;
3556 
3557 	/*
3558 	 * For any complicated cases, fall back to the full
3559 	 * soreceive_generic().
3560 	 */
3561 	if (mp0 != NULL || (flags & (MSG_PEEK | MSG_OOB | MSG_TRUNC)))
3562 		return (soreceive_generic(so, psa, uio, mp0, controlp,
3563 		    flagsp));
3564 
3565 	/*
3566 	 * Enforce restrictions on use.
3567 	 */
3568 	KASSERT((pr->pr_flags & PR_WANTRCVD) == 0,
3569 	    ("soreceive_dgram: wantrcvd"));
3570 	KASSERT(pr->pr_flags & PR_ATOMIC, ("soreceive_dgram: !atomic"));
3571 	KASSERT((so->so_rcv.sb_state & SBS_RCVATMARK) == 0,
3572 	    ("soreceive_dgram: SBS_RCVATMARK"));
3573 	KASSERT((so->so_proto->pr_flags & PR_CONNREQUIRED) == 0,
3574 	    ("soreceive_dgram: P_CONNREQUIRED"));
3575 
3576 	/*
3577 	 * Loop blocking while waiting for a datagram.
3578 	 */
3579 	SOCKBUF_LOCK(&so->so_rcv);
3580 	while ((m = so->so_rcv.sb_mb) == NULL) {
3581 		KASSERT(sbavail(&so->so_rcv) == 0,
3582 		    ("soreceive_dgram: sb_mb NULL but sbavail %u",
3583 		    sbavail(&so->so_rcv)));
3584 		if (so->so_error) {
3585 			error = so->so_error;
3586 			so->so_error = 0;
3587 			SOCKBUF_UNLOCK(&so->so_rcv);
3588 			return (error);
3589 		}
3590 		if (so->so_rcv.sb_state & SBS_CANTRCVMORE ||
3591 		    uio->uio_resid == 0) {
3592 			SOCKBUF_UNLOCK(&so->so_rcv);
3593 			return (0);
3594 		}
3595 		if ((so->so_state & SS_NBIO) ||
3596 		    (flags & (MSG_DONTWAIT|MSG_NBIO))) {
3597 			SOCKBUF_UNLOCK(&so->so_rcv);
3598 			return (EWOULDBLOCK);
3599 		}
3600 		SBLASTRECORDCHK(&so->so_rcv);
3601 		SBLASTMBUFCHK(&so->so_rcv);
3602 		error = sbwait(so, SO_RCV);
3603 		if (error) {
3604 			SOCKBUF_UNLOCK(&so->so_rcv);
3605 			return (error);
3606 		}
3607 	}
3608 	SOCKBUF_LOCK_ASSERT(&so->so_rcv);
3609 
3610 	if (uio->uio_td)
3611 		uio->uio_td->td_ru.ru_msgrcv++;
3612 	SBLASTRECORDCHK(&so->so_rcv);
3613 	SBLASTMBUFCHK(&so->so_rcv);
3614 	nextrecord = m->m_nextpkt;
3615 	if (nextrecord == NULL) {
3616 		KASSERT(so->so_rcv.sb_lastrecord == m,
3617 		    ("soreceive_dgram: lastrecord != m"));
3618 	}
3619 
3620 	KASSERT(so->so_rcv.sb_mb->m_nextpkt == nextrecord,
3621 	    ("soreceive_dgram: m_nextpkt != nextrecord"));
3622 
3623 	/*
3624 	 * Pull 'm' and its chain off the front of the packet queue.
3625 	 */
3626 	so->so_rcv.sb_mb = NULL;
3627 	sockbuf_pushsync(&so->so_rcv, nextrecord);
3628 
3629 	/*
3630 	 * Walk 'm's chain and free that many bytes from the socket buffer.
3631 	 */
3632 	for (m2 = m; m2 != NULL; m2 = m2->m_next)
3633 		sbfree(&so->so_rcv, m2);
3634 
3635 	/*
3636 	 * Do a few last checks before we let go of the lock.
3637 	 */
3638 	SBLASTRECORDCHK(&so->so_rcv);
3639 	SBLASTMBUFCHK(&so->so_rcv);
3640 	SOCKBUF_UNLOCK(&so->so_rcv);
3641 
3642 	if (pr->pr_flags & PR_ADDR) {
3643 		KASSERT(m->m_type == MT_SONAME,
3644 		    ("m->m_type == %d", m->m_type));
3645 		if (psa != NULL)
3646 			*psa = sodupsockaddr(mtod(m, struct sockaddr *),
3647 			    M_WAITOK);
3648 		m = m_free(m);
3649 	}
3650 	KASSERT(m, ("%s: no data or control after soname", __func__));
3651 
3652 	/*
3653 	 * Packet to copyout() is now in 'm' and it is disconnected from the
3654 	 * queue.
3655 	 *
3656 	 * Process one or more MT_CONTROL mbufs present before any data mbufs
3657 	 * in the first mbuf chain on the socket buffer.  We call into the
3658 	 * protocol to perform externalization (or freeing if controlp ==
3659 	 * NULL). In some cases there can be only MT_CONTROL mbufs without
3660 	 * MT_DATA mbufs.
3661 	 */
3662 	if (m->m_type == MT_CONTROL) {
3663 		struct mbuf *cm = NULL, *cmn;
3664 		struct mbuf **cme = &cm;
3665 
3666 		do {
3667 			m2 = m->m_next;
3668 			m->m_next = NULL;
3669 			*cme = m;
3670 			cme = &(*cme)->m_next;
3671 			m = m2;
3672 		} while (m != NULL && m->m_type == MT_CONTROL);
3673 		while (cm != NULL) {
3674 			cmn = cm->m_next;
3675 			cm->m_next = NULL;
3676 			if (controlp != NULL)
3677 				*controlp = cm;
3678 			else
3679 				m_freem(cm);
3680 			if (controlp != NULL) {
3681 				while (*controlp != NULL)
3682 					controlp = &(*controlp)->m_next;
3683 			}
3684 			cm = cmn;
3685 		}
3686 	}
3687 	KASSERT(m == NULL || m->m_type == MT_DATA,
3688 	    ("soreceive_dgram: !data"));
3689 	while (m != NULL && uio->uio_resid > 0) {
3690 		len = uio->uio_resid;
3691 		if (len > m->m_len)
3692 			len = m->m_len;
3693 		error = uiomove(mtod(m, char *), (int)len, uio);
3694 		if (error) {
3695 			m_freem(m);
3696 			return (error);
3697 		}
3698 		if (len == m->m_len)
3699 			m = m_free(m);
3700 		else {
3701 			m->m_data += len;
3702 			m->m_len -= len;
3703 		}
3704 	}
3705 	if (m != NULL) {
3706 		flags |= MSG_TRUNC;
3707 		m_freem(m);
3708 	}
3709 	if (flagsp != NULL)
3710 		*flagsp |= flags;
3711 	return (0);
3712 }
3713 
3714 int
3715 soreceive(struct socket *so, struct sockaddr **psa, struct uio *uio,
3716     struct mbuf **mp0, struct mbuf **controlp, int *flagsp)
3717 {
3718 	int error;
3719 
3720 	CURVNET_SET(so->so_vnet);
3721 	error = so->so_proto->pr_soreceive(so, psa, uio, mp0, controlp, flagsp);
3722 	CURVNET_RESTORE();
3723 	return (error);
3724 }
3725 
3726 int
3727 soshutdown(struct socket *so, enum shutdown_how how)
3728 {
3729 	int error;
3730 
3731 	CURVNET_SET(so->so_vnet);
3732 	error = so->so_proto->pr_shutdown(so, how);
3733 	CURVNET_RESTORE();
3734 
3735 	return (error);
3736 }
3737 
3738 /*
3739  * Used by several pr_shutdown implementations that use generic socket buffers.
3740  */
3741 void
3742 sorflush(struct socket *so)
3743 {
3744 	int error;
3745 
3746 	VNET_SO_ASSERT(so);
3747 
3748 	/*
3749 	 * Dislodge threads currently blocked in receive and wait to acquire
3750 	 * a lock against other simultaneous readers before clearing the
3751 	 * socket buffer.  Don't let our acquire be interrupted by a signal
3752 	 * despite any existing socket disposition on interruptable waiting.
3753 	 *
3754 	 * The SOCK_IO_RECV_LOCK() is important here as there some pr_soreceive
3755 	 * methods that read the top of the socket buffer without acquisition
3756 	 * of the socket buffer mutex, assuming that top of the buffer
3757 	 * exclusively belongs to the read(2) syscall.  This is handy when
3758 	 * performing MSG_PEEK.
3759 	 */
3760 	socantrcvmore(so);
3761 
3762 	error = SOCK_IO_RECV_LOCK(so, SBL_WAIT | SBL_NOINTR);
3763 	if (error != 0) {
3764 		KASSERT(SOLISTENING(so),
3765 		    ("%s: soiolock(%p) failed", __func__, so));
3766 		return;
3767 	}
3768 
3769 	sbrelease(so, SO_RCV);
3770 	SOCK_IO_RECV_UNLOCK(so);
3771 
3772 }
3773 
3774 int
3775 sosetfib(struct socket *so, int fibnum)
3776 {
3777 	if (fibnum < 0 || fibnum >= rt_numfibs)
3778 		return (EINVAL);
3779 
3780 	SOCK_LOCK(so);
3781 	so->so_fibnum = fibnum;
3782 	SOCK_UNLOCK(so);
3783 
3784 	return (0);
3785 }
3786 
3787 #ifdef SOCKET_HHOOK
3788 /*
3789  * Wrapper for Socket established helper hook.
3790  * Parameters: socket, context of the hook point, hook id.
3791  */
3792 static inline int
3793 hhook_run_socket(struct socket *so, void *hctx, int32_t h_id)
3794 {
3795 	struct socket_hhook_data hhook_data = {
3796 		.so = so,
3797 		.hctx = hctx,
3798 		.m = NULL,
3799 		.status = 0
3800 	};
3801 
3802 	CURVNET_SET(so->so_vnet);
3803 	HHOOKS_RUN_IF(V_socket_hhh[h_id], &hhook_data, &so->osd);
3804 	CURVNET_RESTORE();
3805 
3806 	/* Ugly but needed, since hhooks return void for now */
3807 	return (hhook_data.status);
3808 }
3809 #endif
3810 
3811 /*
3812  * Perhaps this routine, and sooptcopyout(), below, ought to come in an
3813  * additional variant to handle the case where the option value needs to be
3814  * some kind of integer, but not a specific size.  In addition to their use
3815  * here, these functions are also called by the protocol-level pr_ctloutput()
3816  * routines.
3817  */
3818 static int
3819 _sooptcopyin(struct sockopt *sopt, void *buf, size_t len, size_t minlen,
3820     bool copycaps)
3821 {
3822 	size_t	valsize;
3823 
3824 	/*
3825 	 * If the user gives us more than we wanted, we ignore it, but if we
3826 	 * don't get the minimum length the caller wants, we return EINVAL.
3827 	 * On success, sopt->sopt_valsize is set to however much we actually
3828 	 * retrieved.
3829 	 */
3830 	if ((valsize = sopt->sopt_valsize) < minlen)
3831 		return EINVAL;
3832 	if (valsize > len)
3833 		sopt->sopt_valsize = valsize = len;
3834 
3835 	if (sopt->sopt_td != NULL) {
3836 		if (copycaps)
3837 			return (copyinptr(sopt->sopt_val, buf, valsize));
3838 		else
3839 			return (copyin(sopt->sopt_val, buf, valsize));
3840 	}
3841 
3842 	if (copycaps)
3843 		memcpy(buf, sopt->sopt_val, valsize);
3844 	else
3845 		memcpy_data(buf, sopt->sopt_val, valsize);
3846 	return (0);
3847 }
3848 
3849 int
3850 sooptcopyin(struct sockopt *sopt, void *buf, size_t len, size_t minlen)
3851 {
3852 	return (_sooptcopyin(sopt, buf, len, minlen, false));
3853 }
3854 
3855 #ifdef __CHERI__
3856 int
3857 sooptcopyinptr(struct sockopt *sopt, void *buf, size_t len, size_t minlen)
3858 {
3859 	return (_sooptcopyin(sopt, buf, len, minlen, true));
3860 }
3861 #endif
3862 
3863 /*
3864  * Kernel version of setsockopt(2).
3865  *
3866  * XXX: optlen is size_t, not socklen_t
3867  */
3868 int
3869 so_setsockopt(struct socket *so, int level, int optname, void *optval,
3870     size_t optlen)
3871 {
3872 	struct sockopt sopt;
3873 
3874 	sopt.sopt_level = level;
3875 	sopt.sopt_name = optname;
3876 	sopt.sopt_dir = SOPT_SET;
3877 	sopt.sopt_val = optval;
3878 	sopt.sopt_valsize = optlen;
3879 	sopt.sopt_td = NULL;
3880 	return (sosetopt(so, &sopt));
3881 }
3882 
3883 int
3884 sosetopt(struct socket *so, struct sockopt *sopt)
3885 {
3886 	int	error, optval;
3887 	struct	linger l;
3888 	struct	timeval tv;
3889 	sbintime_t val, *valp;
3890 	uint32_t val32;
3891 #ifdef MAC
3892 	struct mac extmac;
3893 #endif
3894 
3895 	CURVNET_SET(so->so_vnet);
3896 	error = 0;
3897 	if (sopt->sopt_level != SOL_SOCKET) {
3898 		error = so->so_proto->pr_ctloutput(so, sopt);
3899 	} else {
3900 		switch (sopt->sopt_name) {
3901 		case SO_ACCEPTFILTER:
3902 			error = accept_filt_setopt(so, sopt);
3903 			if (error)
3904 				goto bad;
3905 			break;
3906 
3907 		case SO_LINGER:
3908 			error = sooptcopyin(sopt, &l, sizeof l, sizeof l);
3909 			if (error)
3910 				goto bad;
3911 			if (l.l_linger < 0 ||
3912 			    l.l_linger > USHRT_MAX ||
3913 			    l.l_linger > (INT_MAX / hz)) {
3914 				error = EDOM;
3915 				goto bad;
3916 			}
3917 			SOCK_LOCK(so);
3918 			so->so_linger = l.l_linger;
3919 			if (l.l_onoff)
3920 				so->so_options |= SO_LINGER;
3921 			else
3922 				so->so_options &= ~SO_LINGER;
3923 			SOCK_UNLOCK(so);
3924 			break;
3925 
3926 		case SO_DEBUG:
3927 		case SO_KEEPALIVE:
3928 		case SO_DONTROUTE:
3929 		case SO_USELOOPBACK:
3930 		case SO_BROADCAST:
3931 		case SO_REUSEADDR:
3932 		case SO_REUSEPORT:
3933 		case SO_REUSEPORT_LB:
3934 		case SO_OOBINLINE:
3935 		case SO_TIMESTAMP:
3936 		case SO_BINTIME:
3937 		case SO_NOSIGPIPE:
3938 		case SO_NO_DDP:
3939 		case SO_NO_OFFLOAD:
3940 		case SO_RERROR:
3941 stdopt:
3942 			error = sooptcopyin(sopt, &optval, sizeof optval,
3943 			    sizeof optval);
3944 			if (error)
3945 				goto bad;
3946 			SOCK_LOCK(so);
3947 			if (optval)
3948 				so->so_options |= sopt->sopt_name;
3949 			else
3950 				so->so_options &= ~sopt->sopt_name;
3951 			SOCK_UNLOCK(so);
3952 			break;
3953 
3954 		case SO_PASSRIGHTS:
3955 			if (so->so_proto->pr_domain->dom_family != AF_LOCAL) {
3956 				error = EOPNOTSUPP;
3957 				goto bad;
3958 			}
3959 
3960 			goto stdopt;
3961 
3962 		case SO_SETFIB:
3963 			error = so->so_proto->pr_ctloutput(so, sopt);
3964 			break;
3965 
3966 		case SO_USER_COOKIE:
3967 			error = sooptcopyin(sopt, &val32, sizeof val32,
3968 			    sizeof val32);
3969 			if (error)
3970 				goto bad;
3971 			so->so_user_cookie = val32;
3972 			break;
3973 
3974 		case SO_SNDBUF:
3975 		case SO_RCVBUF:
3976 		case SO_SNDLOWAT:
3977 		case SO_RCVLOWAT:
3978 			error = so->so_proto->pr_setsbopt(so, sopt);
3979 			if (error)
3980 				goto bad;
3981 			break;
3982 
3983 		case SO_SNDTIMEO:
3984 		case SO_RCVTIMEO:
3985 #ifdef COMPAT_FREEBSD32
3986 			if (SV_CURPROC_FLAG(SV_ILP32)) {
3987 				struct timeval32 tv32;
3988 
3989 				error = sooptcopyin(sopt, &tv32, sizeof tv32,
3990 				    sizeof tv32);
3991 				CP(tv32, tv, tv_sec);
3992 				CP(tv32, tv, tv_usec);
3993 			} else
3994 #endif
3995 				error = sooptcopyin(sopt, &tv, sizeof tv,
3996 				    sizeof tv);
3997 			if (error)
3998 				goto bad;
3999 			if (tv.tv_sec < 0 || tv.tv_usec < 0 ||
4000 			    tv.tv_usec >= 1000000) {
4001 				error = EDOM;
4002 				goto bad;
4003 			}
4004 			if (tv.tv_sec > INT32_MAX)
4005 				val = SBT_MAX;
4006 			else
4007 				val = tvtosbt(tv);
4008 			SOCK_LOCK(so);
4009 			valp = sopt->sopt_name == SO_SNDTIMEO ?
4010 			    (SOLISTENING(so) ? &so->sol_sbsnd_timeo :
4011 			    &so->so_snd.sb_timeo) :
4012 			    (SOLISTENING(so) ? &so->sol_sbrcv_timeo :
4013 			    &so->so_rcv.sb_timeo);
4014 			*valp = val;
4015 			SOCK_UNLOCK(so);
4016 			break;
4017 
4018 		case SO_LABEL:
4019 #ifdef MAC
4020 			error = sooptcopyin(sopt, &extmac, sizeof extmac,
4021 			    sizeof extmac);
4022 			if (error)
4023 				goto bad;
4024 			error = mac_setsockopt_label(sopt->sopt_td->td_ucred,
4025 			    so, &extmac);
4026 #else
4027 			error = EOPNOTSUPP;
4028 #endif
4029 			break;
4030 
4031 		case SO_TS_CLOCK:
4032 			error = sooptcopyin(sopt, &optval, sizeof optval,
4033 			    sizeof optval);
4034 			if (error)
4035 				goto bad;
4036 			if (optval < 0 || optval > SO_TS_CLOCK_MAX) {
4037 				error = EINVAL;
4038 				goto bad;
4039 			}
4040 			so->so_ts_clock = optval;
4041 			break;
4042 
4043 		case SO_MAX_PACING_RATE:
4044 			error = sooptcopyin(sopt, &val32, sizeof(val32),
4045 			    sizeof(val32));
4046 			if (error)
4047 				goto bad;
4048 			so->so_max_pacing_rate = val32;
4049 			break;
4050 
4051 		case SO_SPLICE: {
4052 			struct splice splice;
4053 
4054 #ifdef COMPAT_FREEBSD32
4055 			if (SV_CURPROC_FLAG(SV_ILP32)) {
4056 				struct splice32 splice32;
4057 
4058 				error = sooptcopyin(sopt, &splice32,
4059 				    sizeof(splice32), sizeof(splice32));
4060 				if (error == 0) {
4061 					splice.sp_fd = splice32.sp_fd;
4062 					splice.sp_max = splice32.sp_max;
4063 					CP(splice32.sp_idle, splice.sp_idle,
4064 					    tv_sec);
4065 					CP(splice32.sp_idle, splice.sp_idle,
4066 					    tv_usec);
4067 				}
4068 			} else
4069 #endif
4070 			{
4071 				error = sooptcopyin(sopt, &splice,
4072 				    sizeof(splice), sizeof(splice));
4073 			}
4074 			if (error)
4075 				goto bad;
4076 #ifdef KTRACE
4077 			if (KTRPOINT(curthread, KTR_STRUCT))
4078 				ktrsplice(&splice);
4079 #endif
4080 
4081 			error = splice_init();
4082 			if (error != 0)
4083 				goto bad;
4084 
4085 			if (splice.sp_fd >= 0) {
4086 				struct file *fp;
4087 				struct socket *so2;
4088 
4089 				if (!cap_rights_contains(sopt->sopt_rights,
4090 				    &cap_recv_rights)) {
4091 					error = ENOTCAPABLE;
4092 					goto bad;
4093 				}
4094 				error = getsock(sopt->sopt_td, splice.sp_fd,
4095 				    &cap_send_rights, &fp);
4096 				if (error != 0)
4097 					goto bad;
4098 				so2 = fp->f_data;
4099 
4100 				error = so_splice(so, so2, &splice);
4101 				fdrop(fp, sopt->sopt_td);
4102 			} else {
4103 				error = so_unsplice(so, false);
4104 			}
4105 			break;
4106 		}
4107 		default:
4108 #ifdef SOCKET_HHOOK
4109 			if (V_socket_hhh[HHOOK_SOCKET_OPT]->hhh_nhooks > 0)
4110 				error = hhook_run_socket(so, sopt,
4111 				    HHOOK_SOCKET_OPT);
4112 			else
4113 #endif
4114 				error = ENOPROTOOPT;
4115 			break;
4116 		}
4117 		if (error == 0)
4118 			(void)so->so_proto->pr_ctloutput(so, sopt);
4119 	}
4120 bad:
4121 	CURVNET_RESTORE();
4122 	return (error);
4123 }
4124 
4125 /*
4126  * Helper routine for getsockopt.
4127  */
4128 int
4129 sooptcopyout(struct sockopt *sopt, const void *buf, size_t len)
4130 {
4131 	int	error;
4132 	size_t	valsize;
4133 
4134 	error = 0;
4135 
4136 	/*
4137 	 * Documented get behavior is that we always return a value, possibly
4138 	 * truncated to fit in the user's buffer.  Traditional behavior is
4139 	 * that we always tell the user precisely how much we copied, rather
4140 	 * than something useful like the total amount we had available for
4141 	 * her.  Note that this interface is not idempotent; the entire
4142 	 * answer must be generated ahead of time.
4143 	 */
4144 	valsize = min(len, sopt->sopt_valsize);
4145 	sopt->sopt_valsize = valsize;
4146 	if (sopt->sopt_val != NULL) {
4147 		if (sopt->sopt_td != NULL)
4148 			error = copyout(buf, sopt->sopt_val, valsize);
4149 		else
4150 			memcpy_data(sopt->sopt_val, buf, valsize);
4151 	}
4152 	return (error);
4153 }
4154 
4155 int
4156 sogetopt(struct socket *so, struct sockopt *sopt)
4157 {
4158 	int	error, optval;
4159 	struct	linger l;
4160 	struct	timeval tv;
4161 #ifdef MAC
4162 	struct mac extmac;
4163 #endif
4164 
4165 	CURVNET_SET(so->so_vnet);
4166 	error = 0;
4167 	if (sopt->sopt_level != SOL_SOCKET) {
4168 		error = so->so_proto->pr_ctloutput(so, sopt);
4169 		CURVNET_RESTORE();
4170 		return (error);
4171 	} else {
4172 		switch (sopt->sopt_name) {
4173 		case SO_ACCEPTFILTER:
4174 			error = accept_filt_getopt(so, sopt);
4175 			break;
4176 
4177 		case SO_LINGER:
4178 			SOCK_LOCK(so);
4179 			l.l_onoff = so->so_options & SO_LINGER;
4180 			l.l_linger = so->so_linger;
4181 			SOCK_UNLOCK(so);
4182 			error = sooptcopyout(sopt, &l, sizeof l);
4183 			break;
4184 
4185 		case SO_USELOOPBACK:
4186 		case SO_DONTROUTE:
4187 		case SO_DEBUG:
4188 		case SO_KEEPALIVE:
4189 		case SO_REUSEADDR:
4190 		case SO_REUSEPORT:
4191 		case SO_REUSEPORT_LB:
4192 		case SO_BROADCAST:
4193 		case SO_OOBINLINE:
4194 		case SO_ACCEPTCONN:
4195 		case SO_TIMESTAMP:
4196 		case SO_BINTIME:
4197 		case SO_NOSIGPIPE:
4198 		case SO_NO_DDP:
4199 		case SO_NO_OFFLOAD:
4200 		case SO_RERROR:
4201 stdopt:
4202 			optval = so->so_options & sopt->sopt_name;
4203 integer:
4204 			error = sooptcopyout(sopt, &optval, sizeof optval);
4205 			break;
4206 
4207 		case SO_PASSRIGHTS:
4208 			if (so->so_proto->pr_domain->dom_family != AF_LOCAL) {
4209 				error = EOPNOTSUPP;
4210 				goto bad;
4211 			}
4212 
4213 			goto stdopt;
4214 
4215 		case SO_FIB:
4216 			SOCK_LOCK(so);
4217 			optval = so->so_fibnum;
4218 			SOCK_UNLOCK(so);
4219 			goto integer;
4220 
4221 		case SO_DOMAIN:
4222 			optval = so->so_proto->pr_domain->dom_family;
4223 			goto integer;
4224 
4225 		case SO_TYPE:
4226 			optval = so->so_type;
4227 			goto integer;
4228 
4229 		case SO_PROTOCOL:
4230 			optval = so->so_proto->pr_protocol;
4231 			goto integer;
4232 
4233 		case SO_ERROR:
4234 			SOCK_LOCK(so);
4235 			if (so->so_error) {
4236 				optval = so->so_error;
4237 				so->so_error = 0;
4238 			} else {
4239 				optval = so->so_rerror;
4240 				so->so_rerror = 0;
4241 			}
4242 			SOCK_UNLOCK(so);
4243 			goto integer;
4244 
4245 		case SO_SNDBUF:
4246 			SOCK_LOCK(so);
4247 			optval = SOLISTENING(so) ? so->sol_sbsnd_hiwat :
4248 			    so->so_snd.sb_hiwat;
4249 			SOCK_UNLOCK(so);
4250 			goto integer;
4251 
4252 		case SO_RCVBUF:
4253 			SOCK_LOCK(so);
4254 			optval = SOLISTENING(so) ? so->sol_sbrcv_hiwat :
4255 			    so->so_rcv.sb_hiwat;
4256 			SOCK_UNLOCK(so);
4257 			goto integer;
4258 
4259 		case SO_SNDLOWAT:
4260 			SOCK_LOCK(so);
4261 			optval = SOLISTENING(so) ? so->sol_sbsnd_lowat :
4262 			    so->so_snd.sb_lowat;
4263 			SOCK_UNLOCK(so);
4264 			goto integer;
4265 
4266 		case SO_RCVLOWAT:
4267 			SOCK_LOCK(so);
4268 			optval = SOLISTENING(so) ? so->sol_sbrcv_lowat :
4269 			    so->so_rcv.sb_lowat;
4270 			SOCK_UNLOCK(so);
4271 			goto integer;
4272 
4273 		case SO_SNDTIMEO:
4274 		case SO_RCVTIMEO:
4275 			SOCK_LOCK(so);
4276 			tv = sbttotv(sopt->sopt_name == SO_SNDTIMEO ?
4277 			    (SOLISTENING(so) ? so->sol_sbsnd_timeo :
4278 			    so->so_snd.sb_timeo) :
4279 			    (SOLISTENING(so) ? so->sol_sbrcv_timeo :
4280 			    so->so_rcv.sb_timeo));
4281 			SOCK_UNLOCK(so);
4282 #ifdef COMPAT_FREEBSD32
4283 			if (SV_CURPROC_FLAG(SV_ILP32)) {
4284 				struct timeval32 tv32;
4285 
4286 				CP(tv, tv32, tv_sec);
4287 				CP(tv, tv32, tv_usec);
4288 				error = sooptcopyout(sopt, &tv32, sizeof tv32);
4289 			} else
4290 #endif
4291 				error = sooptcopyout(sopt, &tv, sizeof tv);
4292 			break;
4293 
4294 		case SO_LABEL:
4295 #ifdef MAC
4296 			error = sooptcopyin(sopt, &extmac, sizeof(extmac),
4297 			    sizeof(extmac));
4298 			if (error)
4299 				goto bad;
4300 			error = mac_getsockopt_label(sopt->sopt_td->td_ucred,
4301 			    so, &extmac);
4302 			if (error)
4303 				goto bad;
4304 			/* Don't copy out extmac, it is unchanged. */
4305 #else
4306 			error = EOPNOTSUPP;
4307 #endif
4308 			break;
4309 
4310 		case SO_PEERLABEL:
4311 #ifdef MAC
4312 			error = sooptcopyin(sopt, &extmac, sizeof(extmac),
4313 			    sizeof(extmac));
4314 			if (error)
4315 				goto bad;
4316 			error = mac_getsockopt_peerlabel(
4317 			    sopt->sopt_td->td_ucred, so, &extmac);
4318 			if (error)
4319 				goto bad;
4320 			/* Don't copy out extmac, it is unchanged. */
4321 #else
4322 			error = EOPNOTSUPP;
4323 #endif
4324 			break;
4325 
4326 		case SO_LISTENQLIMIT:
4327 			SOCK_LOCK(so);
4328 			optval = SOLISTENING(so) ? so->sol_qlimit : 0;
4329 			SOCK_UNLOCK(so);
4330 			goto integer;
4331 
4332 		case SO_LISTENQLEN:
4333 			SOCK_LOCK(so);
4334 			optval = SOLISTENING(so) ? so->sol_qlen : 0;
4335 			SOCK_UNLOCK(so);
4336 			goto integer;
4337 
4338 		case SO_LISTENINCQLEN:
4339 			SOCK_LOCK(so);
4340 			optval = SOLISTENING(so) ? so->sol_incqlen : 0;
4341 			SOCK_UNLOCK(so);
4342 			goto integer;
4343 
4344 		case SO_TS_CLOCK:
4345 			optval = so->so_ts_clock;
4346 			goto integer;
4347 
4348 		case SO_MAX_PACING_RATE:
4349 			optval = so->so_max_pacing_rate;
4350 			goto integer;
4351 
4352 		case SO_SPLICE: {
4353 			off_t n;
4354 
4355 			/*
4356 			 * Acquire the I/O lock to serialize with
4357 			 * so_splice_xfer().  This is not required for
4358 			 * correctness, but makes testing simpler: once a byte
4359 			 * has been transmitted to the sink and observed (e.g.,
4360 			 * by reading from the socket to which the sink is
4361 			 * connected), a subsequent getsockopt(SO_SPLICE) will
4362 			 * return an up-to-date value.
4363 			 */
4364 			error = SOCK_IO_RECV_LOCK(so, SBL_WAIT);
4365 			if (error != 0)
4366 				goto bad;
4367 			SOCK_LOCK(so);
4368 			if (SOLISTENING(so)) {
4369 				n = 0;
4370 			} else {
4371 				n = so->so_splice_sent;
4372 			}
4373 			SOCK_UNLOCK(so);
4374 			SOCK_IO_RECV_UNLOCK(so);
4375 			error = sooptcopyout(sopt, &n, sizeof(n));
4376 			break;
4377 		}
4378 
4379 		default:
4380 #ifdef SOCKET_HHOOK
4381 			if (V_socket_hhh[HHOOK_SOCKET_OPT]->hhh_nhooks > 0)
4382 				error = hhook_run_socket(so, sopt,
4383 				    HHOOK_SOCKET_OPT);
4384 			else
4385 #endif
4386 				error = ENOPROTOOPT;
4387 			break;
4388 		}
4389 	}
4390 bad:
4391 	CURVNET_RESTORE();
4392 	return (error);
4393 }
4394 
4395 int
4396 soopt_getm(struct sockopt *sopt, struct mbuf **mp)
4397 {
4398 	struct mbuf *m, *m_prev;
4399 	int sopt_size = sopt->sopt_valsize;
4400 
4401 	MGET(m, sopt->sopt_td ? M_WAITOK : M_NOWAIT, MT_DATA);
4402 	if (m == NULL)
4403 		return ENOBUFS;
4404 	if (sopt_size > MLEN) {
4405 		MCLGET(m, sopt->sopt_td ? M_WAITOK : M_NOWAIT);
4406 		if ((m->m_flags & M_EXT) == 0) {
4407 			m_free(m);
4408 			return ENOBUFS;
4409 		}
4410 		m->m_len = min(MCLBYTES, sopt_size);
4411 	} else {
4412 		m->m_len = min(MLEN, sopt_size);
4413 	}
4414 	sopt_size -= m->m_len;
4415 	*mp = m;
4416 	m_prev = m;
4417 
4418 	while (sopt_size) {
4419 		MGET(m, sopt->sopt_td ? M_WAITOK : M_NOWAIT, MT_DATA);
4420 		if (m == NULL) {
4421 			m_freem(*mp);
4422 			return ENOBUFS;
4423 		}
4424 		if (sopt_size > MLEN) {
4425 			MCLGET(m, sopt->sopt_td != NULL ? M_WAITOK :
4426 			    M_NOWAIT);
4427 			if ((m->m_flags & M_EXT) == 0) {
4428 				m_freem(m);
4429 				m_freem(*mp);
4430 				return ENOBUFS;
4431 			}
4432 			m->m_len = min(MCLBYTES, sopt_size);
4433 		} else {
4434 			m->m_len = min(MLEN, sopt_size);
4435 		}
4436 		sopt_size -= m->m_len;
4437 		m_prev->m_next = m;
4438 		m_prev = m;
4439 	}
4440 	return (0);
4441 }
4442 
4443 int
4444 soopt_mcopyin(struct sockopt *sopt, struct mbuf *m)
4445 {
4446 	struct mbuf *m0 = m;
4447 
4448 	if (sopt->sopt_val == NULL)
4449 		return (0);
4450 	while (m != NULL && sopt->sopt_valsize >= m->m_len) {
4451 		if (sopt->sopt_td != NULL) {
4452 			int error;
4453 
4454 			error = copyin(sopt->sopt_val, mtod(m, char *),
4455 			    m->m_len);
4456 			if (error != 0) {
4457 				m_freem(m0);
4458 				return(error);
4459 			}
4460 		} else
4461 			memcpy(mtod(m, char *), sopt->sopt_val, m->m_len);
4462 		sopt->sopt_valsize -= m->m_len;
4463 		sopt->sopt_val = (char *)sopt->sopt_val + m->m_len;
4464 		m = m->m_next;
4465 	}
4466 	if (m != NULL) /* should be allocated enoughly at ip6_sooptmcopyin() */
4467 		panic("ip6_sooptmcopyin");
4468 	return (0);
4469 }
4470 
4471 int
4472 soopt_mcopyout(struct sockopt *sopt, struct mbuf *m)
4473 {
4474 	struct mbuf *m0 = m;
4475 	size_t valsize = 0;
4476 
4477 	if (sopt->sopt_val == NULL)
4478 		return (0);
4479 	while (m != NULL && sopt->sopt_valsize >= m->m_len) {
4480 		if (sopt->sopt_td != NULL) {
4481 			int error;
4482 
4483 			error = copyout(mtod(m, char *), sopt->sopt_val,
4484 			    m->m_len);
4485 			if (error != 0) {
4486 				m_freem(m0);
4487 				return(error);
4488 			}
4489 		} else
4490 			memcpy(sopt->sopt_val, mtod(m, char *), m->m_len);
4491 		sopt->sopt_valsize -= m->m_len;
4492 		sopt->sopt_val = (char *)sopt->sopt_val + m->m_len;
4493 		valsize += m->m_len;
4494 		m = m->m_next;
4495 	}
4496 	if (m != NULL) {
4497 		/* enough soopt buffer should be given from user-land */
4498 		m_freem(m0);
4499 		return(EINVAL);
4500 	}
4501 	sopt->sopt_valsize = valsize;
4502 	return (0);
4503 }
4504 
4505 /*
4506  * sohasoutofband(): protocol notifies socket layer of the arrival of new
4507  * out-of-band data, which will then notify socket consumers.
4508  */
4509 void
4510 sohasoutofband(struct socket *so)
4511 {
4512 
4513 	if (so->so_sigio != NULL)
4514 		pgsigio(&so->so_sigio, SIGURG, 0);
4515 	selwakeuppri(&so->so_rdsel, PSOCK);
4516 }
4517 
4518 int
4519 sopoll_generic(struct socket *so, int events, struct thread *td)
4520 {
4521 	int revents;
4522 
4523 	SOCK_LOCK(so);
4524 	if (SOLISTENING(so)) {
4525 		if (!(events & (POLLIN | POLLRDNORM)))
4526 			revents = 0;
4527 		else if (!TAILQ_EMPTY(&so->sol_comp))
4528 			revents = events & (POLLIN | POLLRDNORM);
4529 		else if ((events & POLLINIGNEOF) == 0 && so->so_error)
4530 			revents = (events & (POLLIN | POLLRDNORM)) | POLLHUP;
4531 		else {
4532 			selrecord(td, &so->so_rdsel);
4533 			revents = 0;
4534 		}
4535 	} else {
4536 		revents = 0;
4537 		SOCK_SENDBUF_LOCK(so);
4538 		SOCK_RECVBUF_LOCK(so);
4539 		if (events & (POLLIN | POLLRDNORM))
4540 			if (soreadabledata(so) && !isspliced(so))
4541 				revents |= events & (POLLIN | POLLRDNORM);
4542 		if (events & (POLLOUT | POLLWRNORM))
4543 			if (sowriteable(so) && !issplicedback(so))
4544 				revents |= events & (POLLOUT | POLLWRNORM);
4545 		if (events & (POLLPRI | POLLRDBAND))
4546 			if (so->so_oobmark ||
4547 			    (so->so_rcv.sb_state & SBS_RCVATMARK))
4548 				revents |= events & (POLLPRI | POLLRDBAND);
4549 		if ((events & POLLINIGNEOF) == 0) {
4550 			if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
4551 				revents |= events & (POLLIN | POLLRDNORM);
4552 				if (so->so_snd.sb_state & SBS_CANTSENDMORE)
4553 					revents |= POLLHUP;
4554 			}
4555 		}
4556 		if (so->so_rcv.sb_state & SBS_CANTRCVMORE)
4557 			revents |= events & POLLRDHUP;
4558 		if (revents == 0) {
4559 			if (events &
4560 			    (POLLIN | POLLPRI | POLLRDNORM | POLLRDBAND | POLLRDHUP)) {
4561 				selrecord(td, &so->so_rdsel);
4562 				so->so_rcv.sb_flags |= SB_SEL;
4563 			}
4564 			if (events & (POLLOUT | POLLWRNORM)) {
4565 				selrecord(td, &so->so_wrsel);
4566 				so->so_snd.sb_flags |= SB_SEL;
4567 			}
4568 		}
4569 		SOCK_RECVBUF_UNLOCK(so);
4570 		SOCK_SENDBUF_UNLOCK(so);
4571 	}
4572 	SOCK_UNLOCK(so);
4573 	return (revents);
4574 }
4575 
4576 int
4577 sokqfilter_generic(struct socket *so, struct knote *kn)
4578 {
4579 	struct sockbuf *sb;
4580 	sb_which which;
4581 	struct knlist *knl;
4582 
4583 	switch (kn->kn_filter) {
4584 	case EVFILT_READ:
4585 		kn->kn_fop = &soread_filtops;
4586 		knl = &so->so_rdsel.si_note;
4587 		sb = &so->so_rcv;
4588 		which = SO_RCV;
4589 		break;
4590 	case EVFILT_WRITE:
4591 		kn->kn_fop = &sowrite_filtops;
4592 		knl = &so->so_wrsel.si_note;
4593 		sb = &so->so_snd;
4594 		which = SO_SND;
4595 		break;
4596 	case EVFILT_EMPTY:
4597 		kn->kn_fop = &soempty_filtops;
4598 		knl = &so->so_wrsel.si_note;
4599 		sb = &so->so_snd;
4600 		which = SO_SND;
4601 		break;
4602 	default:
4603 		return (EINVAL);
4604 	}
4605 
4606 	SOCK_LOCK(so);
4607 	if (SOLISTENING(so)) {
4608 		knlist_add(knl, kn, 1);
4609 	} else {
4610 		SOCK_BUF_LOCK(so, which);
4611 		knlist_add(knl, kn, 1);
4612 		sb->sb_flags |= SB_KNOTE;
4613 		if ((kn->kn_sfflags & NOTE_LOWAT) &&
4614 		    (sb->sb_flags & SB_AUTOLOWAT))
4615 			sb->sb_flags &= ~SB_AUTOLOWAT;
4616 		SOCK_BUF_UNLOCK(so, which);
4617 	}
4618 	SOCK_UNLOCK(so);
4619 	return (0);
4620 }
4621 
4622 static void
4623 filt_sordetach(struct knote *kn)
4624 {
4625 	struct socket *so = kn->kn_fp->f_data;
4626 
4627 	so_rdknl_lock(so);
4628 	knlist_remove(&so->so_rdsel.si_note, kn, 1);
4629 	if (!SOLISTENING(so) && knlist_empty(&so->so_rdsel.si_note))
4630 		so->so_rcv.sb_flags &= ~SB_KNOTE;
4631 	so_rdknl_unlock(so);
4632 }
4633 
4634 /*ARGSUSED*/
4635 static int
4636 filt_soread(struct knote *kn, long hint)
4637 {
4638 	struct socket *so;
4639 
4640 	so = kn->kn_fp->f_data;
4641 
4642 	if (SOLISTENING(so)) {
4643 		SOCK_LOCK_ASSERT(so);
4644 		kn->kn_data = so->sol_qlen;
4645 		if (so->so_error) {
4646 			kn->kn_flags |= EV_EOF;
4647 			kn->kn_fflags = so->so_error;
4648 			return (1);
4649 		}
4650 		return (!TAILQ_EMPTY(&so->sol_comp));
4651 	}
4652 
4653 	if ((so->so_rcv.sb_flags & SB_SPLICED) != 0)
4654 		return (0);
4655 
4656 	SOCK_RECVBUF_LOCK_ASSERT(so);
4657 
4658 	kn->kn_data = sbavail(&so->so_rcv) - so->so_rcv.sb_ctl;
4659 	if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
4660 		kn->kn_flags |= EV_EOF;
4661 		kn->kn_fflags = so->so_error;
4662 		return (1);
4663 	} else if (so->so_error || so->so_rerror)
4664 		return (1);
4665 
4666 	if (kn->kn_sfflags & NOTE_LOWAT) {
4667 		if (kn->kn_data >= kn->kn_sdata)
4668 			return (1);
4669 	} else if (sbavail(&so->so_rcv) >= so->so_rcv.sb_lowat)
4670 		return (1);
4671 
4672 #ifdef SOCKET_HHOOK
4673 	/* This hook returning non-zero indicates an event, not error */
4674 	return (hhook_run_socket(so, NULL, HHOOK_FILT_SOREAD));
4675 #else
4676 	return (0);
4677 #endif
4678 }
4679 
4680 static void
4681 filt_sowdetach(struct knote *kn)
4682 {
4683 	struct socket *so = kn->kn_fp->f_data;
4684 
4685 	so_wrknl_lock(so);
4686 	knlist_remove(&so->so_wrsel.si_note, kn, 1);
4687 	if (!SOLISTENING(so) && knlist_empty(&so->so_wrsel.si_note))
4688 		so->so_snd.sb_flags &= ~SB_KNOTE;
4689 	so_wrknl_unlock(so);
4690 }
4691 
4692 /*ARGSUSED*/
4693 static int
4694 filt_sowrite(struct knote *kn, long hint)
4695 {
4696 	struct socket *so;
4697 
4698 	so = kn->kn_fp->f_data;
4699 
4700 	if (SOLISTENING(so))
4701 		return (0);
4702 
4703 	SOCK_SENDBUF_LOCK_ASSERT(so);
4704 	kn->kn_data = sbspace(&so->so_snd);
4705 
4706 #ifdef SOCKET_HHOOK
4707 	hhook_run_socket(so, kn, HHOOK_FILT_SOWRITE);
4708 #endif
4709 
4710 	if (so->so_snd.sb_state & SBS_CANTSENDMORE) {
4711 		kn->kn_flags |= EV_EOF;
4712 		kn->kn_fflags = so->so_error;
4713 		return (1);
4714 	} else if (so->so_error)	/* temporary udp error */
4715 		return (1);
4716 	else if (((so->so_state & SS_ISCONNECTED) == 0) &&
4717 	    (so->so_proto->pr_flags & PR_CONNREQUIRED))
4718 		return (0);
4719 	else if (kn->kn_sfflags & NOTE_LOWAT)
4720 		return (kn->kn_data >= kn->kn_sdata);
4721 	else
4722 		return (kn->kn_data >= so->so_snd.sb_lowat);
4723 }
4724 
4725 static int
4726 filt_soempty(struct knote *kn, long hint)
4727 {
4728 	struct socket *so;
4729 
4730 	so = kn->kn_fp->f_data;
4731 
4732 	if (SOLISTENING(so))
4733 		return (1);
4734 
4735 	SOCK_SENDBUF_LOCK_ASSERT(so);
4736 	kn->kn_data = sbused(&so->so_snd);
4737 
4738 	if (kn->kn_data == 0)
4739 		return (1);
4740 	else
4741 		return (0);
4742 }
4743 
4744 int
4745 socheckuid(struct socket *so, uid_t uid)
4746 {
4747 
4748 	if (so == NULL)
4749 		return (EPERM);
4750 	if (so->so_cred->cr_uid != uid)
4751 		return (EPERM);
4752 	return (0);
4753 }
4754 
4755 /*
4756  * These functions are used by protocols to notify the socket layer (and its
4757  * consumers) of state changes in the sockets driven by protocol-side events.
4758  */
4759 
4760 /*
4761  * Procedures to manipulate state flags of socket and do appropriate wakeups.
4762  *
4763  * Normal sequence from the active (originating) side is that
4764  * soisconnecting() is called during processing of connect() call, resulting
4765  * in an eventual call to soisconnected() if/when the connection is
4766  * established.  When the connection is torn down soisdisconnecting() is
4767  * called during processing of disconnect() call, and soisdisconnected() is
4768  * called when the connection to the peer is totally severed.  The semantics
4769  * of these routines are such that connectionless protocols can call
4770  * soisconnected() and soisdisconnected() only, bypassing the in-progress
4771  * calls when setting up a ``connection'' takes no time.
4772  *
4773  * From the passive side, a socket is created with two queues of sockets:
4774  * so_incomp for connections in progress and so_comp for connections already
4775  * made and awaiting user acceptance.  As a protocol is preparing incoming
4776  * connections, it creates a socket structure queued on so_incomp by calling
4777  * sonewconn().  When the connection is established, soisconnected() is
4778  * called, and transfers the socket structure to so_comp, making it available
4779  * to accept().
4780  *
4781  * If a socket is closed with sockets on either so_incomp or so_comp, these
4782  * sockets are dropped.
4783  *
4784  * If higher-level protocols are implemented in the kernel, the wakeups done
4785  * here will sometimes cause software-interrupt process scheduling.
4786  */
4787 void
4788 soisconnecting(struct socket *so)
4789 {
4790 
4791 	SOCK_LOCK(so);
4792 	so->so_state &= ~(SS_ISCONNECTED|SS_ISDISCONNECTING);
4793 	so->so_state |= SS_ISCONNECTING;
4794 	SOCK_UNLOCK(so);
4795 }
4796 
4797 void
4798 soisconnected(struct socket *so)
4799 {
4800 	bool last __diagused;
4801 
4802 	SOCK_LOCK(so);
4803 	so->so_state &= ~(SS_ISCONNECTING|SS_ISDISCONNECTING);
4804 	so->so_state |= SS_ISCONNECTED;
4805 
4806 	if (so->so_qstate == SQ_INCOMP) {
4807 		struct socket *head = so->so_listen;
4808 		int ret;
4809 
4810 		KASSERT(head, ("%s: so %p on incomp of NULL", __func__, so));
4811 		/*
4812 		 * Promoting a socket from incomplete queue to complete, we
4813 		 * need to go through reverse order of locking.  We first do
4814 		 * trylock, and if that doesn't succeed, we go the hard way
4815 		 * leaving a reference and rechecking consistency after proper
4816 		 * locking.
4817 		 */
4818 		if (__predict_false(SOLISTEN_TRYLOCK(head) == 0)) {
4819 			soref(head);
4820 			SOCK_UNLOCK(so);
4821 			SOLISTEN_LOCK(head);
4822 			SOCK_LOCK(so);
4823 			if (__predict_false(head != so->so_listen)) {
4824 				/*
4825 				 * The socket went off the listen queue,
4826 				 * should be lost race to close(2) of sol.
4827 				 * The socket is about to soabort().
4828 				 */
4829 				SOCK_UNLOCK(so);
4830 				sorele_locked(head);
4831 				return;
4832 			}
4833 			last = refcount_release(&head->so_count);
4834 			KASSERT(!last, ("%s: released last reference for %p",
4835 			    __func__, head));
4836 		}
4837 again:
4838 		if ((so->so_options & SO_ACCEPTFILTER) == 0) {
4839 			TAILQ_REMOVE(&head->sol_incomp, so, so_list);
4840 			head->sol_incqlen--;
4841 			TAILQ_INSERT_TAIL(&head->sol_comp, so, so_list);
4842 			head->sol_qlen++;
4843 			so->so_qstate = SQ_COMP;
4844 			SOCK_UNLOCK(so);
4845 			solisten_wakeup(head);	/* unlocks */
4846 		} else {
4847 			SOCK_RECVBUF_LOCK(so);
4848 			soupcall_set(so, SO_RCV,
4849 			    head->sol_accept_filter->accf_callback,
4850 			    head->sol_accept_filter_arg);
4851 			so->so_options &= ~SO_ACCEPTFILTER;
4852 			ret = head->sol_accept_filter->accf_callback(so,
4853 			    head->sol_accept_filter_arg, M_NOWAIT);
4854 			if (ret == SU_ISCONNECTED) {
4855 				soupcall_clear(so, SO_RCV);
4856 				SOCK_RECVBUF_UNLOCK(so);
4857 				goto again;
4858 			}
4859 			SOCK_RECVBUF_UNLOCK(so);
4860 			SOCK_UNLOCK(so);
4861 			SOLISTEN_UNLOCK(head);
4862 		}
4863 		return;
4864 	}
4865 	SOCK_UNLOCK(so);
4866 	wakeup(&so->so_timeo);
4867 	sorwakeup(so);
4868 	sowwakeup(so);
4869 }
4870 
4871 void
4872 soisdisconnecting(struct socket *so)
4873 {
4874 
4875 	SOCK_LOCK(so);
4876 	so->so_state &= ~SS_ISCONNECTING;
4877 	so->so_state |= SS_ISDISCONNECTING;
4878 
4879 	if (!SOLISTENING(so)) {
4880 		SOCK_RECVBUF_LOCK(so);
4881 		socantrcvmore_locked(so);
4882 		SOCK_SENDBUF_LOCK(so);
4883 		socantsendmore_locked(so);
4884 	}
4885 	SOCK_UNLOCK(so);
4886 	wakeup(&so->so_timeo);
4887 }
4888 
4889 void
4890 soisdisconnected(struct socket *so)
4891 {
4892 
4893 	SOCK_LOCK(so);
4894 
4895 	/*
4896 	 * There is at least one reader of so_state that does not
4897 	 * acquire socket lock, namely soreceive_generic().  Ensure
4898 	 * that it never sees all flags that track connection status
4899 	 * cleared, by ordering the update with a barrier semantic of
4900 	 * our release thread fence.
4901 	 */
4902 	so->so_state |= SS_ISDISCONNECTED;
4903 	atomic_thread_fence_rel();
4904 	so->so_state &= ~(SS_ISCONNECTING|SS_ISCONNECTED|SS_ISDISCONNECTING);
4905 
4906 	if (!SOLISTENING(so)) {
4907 		SOCK_UNLOCK(so);
4908 		SOCK_RECVBUF_LOCK(so);
4909 		socantrcvmore_locked(so);
4910 		SOCK_SENDBUF_LOCK(so);
4911 		sbdrop_locked(&so->so_snd, sbused(&so->so_snd));
4912 		socantsendmore_locked(so);
4913 	} else
4914 		SOCK_UNLOCK(so);
4915 	wakeup(&so->so_timeo);
4916 }
4917 
4918 int
4919 soiolock(struct socket *so, struct sx *sx, int flags)
4920 {
4921 	int error;
4922 
4923 	KASSERT((flags & SBL_VALID) == flags,
4924 	    ("soiolock: invalid flags %#x", flags));
4925 
4926 	if ((flags & SBL_WAIT) != 0) {
4927 		if ((flags & SBL_NOINTR) != 0) {
4928 			sx_xlock(sx);
4929 		} else {
4930 			error = sx_xlock_sig(sx);
4931 			if (error != 0)
4932 				return (error);
4933 		}
4934 	} else if (!sx_try_xlock(sx)) {
4935 		return (EWOULDBLOCK);
4936 	}
4937 
4938 	if (__predict_false(SOLISTENING(so))) {
4939 		sx_xunlock(sx);
4940 		return (ENOTCONN);
4941 	}
4942 	return (0);
4943 }
4944 
4945 void
4946 soiounlock(struct sx *sx)
4947 {
4948 	sx_xunlock(sx);
4949 }
4950 
4951 /*
4952  * Make a copy of a sockaddr in a malloced buffer of type M_SONAME.
4953  */
4954 struct sockaddr *
4955 sodupsockaddr(const struct sockaddr *sa, int mflags)
4956 {
4957 	struct sockaddr *sa2;
4958 
4959 	sa2 = malloc(sa->sa_len, M_SONAME, mflags);
4960 	if (sa2)
4961 		memcpy(sa2, sa, sa->sa_len);
4962 	return sa2;
4963 }
4964 
4965 /*
4966  * Register per-socket destructor.
4967  */
4968 void
4969 sodtor_set(struct socket *so, so_dtor_t *func)
4970 {
4971 
4972 	SOCK_LOCK_ASSERT(so);
4973 	so->so_dtor = func;
4974 }
4975 
4976 /*
4977  * Register per-socket buffer upcalls.
4978  */
4979 void
4980 soupcall_set(struct socket *so, sb_which which, so_upcall_t func, void *arg)
4981 {
4982 	struct sockbuf *sb;
4983 
4984 	KASSERT(!SOLISTENING(so), ("%s: so %p listening", __func__, so));
4985 
4986 	switch (which) {
4987 	case SO_RCV:
4988 		sb = &so->so_rcv;
4989 		break;
4990 	case SO_SND:
4991 		sb = &so->so_snd;
4992 		break;
4993 	}
4994 	SOCK_BUF_LOCK_ASSERT(so, which);
4995 	sb->sb_upcall = func;
4996 	sb->sb_upcallarg = arg;
4997 	sb->sb_flags |= SB_UPCALL;
4998 }
4999 
5000 void
5001 soupcall_clear(struct socket *so, sb_which which)
5002 {
5003 	struct sockbuf *sb;
5004 
5005 	KASSERT(!SOLISTENING(so), ("%s: so %p listening", __func__, so));
5006 
5007 	switch (which) {
5008 	case SO_RCV:
5009 		sb = &so->so_rcv;
5010 		break;
5011 	case SO_SND:
5012 		sb = &so->so_snd;
5013 		break;
5014 	}
5015 	SOCK_BUF_LOCK_ASSERT(so, which);
5016 	KASSERT(sb->sb_upcall != NULL,
5017 	    ("%s: so %p no upcall to clear", __func__, so));
5018 	sb->sb_upcall = NULL;
5019 	sb->sb_upcallarg = NULL;
5020 	sb->sb_flags &= ~SB_UPCALL;
5021 }
5022 
5023 void
5024 solisten_upcall_set(struct socket *so, so_upcall_t func, void *arg)
5025 {
5026 
5027 	SOLISTEN_LOCK_ASSERT(so);
5028 	so->sol_upcall = func;
5029 	so->sol_upcallarg = arg;
5030 }
5031 
5032 static void
5033 so_rdknl_lock(void *arg)
5034 {
5035 	struct socket *so = arg;
5036 
5037 retry:
5038 	if (SOLISTENING(so)) {
5039 		SOLISTEN_LOCK(so);
5040 	} else {
5041 		SOCK_RECVBUF_LOCK(so);
5042 		if (__predict_false(SOLISTENING(so))) {
5043 			SOCK_RECVBUF_UNLOCK(so);
5044 			goto retry;
5045 		}
5046 	}
5047 }
5048 
5049 static void
5050 so_rdknl_unlock(void *arg)
5051 {
5052 	struct socket *so = arg;
5053 
5054 	if (SOLISTENING(so))
5055 		SOLISTEN_UNLOCK(so);
5056 	else
5057 		SOCK_RECVBUF_UNLOCK(so);
5058 }
5059 
5060 static void
5061 so_rdknl_assert_lock(void *arg, int what)
5062 {
5063 	struct socket *so = arg;
5064 
5065 	if (what == LA_LOCKED) {
5066 		if (SOLISTENING(so))
5067 			SOLISTEN_LOCK_ASSERT(so);
5068 		else
5069 			SOCK_RECVBUF_LOCK_ASSERT(so);
5070 	} else {
5071 		if (SOLISTENING(so))
5072 			SOLISTEN_UNLOCK_ASSERT(so);
5073 		else
5074 			SOCK_RECVBUF_UNLOCK_ASSERT(so);
5075 	}
5076 }
5077 
5078 static void
5079 so_wrknl_lock(void *arg)
5080 {
5081 	struct socket *so = arg;
5082 
5083 retry:
5084 	if (SOLISTENING(so)) {
5085 		SOLISTEN_LOCK(so);
5086 	} else {
5087 		SOCK_SENDBUF_LOCK(so);
5088 		if (__predict_false(SOLISTENING(so))) {
5089 			SOCK_SENDBUF_UNLOCK(so);
5090 			goto retry;
5091 		}
5092 	}
5093 }
5094 
5095 static void
5096 so_wrknl_unlock(void *arg)
5097 {
5098 	struct socket *so = arg;
5099 
5100 	if (SOLISTENING(so))
5101 		SOLISTEN_UNLOCK(so);
5102 	else
5103 		SOCK_SENDBUF_UNLOCK(so);
5104 }
5105 
5106 static void
5107 so_wrknl_assert_lock(void *arg, int what)
5108 {
5109 	struct socket *so = arg;
5110 
5111 	if (what == LA_LOCKED) {
5112 		if (SOLISTENING(so))
5113 			SOLISTEN_LOCK_ASSERT(so);
5114 		else
5115 			SOCK_SENDBUF_LOCK_ASSERT(so);
5116 	} else {
5117 		if (SOLISTENING(so))
5118 			SOLISTEN_UNLOCK_ASSERT(so);
5119 		else
5120 			SOCK_SENDBUF_UNLOCK_ASSERT(so);
5121 	}
5122 }
5123 
5124 /*
5125  * Create an external-format (``xsocket'') structure using the information in
5126  * the kernel-format socket structure pointed to by so.  This is done to
5127  * reduce the spew of irrelevant information over this interface, to isolate
5128  * user code from changes in the kernel structure, and potentially to provide
5129  * information-hiding if we decide that some of this information should be
5130  * hidden from users.
5131  */
5132 void
5133 sotoxsocket(struct socket *so, struct xsocket *xso)
5134 {
5135 
5136 	bzero(xso, sizeof(*xso));
5137 	xso->xso_len = sizeof *xso;
5138 	xso->xso_so = (uintptr_t)so;
5139 	xso->so_type = so->so_type;
5140 	xso->so_options = so->so_options;
5141 	xso->so_linger = so->so_linger;
5142 	xso->so_state = so->so_state;
5143 	xso->so_pcb = (uintptr_t)so->so_pcb;
5144 	xso->xso_protocol = so->so_proto->pr_protocol;
5145 	xso->xso_family = so->so_proto->pr_domain->dom_family;
5146 	xso->so_timeo = so->so_timeo;
5147 	xso->so_error = so->so_error;
5148 	xso->so_uid = so->so_cred->cr_uid;
5149 	xso->so_pgid = so->so_sigio ? so->so_sigio->sio_pgid : 0;
5150 	SOCK_LOCK(so);
5151 	xso->so_fibnum = so->so_fibnum;
5152 	if (SOLISTENING(so)) {
5153 		xso->so_qlen = so->sol_qlen;
5154 		xso->so_incqlen = so->sol_incqlen;
5155 		xso->so_qlimit = so->sol_qlimit;
5156 		xso->so_oobmark = 0;
5157 	} else {
5158 		xso->so_state |= so->so_qstate;
5159 		xso->so_qlen = xso->so_incqlen = xso->so_qlimit = 0;
5160 		xso->so_oobmark = so->so_oobmark;
5161 		sbtoxsockbuf(&so->so_snd, &xso->so_snd);
5162 		sbtoxsockbuf(&so->so_rcv, &xso->so_rcv);
5163 		if ((so->so_rcv.sb_flags & SB_SPLICED) != 0)
5164 			xso->so_splice_so = (uintptr_t)so->so_splice->dst;
5165 	}
5166 	SOCK_UNLOCK(so);
5167 }
5168 
5169 int
5170 so_options_get(const struct socket *so)
5171 {
5172 
5173 	return (so->so_options);
5174 }
5175 
5176 void
5177 so_options_set(struct socket *so, int val)
5178 {
5179 
5180 	so->so_options = val;
5181 }
5182 
5183 int
5184 so_error_get(const struct socket *so)
5185 {
5186 
5187 	return (so->so_error);
5188 }
5189 
5190 void
5191 so_error_set(struct socket *so, int val)
5192 {
5193 
5194 	so->so_error = val;
5195 }
5196