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