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