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