xref: /freebsd/sys/kern/uipc_socket.c (revision fd6b1cc34e4175c1e223f42540debb74cfe3c3e6)
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 
926 	soref(so);
927 
928 	return (so);
929 }
930 #endif	/* SCTP */
931 
932 int
933 sobind(struct socket *so, struct sockaddr *nam, struct thread *td)
934 {
935 	int error;
936 
937 	CURVNET_SET(so->so_vnet);
938 	error = so->so_proto->pr_bind(so, nam, td);
939 	CURVNET_RESTORE();
940 	return (error);
941 }
942 
943 int
944 sobindat(int fd, struct socket *so, struct sockaddr *nam, struct thread *td)
945 {
946 	int error;
947 
948 	CURVNET_SET(so->so_vnet);
949 	error = so->so_proto->pr_bindat(fd, so, nam, td);
950 	CURVNET_RESTORE();
951 	return (error);
952 }
953 
954 /*
955  * solisten() transitions a socket from a non-listening state to a listening
956  * state, but can also be used to update the listen queue depth on an
957  * existing listen socket.  The protocol will call back into the sockets
958  * layer using solisten_proto_check() and solisten_proto() to check and set
959  * socket-layer listen state.  Call backs are used so that the protocol can
960  * acquire both protocol and socket layer locks in whatever order is required
961  * by the protocol.
962  *
963  * Protocol implementors are advised to hold the socket lock across the
964  * socket-layer test and set to avoid races at the socket layer.
965  */
966 int
967 solisten(struct socket *so, int backlog, struct thread *td)
968 {
969 	int error;
970 
971 	CURVNET_SET(so->so_vnet);
972 	error = so->so_proto->pr_listen(so, backlog, td);
973 	CURVNET_RESTORE();
974 	return (error);
975 }
976 
977 /*
978  * Prepare for a call to solisten_proto().  Acquire all socket buffer locks in
979  * order to interlock with socket I/O.
980  */
981 int
982 solisten_proto_check(struct socket *so)
983 {
984 	SOCK_LOCK_ASSERT(so);
985 
986 	if ((so->so_state & (SS_ISCONNECTED | SS_ISCONNECTING |
987 	    SS_ISDISCONNECTING)) != 0)
988 		return (EINVAL);
989 
990 	/*
991 	 * Sleeping is not permitted here, so simply fail if userspace is
992 	 * attempting to transmit or receive on the socket.  This kind of
993 	 * transient failure is not ideal, but it should occur only if userspace
994 	 * is misusing the socket interfaces.
995 	 */
996 	if (!sx_try_xlock(&so->so_snd_sx))
997 		return (EAGAIN);
998 	if (!sx_try_xlock(&so->so_rcv_sx)) {
999 		sx_xunlock(&so->so_snd_sx);
1000 		return (EAGAIN);
1001 	}
1002 	mtx_lock(&so->so_snd_mtx);
1003 	mtx_lock(&so->so_rcv_mtx);
1004 
1005 	/* Interlock with soo_aio_queue() and KTLS. */
1006 	if (!SOLISTENING(so)) {
1007 		bool ktls;
1008 
1009 #ifdef KERN_TLS
1010 		ktls = so->so_snd.sb_tls_info != NULL ||
1011 		    so->so_rcv.sb_tls_info != NULL;
1012 #else
1013 		ktls = false;
1014 #endif
1015 		if (ktls ||
1016 		    (so->so_snd.sb_flags & (SB_AIO | SB_AIO_RUNNING)) != 0 ||
1017 		    (so->so_rcv.sb_flags & (SB_AIO | SB_AIO_RUNNING)) != 0) {
1018 			solisten_proto_abort(so);
1019 			return (EINVAL);
1020 		}
1021 	}
1022 
1023 	return (0);
1024 }
1025 
1026 /*
1027  * Undo the setup done by solisten_proto_check().
1028  */
1029 void
1030 solisten_proto_abort(struct socket *so)
1031 {
1032 	mtx_unlock(&so->so_snd_mtx);
1033 	mtx_unlock(&so->so_rcv_mtx);
1034 	sx_xunlock(&so->so_snd_sx);
1035 	sx_xunlock(&so->so_rcv_sx);
1036 }
1037 
1038 void
1039 solisten_proto(struct socket *so, int backlog)
1040 {
1041 	int sbrcv_lowat, sbsnd_lowat;
1042 	u_int sbrcv_hiwat, sbsnd_hiwat;
1043 	short sbrcv_flags, sbsnd_flags;
1044 	sbintime_t sbrcv_timeo, sbsnd_timeo;
1045 
1046 	SOCK_LOCK_ASSERT(so);
1047 	KASSERT((so->so_state & (SS_ISCONNECTED | SS_ISCONNECTING |
1048 	    SS_ISDISCONNECTING)) == 0,
1049 	    ("%s: bad socket state %p", __func__, so));
1050 
1051 	if (SOLISTENING(so))
1052 		goto listening;
1053 
1054 	/*
1055 	 * Change this socket to listening state.
1056 	 */
1057 	sbrcv_lowat = so->so_rcv.sb_lowat;
1058 	sbsnd_lowat = so->so_snd.sb_lowat;
1059 	sbrcv_hiwat = so->so_rcv.sb_hiwat;
1060 	sbsnd_hiwat = so->so_snd.sb_hiwat;
1061 	sbrcv_flags = so->so_rcv.sb_flags;
1062 	sbsnd_flags = so->so_snd.sb_flags;
1063 	sbrcv_timeo = so->so_rcv.sb_timeo;
1064 	sbsnd_timeo = so->so_snd.sb_timeo;
1065 
1066 	if (!(so->so_proto->pr_flags & PR_SOCKBUF)) {
1067 		sbdestroy(so, SO_SND);
1068 		sbdestroy(so, SO_RCV);
1069 	}
1070 
1071 #ifdef INVARIANTS
1072 	bzero(&so->so_rcv,
1073 	    sizeof(struct socket) - offsetof(struct socket, so_rcv));
1074 #endif
1075 
1076 	so->sol_sbrcv_lowat = sbrcv_lowat;
1077 	so->sol_sbsnd_lowat = sbsnd_lowat;
1078 	so->sol_sbrcv_hiwat = sbrcv_hiwat;
1079 	so->sol_sbsnd_hiwat = sbsnd_hiwat;
1080 	so->sol_sbrcv_flags = sbrcv_flags;
1081 	so->sol_sbsnd_flags = sbsnd_flags;
1082 	so->sol_sbrcv_timeo = sbrcv_timeo;
1083 	so->sol_sbsnd_timeo = sbsnd_timeo;
1084 
1085 	so->sol_qlen = so->sol_incqlen = 0;
1086 	TAILQ_INIT(&so->sol_incomp);
1087 	TAILQ_INIT(&so->sol_comp);
1088 
1089 	so->sol_accept_filter = NULL;
1090 	so->sol_accept_filter_arg = NULL;
1091 	so->sol_accept_filter_str = NULL;
1092 
1093 	so->sol_upcall = NULL;
1094 	so->sol_upcallarg = NULL;
1095 
1096 	so->so_options |= SO_ACCEPTCONN;
1097 
1098 listening:
1099 	if (backlog < 0 || backlog > somaxconn)
1100 		backlog = somaxconn;
1101 	so->sol_qlimit = backlog;
1102 
1103 	mtx_unlock(&so->so_snd_mtx);
1104 	mtx_unlock(&so->so_rcv_mtx);
1105 	sx_xunlock(&so->so_snd_sx);
1106 	sx_xunlock(&so->so_rcv_sx);
1107 }
1108 
1109 /*
1110  * Wakeup listeners/subsystems once we have a complete connection.
1111  * Enters with lock, returns unlocked.
1112  */
1113 void
1114 solisten_wakeup(struct socket *sol)
1115 {
1116 
1117 	if (sol->sol_upcall != NULL)
1118 		(void )sol->sol_upcall(sol, sol->sol_upcallarg, M_NOWAIT);
1119 	else {
1120 		selwakeuppri(&sol->so_rdsel, PSOCK);
1121 		KNOTE_LOCKED(&sol->so_rdsel.si_note, 0);
1122 	}
1123 	SOLISTEN_UNLOCK(sol);
1124 	wakeup_one(&sol->sol_comp);
1125 	if ((sol->so_state & SS_ASYNC) && sol->so_sigio != NULL)
1126 		pgsigio(&sol->so_sigio, SIGIO, 0);
1127 }
1128 
1129 /*
1130  * Return single connection off a listening socket queue.  Main consumer of
1131  * the function is kern_accept4().  Some modules, that do their own accept
1132  * management also use the function.  The socket reference held by the
1133  * listen queue is handed to the caller.
1134  *
1135  * Listening socket must be locked on entry and is returned unlocked on
1136  * return.
1137  * The flags argument is set of accept4(2) flags and ACCEPT4_INHERIT.
1138  */
1139 int
1140 solisten_dequeue(struct socket *head, struct socket **ret, int flags)
1141 {
1142 	struct socket *so;
1143 	int error;
1144 
1145 	SOLISTEN_LOCK_ASSERT(head);
1146 
1147 	while (!(head->so_state & SS_NBIO) && TAILQ_EMPTY(&head->sol_comp) &&
1148 	    head->so_error == 0) {
1149 		error = msleep(&head->sol_comp, SOCK_MTX(head), PSOCK | PCATCH,
1150 		    "accept", 0);
1151 		if (error != 0) {
1152 			SOLISTEN_UNLOCK(head);
1153 			return (error);
1154 		}
1155 	}
1156 	if (head->so_error) {
1157 		error = head->so_error;
1158 		head->so_error = 0;
1159 	} else if ((head->so_state & SS_NBIO) && TAILQ_EMPTY(&head->sol_comp))
1160 		error = EWOULDBLOCK;
1161 	else
1162 		error = 0;
1163 	if (error) {
1164 		SOLISTEN_UNLOCK(head);
1165 		return (error);
1166 	}
1167 	so = TAILQ_FIRST(&head->sol_comp);
1168 	SOCK_LOCK(so);
1169 	KASSERT(so->so_qstate == SQ_COMP,
1170 	    ("%s: so %p not SQ_COMP", __func__, so));
1171 	head->sol_qlen--;
1172 	so->so_qstate = SQ_NONE;
1173 	so->so_listen = NULL;
1174 	TAILQ_REMOVE(&head->sol_comp, so, so_list);
1175 	if (flags & ACCEPT4_INHERIT)
1176 		so->so_state |= (head->so_state & SS_NBIO);
1177 	else
1178 		so->so_state |= (flags & SOCK_NONBLOCK) ? SS_NBIO : 0;
1179 	SOCK_UNLOCK(so);
1180 	sorele_locked(head);
1181 
1182 	*ret = so;
1183 	return (0);
1184 }
1185 
1186 /*
1187  * Free socket upon release of the very last reference.
1188  */
1189 static void
1190 sofree(struct socket *so)
1191 {
1192 	struct protosw *pr = so->so_proto;
1193 
1194 	SOCK_LOCK_ASSERT(so);
1195 	KASSERT(refcount_load(&so->so_count) == 0,
1196 	    ("%s: so %p has references", __func__, so));
1197 	KASSERT(SOLISTENING(so) || so->so_qstate == SQ_NONE,
1198 	    ("%s: so %p is on listen queue", __func__, so));
1199 
1200 	SOCK_UNLOCK(so);
1201 
1202 	if (so->so_dtor != NULL)
1203 		so->so_dtor(so);
1204 
1205 	VNET_SO_ASSERT(so);
1206 	if (pr->pr_detach != NULL)
1207 		pr->pr_detach(so);
1208 
1209 	/*
1210 	 * From this point on, we assume that no other references to this
1211 	 * socket exist anywhere else in the stack.  Therefore, no locks need
1212 	 * to be acquired or held.
1213 	 */
1214 	if (!(pr->pr_flags & PR_SOCKBUF) && !SOLISTENING(so)) {
1215 		sbdestroy(so, SO_SND);
1216 		sbdestroy(so, SO_RCV);
1217 	}
1218 	seldrain(&so->so_rdsel);
1219 	seldrain(&so->so_wrsel);
1220 	knlist_destroy(&so->so_rdsel.si_note);
1221 	knlist_destroy(&so->so_wrsel.si_note);
1222 	sodealloc(so);
1223 }
1224 
1225 /*
1226  * Release a reference on a socket while holding the socket lock.
1227  * Unlocks the socket lock before returning.
1228  */
1229 void
1230 sorele_locked(struct socket *so)
1231 {
1232 	SOCK_LOCK_ASSERT(so);
1233 	if (refcount_release(&so->so_count))
1234 		sofree(so);
1235 	else
1236 		SOCK_UNLOCK(so);
1237 }
1238 
1239 /*
1240  * Close a socket on last file table reference removal.  Initiate disconnect
1241  * if connected.  Free socket when disconnect complete.
1242  *
1243  * This function will sorele() the socket.  Note that soclose() may be called
1244  * prior to the ref count reaching zero.  The actual socket structure will
1245  * not be freed until the ref count reaches zero.
1246  */
1247 int
1248 soclose(struct socket *so)
1249 {
1250 	struct accept_queue lqueue;
1251 	int error = 0;
1252 	bool listening, last __diagused;
1253 
1254 	CURVNET_SET(so->so_vnet);
1255 	funsetown(&so->so_sigio);
1256 	if (so->so_state & SS_ISCONNECTED) {
1257 		if ((so->so_state & SS_ISDISCONNECTING) == 0) {
1258 			error = sodisconnect(so);
1259 			if (error) {
1260 				if (error == ENOTCONN)
1261 					error = 0;
1262 				goto drop;
1263 			}
1264 		}
1265 
1266 		if ((so->so_options & SO_LINGER) != 0 && so->so_linger != 0) {
1267 			if ((so->so_state & SS_ISDISCONNECTING) &&
1268 			    (so->so_state & SS_NBIO))
1269 				goto drop;
1270 			while (so->so_state & SS_ISCONNECTED) {
1271 				error = tsleep(&so->so_timeo,
1272 				    PSOCK | PCATCH, "soclos",
1273 				    so->so_linger * hz);
1274 				if (error)
1275 					break;
1276 			}
1277 		}
1278 	}
1279 
1280 drop:
1281 	if (so->so_proto->pr_close != NULL)
1282 		so->so_proto->pr_close(so);
1283 
1284 	SOCK_LOCK(so);
1285 	if ((listening = SOLISTENING(so))) {
1286 		struct socket *sp;
1287 
1288 		TAILQ_INIT(&lqueue);
1289 		TAILQ_SWAP(&lqueue, &so->sol_incomp, socket, so_list);
1290 		TAILQ_CONCAT(&lqueue, &so->sol_comp, so_list);
1291 
1292 		so->sol_qlen = so->sol_incqlen = 0;
1293 
1294 		TAILQ_FOREACH(sp, &lqueue, so_list) {
1295 			SOCK_LOCK(sp);
1296 			sp->so_qstate = SQ_NONE;
1297 			sp->so_listen = NULL;
1298 			SOCK_UNLOCK(sp);
1299 			last = refcount_release(&so->so_count);
1300 			KASSERT(!last, ("%s: released last reference for %p",
1301 			    __func__, so));
1302 		}
1303 	}
1304 	sorele_locked(so);
1305 	if (listening) {
1306 		struct socket *sp, *tsp;
1307 
1308 		TAILQ_FOREACH_SAFE(sp, &lqueue, so_list, tsp)
1309 			soabort(sp);
1310 	}
1311 	CURVNET_RESTORE();
1312 	return (error);
1313 }
1314 
1315 /*
1316  * soabort() is used to abruptly tear down a connection, such as when a
1317  * resource limit is reached (listen queue depth exceeded), or if a listen
1318  * socket is closed while there are sockets waiting to be accepted.
1319  *
1320  * This interface is tricky, because it is called on an unreferenced socket,
1321  * and must be called only by a thread that has actually removed the socket
1322  * from the listen queue it was on.  Likely this thread holds the last
1323  * reference on the socket and soabort() will proceed with sofree().  But
1324  * it might be not the last, as the sockets on the listen queues are seen
1325  * from the protocol side.
1326  *
1327  * This interface will call into the protocol code, so must not be called
1328  * with any socket locks held.  Protocols do call it while holding their own
1329  * recursible protocol mutexes, but this is something that should be subject
1330  * to review in the future.
1331  *
1332  * Usually socket should have a single reference left, but this is not a
1333  * requirement.  In the past, when we have had named references for file
1334  * descriptor and protocol, we asserted that none of them are being held.
1335  */
1336 void
1337 soabort(struct socket *so)
1338 {
1339 
1340 	VNET_SO_ASSERT(so);
1341 
1342 	if (so->so_proto->pr_abort != NULL)
1343 		so->so_proto->pr_abort(so);
1344 	SOCK_LOCK(so);
1345 	sorele_locked(so);
1346 }
1347 
1348 int
1349 soaccept(struct socket *so, struct sockaddr *sa)
1350 {
1351 #ifdef INVARIANTS
1352 	u_char len = sa->sa_len;
1353 #endif
1354 	int error;
1355 
1356 	CURVNET_SET(so->so_vnet);
1357 	error = so->so_proto->pr_accept(so, sa);
1358 	KASSERT(sa->sa_len <= len,
1359 	    ("%s: protocol %p sockaddr overflow", __func__, so->so_proto));
1360 	CURVNET_RESTORE();
1361 	return (error);
1362 }
1363 
1364 int
1365 sopeeraddr(struct socket *so, struct sockaddr *sa)
1366 {
1367 #ifdef INVARIANTS
1368 	u_char len = sa->sa_len;
1369 #endif
1370 	int error;
1371 
1372 	CURVNET_SET(so->so_vnet);
1373 	error = so->so_proto->pr_peeraddr(so, sa);
1374 	KASSERT(sa->sa_len <= len,
1375 	    ("%s: protocol %p sockaddr overflow", __func__, so->so_proto));
1376 	CURVNET_RESTORE();
1377 
1378 	return (error);
1379 }
1380 
1381 int
1382 sosockaddr(struct socket *so, struct sockaddr *sa)
1383 {
1384 #ifdef INVARIANTS
1385 	u_char len = sa->sa_len;
1386 #endif
1387 	int error;
1388 
1389 	CURVNET_SET(so->so_vnet);
1390 	error = so->so_proto->pr_sockaddr(so, sa);
1391 	KASSERT(sa->sa_len <= len,
1392 	    ("%s: protocol %p sockaddr overflow", __func__, so->so_proto));
1393 	CURVNET_RESTORE();
1394 
1395 	return (error);
1396 }
1397 
1398 int
1399 soconnect(struct socket *so, struct sockaddr *nam, struct thread *td)
1400 {
1401 
1402 	return (soconnectat(AT_FDCWD, so, nam, td));
1403 }
1404 
1405 int
1406 soconnectat(int fd, struct socket *so, struct sockaddr *nam, struct thread *td)
1407 {
1408 	int error;
1409 
1410 	CURVNET_SET(so->so_vnet);
1411 
1412 	/*
1413 	 * If protocol is connection-based, can only connect once.
1414 	 * Otherwise, if connected, try to disconnect first.  This allows
1415 	 * user to disconnect by connecting to, e.g., a null address.
1416 	 *
1417 	 * Note, this check is racy and may need to be re-evaluated at the
1418 	 * protocol layer.
1419 	 */
1420 	if (so->so_state & (SS_ISCONNECTED|SS_ISCONNECTING) &&
1421 	    ((so->so_proto->pr_flags & PR_CONNREQUIRED) ||
1422 	    (error = sodisconnect(so)))) {
1423 		error = EISCONN;
1424 	} else {
1425 		/*
1426 		 * Prevent accumulated error from previous connection from
1427 		 * biting us.
1428 		 */
1429 		so->so_error = 0;
1430 		if (fd == AT_FDCWD) {
1431 			error = so->so_proto->pr_connect(so, nam, td);
1432 		} else {
1433 			error = so->so_proto->pr_connectat(fd, so, nam, td);
1434 		}
1435 	}
1436 	CURVNET_RESTORE();
1437 
1438 	return (error);
1439 }
1440 
1441 int
1442 soconnect2(struct socket *so1, struct socket *so2)
1443 {
1444 	int error;
1445 
1446 	CURVNET_SET(so1->so_vnet);
1447 	error = so1->so_proto->pr_connect2(so1, so2);
1448 	CURVNET_RESTORE();
1449 	return (error);
1450 }
1451 
1452 int
1453 sodisconnect(struct socket *so)
1454 {
1455 	int error;
1456 
1457 	if ((so->so_state & SS_ISCONNECTED) == 0)
1458 		return (ENOTCONN);
1459 	if (so->so_state & SS_ISDISCONNECTING)
1460 		return (EALREADY);
1461 	VNET_SO_ASSERT(so);
1462 	error = so->so_proto->pr_disconnect(so);
1463 	return (error);
1464 }
1465 
1466 int
1467 sosend_dgram(struct socket *so, struct sockaddr *addr, struct uio *uio,
1468     struct mbuf *top, struct mbuf *control, int flags, struct thread *td)
1469 {
1470 	long space;
1471 	ssize_t resid;
1472 	int clen = 0, error, dontroute;
1473 
1474 	KASSERT(so->so_type == SOCK_DGRAM, ("sosend_dgram: !SOCK_DGRAM"));
1475 	KASSERT(so->so_proto->pr_flags & PR_ATOMIC,
1476 	    ("sosend_dgram: !PR_ATOMIC"));
1477 
1478 	if (uio != NULL)
1479 		resid = uio->uio_resid;
1480 	else
1481 		resid = top->m_pkthdr.len;
1482 	/*
1483 	 * In theory resid should be unsigned.  However, space must be
1484 	 * signed, as it might be less than 0 if we over-committed, and we
1485 	 * must use a signed comparison of space and resid.  On the other
1486 	 * hand, a negative resid causes us to loop sending 0-length
1487 	 * segments to the protocol.
1488 	 */
1489 	if (resid < 0) {
1490 		error = EINVAL;
1491 		goto out;
1492 	}
1493 
1494 	dontroute =
1495 	    (flags & MSG_DONTROUTE) && (so->so_options & SO_DONTROUTE) == 0;
1496 	if (td != NULL)
1497 		td->td_ru.ru_msgsnd++;
1498 	if (control != NULL)
1499 		clen = control->m_len;
1500 
1501 	SOCKBUF_LOCK(&so->so_snd);
1502 	if (so->so_snd.sb_state & SBS_CANTSENDMORE) {
1503 		SOCKBUF_UNLOCK(&so->so_snd);
1504 		error = EPIPE;
1505 		goto out;
1506 	}
1507 	if (so->so_error) {
1508 		error = so->so_error;
1509 		so->so_error = 0;
1510 		SOCKBUF_UNLOCK(&so->so_snd);
1511 		goto out;
1512 	}
1513 	if ((so->so_state & SS_ISCONNECTED) == 0) {
1514 		/*
1515 		 * `sendto' and `sendmsg' is allowed on a connection-based
1516 		 * socket if it supports implied connect.  Return ENOTCONN if
1517 		 * not connected and no address is supplied.
1518 		 */
1519 		if ((so->so_proto->pr_flags & PR_CONNREQUIRED) &&
1520 		    (so->so_proto->pr_flags & PR_IMPLOPCL) == 0) {
1521 			if (!(resid == 0 && clen != 0)) {
1522 				SOCKBUF_UNLOCK(&so->so_snd);
1523 				error = ENOTCONN;
1524 				goto out;
1525 			}
1526 		} else if (addr == NULL) {
1527 			if (so->so_proto->pr_flags & PR_CONNREQUIRED)
1528 				error = ENOTCONN;
1529 			else
1530 				error = EDESTADDRREQ;
1531 			SOCKBUF_UNLOCK(&so->so_snd);
1532 			goto out;
1533 		}
1534 	}
1535 
1536 	/*
1537 	 * Do we need MSG_OOB support in SOCK_DGRAM?  Signs here may be a
1538 	 * problem and need fixing.
1539 	 */
1540 	space = sbspace(&so->so_snd);
1541 	if (flags & MSG_OOB)
1542 		space += 1024;
1543 	space -= clen;
1544 	SOCKBUF_UNLOCK(&so->so_snd);
1545 	if (resid > space) {
1546 		error = EMSGSIZE;
1547 		goto out;
1548 	}
1549 	if (uio == NULL) {
1550 		resid = 0;
1551 		if (flags & MSG_EOR)
1552 			top->m_flags |= M_EOR;
1553 	} else {
1554 		/*
1555 		 * Copy the data from userland into a mbuf chain.
1556 		 * If no data is to be copied in, a single empty mbuf
1557 		 * is returned.
1558 		 */
1559 		top = m_uiotombuf(uio, M_WAITOK, space, max_hdr,
1560 		    (M_PKTHDR | ((flags & MSG_EOR) ? M_EOR : 0)));
1561 		if (top == NULL) {
1562 			error = EFAULT;	/* only possible error */
1563 			goto out;
1564 		}
1565 		space -= resid - uio->uio_resid;
1566 		resid = uio->uio_resid;
1567 	}
1568 	KASSERT(resid == 0, ("sosend_dgram: resid != 0"));
1569 	/*
1570 	 * XXXRW: Frobbing SO_DONTROUTE here is even worse without sblock
1571 	 * than with.
1572 	 */
1573 	if (dontroute) {
1574 		SOCK_LOCK(so);
1575 		so->so_options |= SO_DONTROUTE;
1576 		SOCK_UNLOCK(so);
1577 	}
1578 	/*
1579 	 * XXX all the SBS_CANTSENDMORE checks previously done could be out
1580 	 * of date.  We could have received a reset packet in an interrupt or
1581 	 * maybe we slept while doing page faults in uiomove() etc.  We could
1582 	 * probably recheck again inside the locking protection here, but
1583 	 * there are probably other places that this also happens.  We must
1584 	 * rethink this.
1585 	 */
1586 	VNET_SO_ASSERT(so);
1587 	error = so->so_proto->pr_send(so, (flags & MSG_OOB) ? PRUS_OOB :
1588 	/*
1589 	 * If the user set MSG_EOF, the protocol understands this flag and
1590 	 * nothing left to send then use PRU_SEND_EOF instead of PRU_SEND.
1591 	 */
1592 	    ((flags & MSG_EOF) &&
1593 	     (so->so_proto->pr_flags & PR_IMPLOPCL) &&
1594 	     (resid <= 0)) ?
1595 		PRUS_EOF :
1596 		/* If there is more to send set PRUS_MORETOCOME */
1597 		(flags & MSG_MORETOCOME) ||
1598 		(resid > 0 && space > 0) ? PRUS_MORETOCOME : 0,
1599 		top, addr, control, td);
1600 	if (dontroute) {
1601 		SOCK_LOCK(so);
1602 		so->so_options &= ~SO_DONTROUTE;
1603 		SOCK_UNLOCK(so);
1604 	}
1605 	clen = 0;
1606 	control = NULL;
1607 	top = NULL;
1608 out:
1609 	if (top != NULL)
1610 		m_freem(top);
1611 	if (control != NULL)
1612 		m_freem(control);
1613 	return (error);
1614 }
1615 
1616 /*
1617  * Send on a socket.  If send must go all at once and message is larger than
1618  * send buffering, then hard error.  Lock against other senders.  If must go
1619  * all at once and not enough room now, then inform user that this would
1620  * block and do nothing.  Otherwise, if nonblocking, send as much as
1621  * possible.  The data to be sent is described by "uio" if nonzero, otherwise
1622  * by the mbuf chain "top" (which must be null if uio is not).  Data provided
1623  * in mbuf chain must be small enough to send all at once.
1624  *
1625  * Returns nonzero on error, timeout or signal; callers must check for short
1626  * counts if EINTR/ERESTART are returned.  Data and control buffers are freed
1627  * on return.
1628  */
1629 int
1630 sosend_generic(struct socket *so, struct sockaddr *addr, struct uio *uio,
1631     struct mbuf *top, struct mbuf *control, int flags, struct thread *td)
1632 {
1633 	long space;
1634 	ssize_t resid;
1635 	int clen = 0, error, dontroute;
1636 	int atomic = sosendallatonce(so) || top;
1637 	int pr_send_flag;
1638 #ifdef KERN_TLS
1639 	struct ktls_session *tls;
1640 	int tls_enq_cnt, tls_send_flag;
1641 	uint8_t tls_rtype;
1642 
1643 	tls = NULL;
1644 	tls_rtype = TLS_RLTYPE_APP;
1645 #endif
1646 	if (uio != NULL)
1647 		resid = uio->uio_resid;
1648 	else if ((top->m_flags & M_PKTHDR) != 0)
1649 		resid = top->m_pkthdr.len;
1650 	else
1651 		resid = m_length(top, NULL);
1652 	/*
1653 	 * In theory resid should be unsigned.  However, space must be
1654 	 * signed, as it might be less than 0 if we over-committed, and we
1655 	 * must use a signed comparison of space and resid.  On the other
1656 	 * hand, a negative resid causes us to loop sending 0-length
1657 	 * segments to the protocol.
1658 	 *
1659 	 * Also check to make sure that MSG_EOR isn't used on SOCK_STREAM
1660 	 * type sockets since that's an error.
1661 	 */
1662 	if (resid < 0 || (so->so_type == SOCK_STREAM && (flags & MSG_EOR))) {
1663 		error = EINVAL;
1664 		goto out;
1665 	}
1666 
1667 	dontroute =
1668 	    (flags & MSG_DONTROUTE) && (so->so_options & SO_DONTROUTE) == 0 &&
1669 	    (so->so_proto->pr_flags & PR_ATOMIC);
1670 	if (td != NULL)
1671 		td->td_ru.ru_msgsnd++;
1672 	if (control != NULL)
1673 		clen = control->m_len;
1674 
1675 	error = SOCK_IO_SEND_LOCK(so, SBLOCKWAIT(flags));
1676 	if (error)
1677 		goto out;
1678 
1679 #ifdef KERN_TLS
1680 	tls_send_flag = 0;
1681 	tls = ktls_hold(so->so_snd.sb_tls_info);
1682 	if (tls != NULL) {
1683 		if (tls->mode == TCP_TLS_MODE_SW)
1684 			tls_send_flag = PRUS_NOTREADY;
1685 
1686 		if (control != NULL) {
1687 			struct cmsghdr *cm = mtod(control, struct cmsghdr *);
1688 
1689 			if (clen >= sizeof(*cm) &&
1690 			    cm->cmsg_type == TLS_SET_RECORD_TYPE) {
1691 				tls_rtype = *((uint8_t *)CMSG_DATA(cm));
1692 				clen = 0;
1693 				m_freem(control);
1694 				control = NULL;
1695 				atomic = 1;
1696 			}
1697 		}
1698 
1699 		if (resid == 0 && !ktls_permit_empty_frames(tls)) {
1700 			error = EINVAL;
1701 			goto release;
1702 		}
1703 	}
1704 #endif
1705 
1706 restart:
1707 	do {
1708 		SOCKBUF_LOCK(&so->so_snd);
1709 		if (so->so_snd.sb_state & SBS_CANTSENDMORE) {
1710 			SOCKBUF_UNLOCK(&so->so_snd);
1711 			error = EPIPE;
1712 			goto release;
1713 		}
1714 		if (so->so_error) {
1715 			error = so->so_error;
1716 			so->so_error = 0;
1717 			SOCKBUF_UNLOCK(&so->so_snd);
1718 			goto release;
1719 		}
1720 		if ((so->so_state & SS_ISCONNECTED) == 0) {
1721 			/*
1722 			 * `sendto' and `sendmsg' is allowed on a connection-
1723 			 * based socket if it supports implied connect.
1724 			 * Return ENOTCONN if not connected and no address is
1725 			 * supplied.
1726 			 */
1727 			if ((so->so_proto->pr_flags & PR_CONNREQUIRED) &&
1728 			    (so->so_proto->pr_flags & PR_IMPLOPCL) == 0) {
1729 				if (!(resid == 0 && clen != 0)) {
1730 					SOCKBUF_UNLOCK(&so->so_snd);
1731 					error = ENOTCONN;
1732 					goto release;
1733 				}
1734 			} else if (addr == NULL) {
1735 				SOCKBUF_UNLOCK(&so->so_snd);
1736 				if (so->so_proto->pr_flags & PR_CONNREQUIRED)
1737 					error = ENOTCONN;
1738 				else
1739 					error = EDESTADDRREQ;
1740 				goto release;
1741 			}
1742 		}
1743 		space = sbspace(&so->so_snd);
1744 		if (flags & MSG_OOB)
1745 			space += 1024;
1746 		if ((atomic && resid > so->so_snd.sb_hiwat) ||
1747 		    clen > so->so_snd.sb_hiwat) {
1748 			SOCKBUF_UNLOCK(&so->so_snd);
1749 			error = EMSGSIZE;
1750 			goto release;
1751 		}
1752 		if (space < resid + clen &&
1753 		    (atomic || space < so->so_snd.sb_lowat || space < clen)) {
1754 			if ((so->so_state & SS_NBIO) ||
1755 			    (flags & (MSG_NBIO | MSG_DONTWAIT)) != 0) {
1756 				SOCKBUF_UNLOCK(&so->so_snd);
1757 				error = EWOULDBLOCK;
1758 				goto release;
1759 			}
1760 			error = sbwait(so, SO_SND);
1761 			SOCKBUF_UNLOCK(&so->so_snd);
1762 			if (error)
1763 				goto release;
1764 			goto restart;
1765 		}
1766 		SOCKBUF_UNLOCK(&so->so_snd);
1767 		space -= clen;
1768 		do {
1769 			if (uio == NULL) {
1770 				resid = 0;
1771 				if (flags & MSG_EOR)
1772 					top->m_flags |= M_EOR;
1773 #ifdef KERN_TLS
1774 				if (tls != NULL) {
1775 					ktls_frame(top, tls, &tls_enq_cnt,
1776 					    tls_rtype);
1777 					tls_rtype = TLS_RLTYPE_APP;
1778 				}
1779 #endif
1780 			} else {
1781 				/*
1782 				 * Copy the data from userland into a mbuf
1783 				 * chain.  If resid is 0, which can happen
1784 				 * only if we have control to send, then
1785 				 * a single empty mbuf is returned.  This
1786 				 * is a workaround to prevent protocol send
1787 				 * methods to panic.
1788 				 */
1789 #ifdef KERN_TLS
1790 				if (tls != NULL) {
1791 					top = m_uiotombuf(uio, M_WAITOK, space,
1792 					    tls->params.max_frame_len,
1793 					    M_EXTPG |
1794 					    ((flags & MSG_EOR) ? M_EOR : 0));
1795 					if (top != NULL) {
1796 						ktls_frame(top, tls,
1797 						    &tls_enq_cnt, tls_rtype);
1798 					}
1799 					tls_rtype = TLS_RLTYPE_APP;
1800 				} else
1801 #endif
1802 					top = m_uiotombuf(uio, M_WAITOK, space,
1803 					    (atomic ? max_hdr : 0),
1804 					    (atomic ? M_PKTHDR : 0) |
1805 					    ((flags & MSG_EOR) ? M_EOR : 0));
1806 				if (top == NULL) {
1807 					error = EFAULT; /* only possible error */
1808 					goto release;
1809 				}
1810 				space -= resid - uio->uio_resid;
1811 				resid = uio->uio_resid;
1812 			}
1813 			if (dontroute) {
1814 				SOCK_LOCK(so);
1815 				so->so_options |= SO_DONTROUTE;
1816 				SOCK_UNLOCK(so);
1817 			}
1818 			/*
1819 			 * XXX all the SBS_CANTSENDMORE checks previously
1820 			 * done could be out of date.  We could have received
1821 			 * a reset packet in an interrupt or maybe we slept
1822 			 * while doing page faults in uiomove() etc.  We
1823 			 * could probably recheck again inside the locking
1824 			 * protection here, but there are probably other
1825 			 * places that this also happens.  We must rethink
1826 			 * this.
1827 			 */
1828 			VNET_SO_ASSERT(so);
1829 
1830 			pr_send_flag = (flags & MSG_OOB) ? PRUS_OOB :
1831 			/*
1832 			 * If the user set MSG_EOF, the protocol understands
1833 			 * this flag and nothing left to send then use
1834 			 * PRU_SEND_EOF instead of PRU_SEND.
1835 			 */
1836 			    ((flags & MSG_EOF) &&
1837 			     (so->so_proto->pr_flags & PR_IMPLOPCL) &&
1838 			     (resid <= 0)) ?
1839 				PRUS_EOF :
1840 			/* If there is more to send set PRUS_MORETOCOME. */
1841 			    (flags & MSG_MORETOCOME) ||
1842 			    (resid > 0 && space > 0) ? PRUS_MORETOCOME : 0;
1843 
1844 #ifdef KERN_TLS
1845 			pr_send_flag |= tls_send_flag;
1846 #endif
1847 
1848 			error = so->so_proto->pr_send(so, pr_send_flag, top,
1849 			    addr, control, td);
1850 
1851 			if (dontroute) {
1852 				SOCK_LOCK(so);
1853 				so->so_options &= ~SO_DONTROUTE;
1854 				SOCK_UNLOCK(so);
1855 			}
1856 
1857 #ifdef KERN_TLS
1858 			if (tls != NULL && tls->mode == TCP_TLS_MODE_SW) {
1859 				if (error != 0) {
1860 					m_freem(top);
1861 					top = NULL;
1862 				} else {
1863 					soref(so);
1864 					ktls_enqueue(top, so, tls_enq_cnt);
1865 				}
1866 			}
1867 #endif
1868 			clen = 0;
1869 			control = NULL;
1870 			top = NULL;
1871 			if (error)
1872 				goto release;
1873 		} while (resid && space > 0);
1874 	} while (resid);
1875 
1876 release:
1877 	SOCK_IO_SEND_UNLOCK(so);
1878 out:
1879 #ifdef KERN_TLS
1880 	if (tls != NULL)
1881 		ktls_free(tls);
1882 #endif
1883 	if (top != NULL)
1884 		m_freem(top);
1885 	if (control != NULL)
1886 		m_freem(control);
1887 	return (error);
1888 }
1889 
1890 /*
1891  * Send to a socket from a kernel thread.
1892  *
1893  * XXXGL: in almost all cases uio is NULL and the mbuf is supplied.
1894  * Exception is nfs/bootp_subr.c.  It is arguable that the VNET context needs
1895  * to be set at all.  This function should just boil down to a static inline
1896  * calling the protocol method.
1897  */
1898 int
1899 sosend(struct socket *so, struct sockaddr *addr, struct uio *uio,
1900     struct mbuf *top, struct mbuf *control, int flags, struct thread *td)
1901 {
1902 	int error;
1903 
1904 	CURVNET_SET(so->so_vnet);
1905 	error = so->so_proto->pr_sosend(so, addr, uio,
1906 	    top, control, flags, td);
1907 	CURVNET_RESTORE();
1908 	return (error);
1909 }
1910 
1911 /*
1912  * send(2), write(2) or aio_write(2) on a socket.
1913  */
1914 int
1915 sousrsend(struct socket *so, struct sockaddr *addr, struct uio *uio,
1916     struct mbuf *control, int flags, struct proc *userproc)
1917 {
1918 	struct thread *td;
1919 	ssize_t len;
1920 	int error;
1921 
1922 	td = uio->uio_td;
1923 	len = uio->uio_resid;
1924 	CURVNET_SET(so->so_vnet);
1925 	error = so->so_proto->pr_sosend(so, addr, uio, NULL, control, flags,
1926 	    td);
1927 	CURVNET_RESTORE();
1928 	if (error != 0) {
1929 		/*
1930 		 * Clear transient errors for stream protocols if they made
1931 		 * some progress.  Make exclusion for aio(4) that would
1932 		 * schedule a new write in case of EWOULDBLOCK and clear
1933 		 * error itself.  See soaio_process_job().
1934 		 */
1935 		if (uio->uio_resid != len &&
1936 		    (so->so_proto->pr_flags & PR_ATOMIC) == 0 &&
1937 		    userproc == NULL &&
1938 		    (error == ERESTART || error == EINTR ||
1939 		    error == EWOULDBLOCK))
1940 			error = 0;
1941 		/* Generation of SIGPIPE can be controlled per socket. */
1942 		if (error == EPIPE && (so->so_options & SO_NOSIGPIPE) == 0 &&
1943 		    (flags & MSG_NOSIGNAL) == 0) {
1944 			if (userproc != NULL) {
1945 				/* aio(4) job */
1946 				PROC_LOCK(userproc);
1947 				kern_psignal(userproc, SIGPIPE);
1948 				PROC_UNLOCK(userproc);
1949 			} else {
1950 				PROC_LOCK(td->td_proc);
1951 				tdsignal(td, SIGPIPE);
1952 				PROC_UNLOCK(td->td_proc);
1953 			}
1954 		}
1955 	}
1956 	return (error);
1957 }
1958 
1959 /*
1960  * The part of soreceive() that implements reading non-inline out-of-band
1961  * data from a socket.  For more complete comments, see soreceive(), from
1962  * which this code originated.
1963  *
1964  * Note that soreceive_rcvoob(), unlike the remainder of soreceive(), is
1965  * unable to return an mbuf chain to the caller.
1966  */
1967 static int
1968 soreceive_rcvoob(struct socket *so, struct uio *uio, int flags)
1969 {
1970 	struct protosw *pr = so->so_proto;
1971 	struct mbuf *m;
1972 	int error;
1973 
1974 	KASSERT(flags & MSG_OOB, ("soreceive_rcvoob: (flags & MSG_OOB) == 0"));
1975 	VNET_SO_ASSERT(so);
1976 
1977 	m = m_get(M_WAITOK, MT_DATA);
1978 	error = pr->pr_rcvoob(so, m, flags & MSG_PEEK);
1979 	if (error)
1980 		goto bad;
1981 	do {
1982 		error = uiomove(mtod(m, void *),
1983 		    (int) min(uio->uio_resid, m->m_len), uio);
1984 		m = m_free(m);
1985 	} while (uio->uio_resid && error == 0 && m);
1986 bad:
1987 	if (m != NULL)
1988 		m_freem(m);
1989 	return (error);
1990 }
1991 
1992 /*
1993  * Following replacement or removal of the first mbuf on the first mbuf chain
1994  * of a socket buffer, push necessary state changes back into the socket
1995  * buffer so that other consumers see the values consistently.  'nextrecord'
1996  * is the callers locally stored value of the original value of
1997  * sb->sb_mb->m_nextpkt which must be restored when the lead mbuf changes.
1998  * NOTE: 'nextrecord' may be NULL.
1999  */
2000 static __inline void
2001 sockbuf_pushsync(struct sockbuf *sb, struct mbuf *nextrecord)
2002 {
2003 
2004 	SOCKBUF_LOCK_ASSERT(sb);
2005 	/*
2006 	 * First, update for the new value of nextrecord.  If necessary, make
2007 	 * it the first record.
2008 	 */
2009 	if (sb->sb_mb != NULL)
2010 		sb->sb_mb->m_nextpkt = nextrecord;
2011 	else
2012 		sb->sb_mb = nextrecord;
2013 
2014 	/*
2015 	 * Now update any dependent socket buffer fields to reflect the new
2016 	 * state.  This is an expanded inline of SB_EMPTY_FIXUP(), with the
2017 	 * addition of a second clause that takes care of the case where
2018 	 * sb_mb has been updated, but remains the last record.
2019 	 */
2020 	if (sb->sb_mb == NULL) {
2021 		sb->sb_mbtail = NULL;
2022 		sb->sb_lastrecord = NULL;
2023 	} else if (sb->sb_mb->m_nextpkt == NULL)
2024 		sb->sb_lastrecord = sb->sb_mb;
2025 }
2026 
2027 /*
2028  * Implement receive operations on a socket.  We depend on the way that
2029  * records are added to the sockbuf by sbappend.  In particular, each record
2030  * (mbufs linked through m_next) must begin with an address if the protocol
2031  * so specifies, followed by an optional mbuf or mbufs containing ancillary
2032  * data, and then zero or more mbufs of data.  In order to allow parallelism
2033  * between network receive and copying to user space, as well as avoid
2034  * sleeping with a mutex held, we release the socket buffer mutex during the
2035  * user space copy.  Although the sockbuf is locked, new data may still be
2036  * appended, and thus we must maintain consistency of the sockbuf during that
2037  * time.
2038  *
2039  * The caller may receive the data as a single mbuf chain by supplying an
2040  * mbuf **mp0 for use in returning the chain.  The uio is then used only for
2041  * the count in uio_resid.
2042  */
2043 int
2044 soreceive_generic(struct socket *so, struct sockaddr **psa, struct uio *uio,
2045     struct mbuf **mp0, struct mbuf **controlp, int *flagsp)
2046 {
2047 	struct mbuf *m, **mp;
2048 	int flags, error, offset;
2049 	ssize_t len;
2050 	struct protosw *pr = so->so_proto;
2051 	struct mbuf *nextrecord;
2052 	int moff, type = 0;
2053 	ssize_t orig_resid = uio->uio_resid;
2054 	bool report_real_len = false;
2055 
2056 	mp = mp0;
2057 	if (psa != NULL)
2058 		*psa = NULL;
2059 	if (controlp != NULL)
2060 		*controlp = NULL;
2061 	if (flagsp != NULL) {
2062 		report_real_len = *flagsp & MSG_TRUNC;
2063 		*flagsp &= ~MSG_TRUNC;
2064 		flags = *flagsp &~ MSG_EOR;
2065 	} else
2066 		flags = 0;
2067 	if (flags & MSG_OOB)
2068 		return (soreceive_rcvoob(so, uio, flags));
2069 	if (mp != NULL)
2070 		*mp = NULL;
2071 
2072 	error = SOCK_IO_RECV_LOCK(so, SBLOCKWAIT(flags));
2073 	if (error)
2074 		return (error);
2075 
2076 restart:
2077 	SOCKBUF_LOCK(&so->so_rcv);
2078 	m = so->so_rcv.sb_mb;
2079 	/*
2080 	 * If we have less data than requested, block awaiting more (subject
2081 	 * to any timeout) if:
2082 	 *   1. the current count is less than the low water mark, or
2083 	 *   2. MSG_DONTWAIT is not set
2084 	 */
2085 	if (m == NULL || (((flags & MSG_DONTWAIT) == 0 &&
2086 	    sbavail(&so->so_rcv) < uio->uio_resid) &&
2087 	    sbavail(&so->so_rcv) < so->so_rcv.sb_lowat &&
2088 	    m->m_nextpkt == NULL && (pr->pr_flags & PR_ATOMIC) == 0)) {
2089 		KASSERT(m != NULL || !sbavail(&so->so_rcv),
2090 		    ("receive: m == %p sbavail == %u",
2091 		    m, sbavail(&so->so_rcv)));
2092 		if (so->so_error || so->so_rerror) {
2093 			if (m != NULL)
2094 				goto dontblock;
2095 			if (so->so_error)
2096 				error = so->so_error;
2097 			else
2098 				error = so->so_rerror;
2099 			if ((flags & MSG_PEEK) == 0) {
2100 				if (so->so_error)
2101 					so->so_error = 0;
2102 				else
2103 					so->so_rerror = 0;
2104 			}
2105 			SOCKBUF_UNLOCK(&so->so_rcv);
2106 			goto release;
2107 		}
2108 		SOCKBUF_LOCK_ASSERT(&so->so_rcv);
2109 		if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
2110 			if (m != NULL)
2111 				goto dontblock;
2112 #ifdef KERN_TLS
2113 			else if (so->so_rcv.sb_tlsdcc == 0 &&
2114 			    so->so_rcv.sb_tlscc == 0) {
2115 #else
2116 			else {
2117 #endif
2118 				SOCKBUF_UNLOCK(&so->so_rcv);
2119 				goto release;
2120 			}
2121 		}
2122 		for (; m != NULL; m = m->m_next)
2123 			if (m->m_type == MT_OOBDATA  || (m->m_flags & M_EOR)) {
2124 				m = so->so_rcv.sb_mb;
2125 				goto dontblock;
2126 			}
2127 		if ((so->so_state & (SS_ISCONNECTING | SS_ISCONNECTED |
2128 		    SS_ISDISCONNECTING | SS_ISDISCONNECTED)) == 0 &&
2129 		    (so->so_proto->pr_flags & PR_CONNREQUIRED) != 0) {
2130 			SOCKBUF_UNLOCK(&so->so_rcv);
2131 			error = ENOTCONN;
2132 			goto release;
2133 		}
2134 		if (uio->uio_resid == 0 && !report_real_len) {
2135 			SOCKBUF_UNLOCK(&so->so_rcv);
2136 			goto release;
2137 		}
2138 		if ((so->so_state & SS_NBIO) ||
2139 		    (flags & (MSG_DONTWAIT|MSG_NBIO))) {
2140 			SOCKBUF_UNLOCK(&so->so_rcv);
2141 			error = EWOULDBLOCK;
2142 			goto release;
2143 		}
2144 		SBLASTRECORDCHK(&so->so_rcv);
2145 		SBLASTMBUFCHK(&so->so_rcv);
2146 		error = sbwait(so, SO_RCV);
2147 		SOCKBUF_UNLOCK(&so->so_rcv);
2148 		if (error)
2149 			goto release;
2150 		goto restart;
2151 	}
2152 dontblock:
2153 	/*
2154 	 * From this point onward, we maintain 'nextrecord' as a cache of the
2155 	 * pointer to the next record in the socket buffer.  We must keep the
2156 	 * various socket buffer pointers and local stack versions of the
2157 	 * pointers in sync, pushing out modifications before dropping the
2158 	 * socket buffer mutex, and re-reading them when picking it up.
2159 	 *
2160 	 * Otherwise, we will race with the network stack appending new data
2161 	 * or records onto the socket buffer by using inconsistent/stale
2162 	 * versions of the field, possibly resulting in socket buffer
2163 	 * corruption.
2164 	 *
2165 	 * By holding the high-level sblock(), we prevent simultaneous
2166 	 * readers from pulling off the front of the socket buffer.
2167 	 */
2168 	SOCKBUF_LOCK_ASSERT(&so->so_rcv);
2169 	if (uio->uio_td)
2170 		uio->uio_td->td_ru.ru_msgrcv++;
2171 	KASSERT(m == so->so_rcv.sb_mb, ("soreceive: m != so->so_rcv.sb_mb"));
2172 	SBLASTRECORDCHK(&so->so_rcv);
2173 	SBLASTMBUFCHK(&so->so_rcv);
2174 	nextrecord = m->m_nextpkt;
2175 	if (pr->pr_flags & PR_ADDR) {
2176 		KASSERT(m->m_type == MT_SONAME,
2177 		    ("m->m_type == %d", m->m_type));
2178 		orig_resid = 0;
2179 		if (psa != NULL)
2180 			*psa = sodupsockaddr(mtod(m, struct sockaddr *),
2181 			    M_NOWAIT);
2182 		if (flags & MSG_PEEK) {
2183 			m = m->m_next;
2184 		} else {
2185 			sbfree(&so->so_rcv, m);
2186 			so->so_rcv.sb_mb = m_free(m);
2187 			m = so->so_rcv.sb_mb;
2188 			sockbuf_pushsync(&so->so_rcv, nextrecord);
2189 		}
2190 	}
2191 
2192 	/*
2193 	 * Process one or more MT_CONTROL mbufs present before any data mbufs
2194 	 * in the first mbuf chain on the socket buffer.  If MSG_PEEK, we
2195 	 * just copy the data; if !MSG_PEEK, we call into the protocol to
2196 	 * perform externalization (or freeing if controlp == NULL).
2197 	 */
2198 	if (m != NULL && m->m_type == MT_CONTROL) {
2199 		struct mbuf *cm = NULL, *cmn;
2200 		struct mbuf **cme = &cm;
2201 #ifdef KERN_TLS
2202 		struct cmsghdr *cmsg;
2203 		struct tls_get_record tgr;
2204 
2205 		/*
2206 		 * For MSG_TLSAPPDATA, check for an alert record.
2207 		 * If found, return ENXIO without removing
2208 		 * it from the receive queue.  This allows a subsequent
2209 		 * call without MSG_TLSAPPDATA to receive it.
2210 		 * Note that, for TLS, there should only be a single
2211 		 * control mbuf with the TLS_GET_RECORD message in it.
2212 		 */
2213 		if (flags & MSG_TLSAPPDATA) {
2214 			cmsg = mtod(m, struct cmsghdr *);
2215 			if (cmsg->cmsg_type == TLS_GET_RECORD &&
2216 			    cmsg->cmsg_len == CMSG_LEN(sizeof(tgr))) {
2217 				memcpy(&tgr, CMSG_DATA(cmsg), sizeof(tgr));
2218 				if (__predict_false(tgr.tls_type ==
2219 				    TLS_RLTYPE_ALERT)) {
2220 					SOCKBUF_UNLOCK(&so->so_rcv);
2221 					error = ENXIO;
2222 					goto release;
2223 				}
2224 			}
2225 		}
2226 #endif
2227 
2228 		do {
2229 			if (flags & MSG_PEEK) {
2230 				if (controlp != NULL) {
2231 					*controlp = m_copym(m, 0, m->m_len,
2232 					    M_NOWAIT);
2233 					controlp = &(*controlp)->m_next;
2234 				}
2235 				m = m->m_next;
2236 			} else {
2237 				sbfree(&so->so_rcv, m);
2238 				so->so_rcv.sb_mb = m->m_next;
2239 				m->m_next = NULL;
2240 				*cme = m;
2241 				cme = &(*cme)->m_next;
2242 				m = so->so_rcv.sb_mb;
2243 			}
2244 		} while (m != NULL && m->m_type == MT_CONTROL);
2245 		if ((flags & MSG_PEEK) == 0)
2246 			sockbuf_pushsync(&so->so_rcv, nextrecord);
2247 		while (cm != NULL) {
2248 			cmn = cm->m_next;
2249 			cm->m_next = NULL;
2250 			if (pr->pr_domain->dom_externalize != NULL) {
2251 				SOCKBUF_UNLOCK(&so->so_rcv);
2252 				VNET_SO_ASSERT(so);
2253 				error = (*pr->pr_domain->dom_externalize)
2254 				    (cm, controlp, flags);
2255 				SOCKBUF_LOCK(&so->so_rcv);
2256 			} else if (controlp != NULL)
2257 				*controlp = cm;
2258 			else
2259 				m_freem(cm);
2260 			if (controlp != NULL) {
2261 				while (*controlp != NULL)
2262 					controlp = &(*controlp)->m_next;
2263 			}
2264 			cm = cmn;
2265 		}
2266 		if (m != NULL)
2267 			nextrecord = so->so_rcv.sb_mb->m_nextpkt;
2268 		else
2269 			nextrecord = so->so_rcv.sb_mb;
2270 		orig_resid = 0;
2271 	}
2272 	if (m != NULL) {
2273 		if ((flags & MSG_PEEK) == 0) {
2274 			KASSERT(m->m_nextpkt == nextrecord,
2275 			    ("soreceive: post-control, nextrecord !sync"));
2276 			if (nextrecord == NULL) {
2277 				KASSERT(so->so_rcv.sb_mb == m,
2278 				    ("soreceive: post-control, sb_mb!=m"));
2279 				KASSERT(so->so_rcv.sb_lastrecord == m,
2280 				    ("soreceive: post-control, lastrecord!=m"));
2281 			}
2282 		}
2283 		type = m->m_type;
2284 		if (type == MT_OOBDATA)
2285 			flags |= MSG_OOB;
2286 	} else {
2287 		if ((flags & MSG_PEEK) == 0) {
2288 			KASSERT(so->so_rcv.sb_mb == nextrecord,
2289 			    ("soreceive: sb_mb != nextrecord"));
2290 			if (so->so_rcv.sb_mb == NULL) {
2291 				KASSERT(so->so_rcv.sb_lastrecord == NULL,
2292 				    ("soreceive: sb_lastercord != NULL"));
2293 			}
2294 		}
2295 	}
2296 	SOCKBUF_LOCK_ASSERT(&so->so_rcv);
2297 	SBLASTRECORDCHK(&so->so_rcv);
2298 	SBLASTMBUFCHK(&so->so_rcv);
2299 
2300 	/*
2301 	 * Now continue to read any data mbufs off of the head of the socket
2302 	 * buffer until the read request is satisfied.  Note that 'type' is
2303 	 * used to store the type of any mbuf reads that have happened so far
2304 	 * such that soreceive() can stop reading if the type changes, which
2305 	 * causes soreceive() to return only one of regular data and inline
2306 	 * out-of-band data in a single socket receive operation.
2307 	 */
2308 	moff = 0;
2309 	offset = 0;
2310 	while (m != NULL && !(m->m_flags & M_NOTAVAIL) && uio->uio_resid > 0
2311 	    && error == 0) {
2312 		/*
2313 		 * If the type of mbuf has changed since the last mbuf
2314 		 * examined ('type'), end the receive operation.
2315 		 */
2316 		SOCKBUF_LOCK_ASSERT(&so->so_rcv);
2317 		if (m->m_type == MT_OOBDATA || m->m_type == MT_CONTROL) {
2318 			if (type != m->m_type)
2319 				break;
2320 		} else if (type == MT_OOBDATA)
2321 			break;
2322 		else
2323 		    KASSERT(m->m_type == MT_DATA,
2324 			("m->m_type == %d", m->m_type));
2325 		so->so_rcv.sb_state &= ~SBS_RCVATMARK;
2326 		len = uio->uio_resid;
2327 		if (so->so_oobmark && len > so->so_oobmark - offset)
2328 			len = so->so_oobmark - offset;
2329 		if (len > m->m_len - moff)
2330 			len = m->m_len - moff;
2331 		/*
2332 		 * If mp is set, just pass back the mbufs.  Otherwise copy
2333 		 * them out via the uio, then free.  Sockbuf must be
2334 		 * consistent here (points to current mbuf, it points to next
2335 		 * record) when we drop priority; we must note any additions
2336 		 * to the sockbuf when we block interrupts again.
2337 		 */
2338 		if (mp == NULL) {
2339 			SOCKBUF_LOCK_ASSERT(&so->so_rcv);
2340 			SBLASTRECORDCHK(&so->so_rcv);
2341 			SBLASTMBUFCHK(&so->so_rcv);
2342 			SOCKBUF_UNLOCK(&so->so_rcv);
2343 			if ((m->m_flags & M_EXTPG) != 0)
2344 				error = m_unmapped_uiomove(m, moff, uio,
2345 				    (int)len);
2346 			else
2347 				error = uiomove(mtod(m, char *) + moff,
2348 				    (int)len, uio);
2349 			SOCKBUF_LOCK(&so->so_rcv);
2350 			if (error) {
2351 				/*
2352 				 * The MT_SONAME mbuf has already been removed
2353 				 * from the record, so it is necessary to
2354 				 * remove the data mbufs, if any, to preserve
2355 				 * the invariant in the case of PR_ADDR that
2356 				 * requires MT_SONAME mbufs at the head of
2357 				 * each record.
2358 				 */
2359 				if (pr->pr_flags & PR_ATOMIC &&
2360 				    ((flags & MSG_PEEK) == 0))
2361 					(void)sbdroprecord_locked(&so->so_rcv);
2362 				SOCKBUF_UNLOCK(&so->so_rcv);
2363 				goto release;
2364 			}
2365 		} else
2366 			uio->uio_resid -= len;
2367 		SOCKBUF_LOCK_ASSERT(&so->so_rcv);
2368 		if (len == m->m_len - moff) {
2369 			if (m->m_flags & M_EOR)
2370 				flags |= MSG_EOR;
2371 			if (flags & MSG_PEEK) {
2372 				m = m->m_next;
2373 				moff = 0;
2374 			} else {
2375 				nextrecord = m->m_nextpkt;
2376 				sbfree(&so->so_rcv, m);
2377 				if (mp != NULL) {
2378 					m->m_nextpkt = NULL;
2379 					*mp = m;
2380 					mp = &m->m_next;
2381 					so->so_rcv.sb_mb = m = m->m_next;
2382 					*mp = NULL;
2383 				} else {
2384 					so->so_rcv.sb_mb = m_free(m);
2385 					m = so->so_rcv.sb_mb;
2386 				}
2387 				sockbuf_pushsync(&so->so_rcv, nextrecord);
2388 				SBLASTRECORDCHK(&so->so_rcv);
2389 				SBLASTMBUFCHK(&so->so_rcv);
2390 			}
2391 		} else {
2392 			if (flags & MSG_PEEK)
2393 				moff += len;
2394 			else {
2395 				if (mp != NULL) {
2396 					if (flags & MSG_DONTWAIT) {
2397 						*mp = m_copym(m, 0, len,
2398 						    M_NOWAIT);
2399 						if (*mp == NULL) {
2400 							/*
2401 							 * m_copym() couldn't
2402 							 * allocate an mbuf.
2403 							 * Adjust uio_resid back
2404 							 * (it was adjusted
2405 							 * down by len bytes,
2406 							 * which we didn't end
2407 							 * up "copying" over).
2408 							 */
2409 							uio->uio_resid += len;
2410 							break;
2411 						}
2412 					} else {
2413 						SOCKBUF_UNLOCK(&so->so_rcv);
2414 						*mp = m_copym(m, 0, len,
2415 						    M_WAITOK);
2416 						SOCKBUF_LOCK(&so->so_rcv);
2417 					}
2418 				}
2419 				sbcut_locked(&so->so_rcv, len);
2420 			}
2421 		}
2422 		SOCKBUF_LOCK_ASSERT(&so->so_rcv);
2423 		if (so->so_oobmark) {
2424 			if ((flags & MSG_PEEK) == 0) {
2425 				so->so_oobmark -= len;
2426 				if (so->so_oobmark == 0) {
2427 					so->so_rcv.sb_state |= SBS_RCVATMARK;
2428 					break;
2429 				}
2430 			} else {
2431 				offset += len;
2432 				if (offset == so->so_oobmark)
2433 					break;
2434 			}
2435 		}
2436 		if (flags & MSG_EOR)
2437 			break;
2438 		/*
2439 		 * If the MSG_WAITALL flag is set (for non-atomic socket), we
2440 		 * must not quit until "uio->uio_resid == 0" or an error
2441 		 * termination.  If a signal/timeout occurs, return with a
2442 		 * short count but without error.  Keep sockbuf locked
2443 		 * against other readers.
2444 		 */
2445 		while (flags & MSG_WAITALL && m == NULL && uio->uio_resid > 0 &&
2446 		    !sosendallatonce(so) && nextrecord == NULL) {
2447 			SOCKBUF_LOCK_ASSERT(&so->so_rcv);
2448 			if (so->so_error || so->so_rerror ||
2449 			    so->so_rcv.sb_state & SBS_CANTRCVMORE)
2450 				break;
2451 			/*
2452 			 * Notify the protocol that some data has been
2453 			 * drained before blocking.
2454 			 */
2455 			if (pr->pr_flags & PR_WANTRCVD) {
2456 				SOCKBUF_UNLOCK(&so->so_rcv);
2457 				VNET_SO_ASSERT(so);
2458 				pr->pr_rcvd(so, flags);
2459 				SOCKBUF_LOCK(&so->so_rcv);
2460 				if (__predict_false(so->so_rcv.sb_mb == NULL &&
2461 				    (so->so_error || so->so_rerror ||
2462 				    so->so_rcv.sb_state & SBS_CANTRCVMORE)))
2463 					break;
2464 			}
2465 			SBLASTRECORDCHK(&so->so_rcv);
2466 			SBLASTMBUFCHK(&so->so_rcv);
2467 			/*
2468 			 * We could receive some data while was notifying
2469 			 * the protocol. Skip blocking in this case.
2470 			 */
2471 			if (so->so_rcv.sb_mb == NULL) {
2472 				error = sbwait(so, SO_RCV);
2473 				if (error) {
2474 					SOCKBUF_UNLOCK(&so->so_rcv);
2475 					goto release;
2476 				}
2477 			}
2478 			m = so->so_rcv.sb_mb;
2479 			if (m != NULL)
2480 				nextrecord = m->m_nextpkt;
2481 		}
2482 	}
2483 
2484 	SOCKBUF_LOCK_ASSERT(&so->so_rcv);
2485 	if (m != NULL && pr->pr_flags & PR_ATOMIC) {
2486 		if (report_real_len)
2487 			uio->uio_resid -= m_length(m, NULL) - moff;
2488 		flags |= MSG_TRUNC;
2489 		if ((flags & MSG_PEEK) == 0)
2490 			(void) sbdroprecord_locked(&so->so_rcv);
2491 	}
2492 	if ((flags & MSG_PEEK) == 0) {
2493 		if (m == NULL) {
2494 			/*
2495 			 * First part is an inline SB_EMPTY_FIXUP().  Second
2496 			 * part makes sure sb_lastrecord is up-to-date if
2497 			 * there is still data in the socket buffer.
2498 			 */
2499 			so->so_rcv.sb_mb = nextrecord;
2500 			if (so->so_rcv.sb_mb == NULL) {
2501 				so->so_rcv.sb_mbtail = NULL;
2502 				so->so_rcv.sb_lastrecord = NULL;
2503 			} else if (nextrecord->m_nextpkt == NULL)
2504 				so->so_rcv.sb_lastrecord = nextrecord;
2505 		}
2506 		SBLASTRECORDCHK(&so->so_rcv);
2507 		SBLASTMBUFCHK(&so->so_rcv);
2508 		/*
2509 		 * If soreceive() is being done from the socket callback,
2510 		 * then don't need to generate ACK to peer to update window,
2511 		 * since ACK will be generated on return to TCP.
2512 		 */
2513 		if (!(flags & MSG_SOCALLBCK) &&
2514 		    (pr->pr_flags & PR_WANTRCVD)) {
2515 			SOCKBUF_UNLOCK(&so->so_rcv);
2516 			VNET_SO_ASSERT(so);
2517 			pr->pr_rcvd(so, flags);
2518 			SOCKBUF_LOCK(&so->so_rcv);
2519 		}
2520 	}
2521 	SOCKBUF_LOCK_ASSERT(&so->so_rcv);
2522 	if (orig_resid == uio->uio_resid && orig_resid &&
2523 	    (flags & MSG_EOR) == 0 && (so->so_rcv.sb_state & SBS_CANTRCVMORE) == 0) {
2524 		SOCKBUF_UNLOCK(&so->so_rcv);
2525 		goto restart;
2526 	}
2527 	SOCKBUF_UNLOCK(&so->so_rcv);
2528 
2529 	if (flagsp != NULL)
2530 		*flagsp |= flags;
2531 release:
2532 	SOCK_IO_RECV_UNLOCK(so);
2533 	return (error);
2534 }
2535 
2536 /*
2537  * Optimized version of soreceive() for stream (TCP) sockets.
2538  */
2539 int
2540 soreceive_stream(struct socket *so, struct sockaddr **psa, struct uio *uio,
2541     struct mbuf **mp0, struct mbuf **controlp, int *flagsp)
2542 {
2543 	int len = 0, error = 0, flags, oresid;
2544 	struct sockbuf *sb;
2545 	struct mbuf *m, *n = NULL;
2546 
2547 	/* We only do stream sockets. */
2548 	if (so->so_type != SOCK_STREAM)
2549 		return (EINVAL);
2550 	if (psa != NULL)
2551 		*psa = NULL;
2552 	if (flagsp != NULL)
2553 		flags = *flagsp &~ MSG_EOR;
2554 	else
2555 		flags = 0;
2556 	if (controlp != NULL)
2557 		*controlp = NULL;
2558 	if (flags & MSG_OOB)
2559 		return (soreceive_rcvoob(so, uio, flags));
2560 	if (mp0 != NULL)
2561 		*mp0 = NULL;
2562 
2563 	sb = &so->so_rcv;
2564 
2565 #ifdef KERN_TLS
2566 	/*
2567 	 * KTLS store TLS records as records with a control message to
2568 	 * describe the framing.
2569 	 *
2570 	 * We check once here before acquiring locks to optimize the
2571 	 * common case.
2572 	 */
2573 	if (sb->sb_tls_info != NULL)
2574 		return (soreceive_generic(so, psa, uio, mp0, controlp,
2575 		    flagsp));
2576 #endif
2577 
2578 	/* Prevent other readers from entering the socket. */
2579 	error = SOCK_IO_RECV_LOCK(so, SBLOCKWAIT(flags));
2580 	if (error)
2581 		return (error);
2582 	SOCKBUF_LOCK(sb);
2583 
2584 #ifdef KERN_TLS
2585 	if (sb->sb_tls_info != NULL) {
2586 		SOCKBUF_UNLOCK(sb);
2587 		SOCK_IO_RECV_UNLOCK(so);
2588 		return (soreceive_generic(so, psa, uio, mp0, controlp,
2589 		    flagsp));
2590 	}
2591 #endif
2592 
2593 	/* Easy one, no space to copyout anything. */
2594 	if (uio->uio_resid == 0) {
2595 		error = EINVAL;
2596 		goto out;
2597 	}
2598 	oresid = uio->uio_resid;
2599 
2600 	/* We will never ever get anything unless we are or were connected. */
2601 	if (!(so->so_state & (SS_ISCONNECTED|SS_ISDISCONNECTED))) {
2602 		error = ENOTCONN;
2603 		goto out;
2604 	}
2605 
2606 restart:
2607 	SOCKBUF_LOCK_ASSERT(&so->so_rcv);
2608 
2609 	/* Abort if socket has reported problems. */
2610 	if (so->so_error) {
2611 		if (sbavail(sb) > 0)
2612 			goto deliver;
2613 		if (oresid > uio->uio_resid)
2614 			goto out;
2615 		error = so->so_error;
2616 		if (!(flags & MSG_PEEK))
2617 			so->so_error = 0;
2618 		goto out;
2619 	}
2620 
2621 	/* Door is closed.  Deliver what is left, if any. */
2622 	if (sb->sb_state & SBS_CANTRCVMORE) {
2623 		if (sbavail(sb) > 0)
2624 			goto deliver;
2625 		else
2626 			goto out;
2627 	}
2628 
2629 	/* Socket buffer is empty and we shall not block. */
2630 	if (sbavail(sb) == 0 &&
2631 	    ((so->so_state & SS_NBIO) || (flags & (MSG_DONTWAIT|MSG_NBIO)))) {
2632 		error = EAGAIN;
2633 		goto out;
2634 	}
2635 
2636 	/* Socket buffer got some data that we shall deliver now. */
2637 	if (sbavail(sb) > 0 && !(flags & MSG_WAITALL) &&
2638 	    ((so->so_state & SS_NBIO) ||
2639 	     (flags & (MSG_DONTWAIT|MSG_NBIO)) ||
2640 	     sbavail(sb) >= sb->sb_lowat ||
2641 	     sbavail(sb) >= uio->uio_resid ||
2642 	     sbavail(sb) >= sb->sb_hiwat) ) {
2643 		goto deliver;
2644 	}
2645 
2646 	/* On MSG_WAITALL we must wait until all data or error arrives. */
2647 	if ((flags & MSG_WAITALL) &&
2648 	    (sbavail(sb) >= uio->uio_resid || sbavail(sb) >= sb->sb_hiwat))
2649 		goto deliver;
2650 
2651 	/*
2652 	 * Wait and block until (more) data comes in.
2653 	 * NB: Drops the sockbuf lock during wait.
2654 	 */
2655 	error = sbwait(so, SO_RCV);
2656 	if (error)
2657 		goto out;
2658 	goto restart;
2659 
2660 deliver:
2661 	SOCKBUF_LOCK_ASSERT(&so->so_rcv);
2662 	KASSERT(sbavail(sb) > 0, ("%s: sockbuf empty", __func__));
2663 	KASSERT(sb->sb_mb != NULL, ("%s: sb_mb == NULL", __func__));
2664 
2665 	/* Statistics. */
2666 	if (uio->uio_td)
2667 		uio->uio_td->td_ru.ru_msgrcv++;
2668 
2669 	/* Fill uio until full or current end of socket buffer is reached. */
2670 	len = min(uio->uio_resid, sbavail(sb));
2671 	if (mp0 != NULL) {
2672 		/* Dequeue as many mbufs as possible. */
2673 		if (!(flags & MSG_PEEK) && len >= sb->sb_mb->m_len) {
2674 			if (*mp0 == NULL)
2675 				*mp0 = sb->sb_mb;
2676 			else
2677 				m_cat(*mp0, sb->sb_mb);
2678 			for (m = sb->sb_mb;
2679 			     m != NULL && m->m_len <= len;
2680 			     m = m->m_next) {
2681 				KASSERT(!(m->m_flags & M_NOTAVAIL),
2682 				    ("%s: m %p not available", __func__, m));
2683 				len -= m->m_len;
2684 				uio->uio_resid -= m->m_len;
2685 				sbfree(sb, m);
2686 				n = m;
2687 			}
2688 			n->m_next = NULL;
2689 			sb->sb_mb = m;
2690 			sb->sb_lastrecord = sb->sb_mb;
2691 			if (sb->sb_mb == NULL)
2692 				SB_EMPTY_FIXUP(sb);
2693 		}
2694 		/* Copy the remainder. */
2695 		if (len > 0) {
2696 			KASSERT(sb->sb_mb != NULL,
2697 			    ("%s: len > 0 && sb->sb_mb empty", __func__));
2698 
2699 			m = m_copym(sb->sb_mb, 0, len, M_NOWAIT);
2700 			if (m == NULL)
2701 				len = 0;	/* Don't flush data from sockbuf. */
2702 			else
2703 				uio->uio_resid -= len;
2704 			if (*mp0 != NULL)
2705 				m_cat(*mp0, m);
2706 			else
2707 				*mp0 = m;
2708 			if (*mp0 == NULL) {
2709 				error = ENOBUFS;
2710 				goto out;
2711 			}
2712 		}
2713 	} else {
2714 		/* NB: Must unlock socket buffer as uiomove may sleep. */
2715 		SOCKBUF_UNLOCK(sb);
2716 		error = m_mbuftouio(uio, sb->sb_mb, len);
2717 		SOCKBUF_LOCK(sb);
2718 		if (error)
2719 			goto out;
2720 	}
2721 	SBLASTRECORDCHK(sb);
2722 	SBLASTMBUFCHK(sb);
2723 
2724 	/*
2725 	 * Remove the delivered data from the socket buffer unless we
2726 	 * were only peeking.
2727 	 */
2728 	if (!(flags & MSG_PEEK)) {
2729 		if (len > 0)
2730 			sbdrop_locked(sb, len);
2731 
2732 		/* Notify protocol that we drained some data. */
2733 		if ((so->so_proto->pr_flags & PR_WANTRCVD) &&
2734 		    (((flags & MSG_WAITALL) && uio->uio_resid > 0) ||
2735 		     !(flags & MSG_SOCALLBCK))) {
2736 			SOCKBUF_UNLOCK(sb);
2737 			VNET_SO_ASSERT(so);
2738 			so->so_proto->pr_rcvd(so, flags);
2739 			SOCKBUF_LOCK(sb);
2740 		}
2741 	}
2742 
2743 	/*
2744 	 * For MSG_WAITALL we may have to loop again and wait for
2745 	 * more data to come in.
2746 	 */
2747 	if ((flags & MSG_WAITALL) && uio->uio_resid > 0)
2748 		goto restart;
2749 out:
2750 	SBLASTRECORDCHK(sb);
2751 	SBLASTMBUFCHK(sb);
2752 	SOCKBUF_UNLOCK(sb);
2753 	SOCK_IO_RECV_UNLOCK(so);
2754 	return (error);
2755 }
2756 
2757 /*
2758  * Optimized version of soreceive() for simple datagram cases from userspace.
2759  * Unlike in the stream case, we're able to drop a datagram if copyout()
2760  * fails, and because we handle datagrams atomically, we don't need to use a
2761  * sleep lock to prevent I/O interlacing.
2762  */
2763 int
2764 soreceive_dgram(struct socket *so, struct sockaddr **psa, struct uio *uio,
2765     struct mbuf **mp0, struct mbuf **controlp, int *flagsp)
2766 {
2767 	struct mbuf *m, *m2;
2768 	int flags, error;
2769 	ssize_t len;
2770 	struct protosw *pr = so->so_proto;
2771 	struct mbuf *nextrecord;
2772 
2773 	if (psa != NULL)
2774 		*psa = NULL;
2775 	if (controlp != NULL)
2776 		*controlp = NULL;
2777 	if (flagsp != NULL)
2778 		flags = *flagsp &~ MSG_EOR;
2779 	else
2780 		flags = 0;
2781 
2782 	/*
2783 	 * For any complicated cases, fall back to the full
2784 	 * soreceive_generic().
2785 	 */
2786 	if (mp0 != NULL || (flags & (MSG_PEEK | MSG_OOB | MSG_TRUNC)))
2787 		return (soreceive_generic(so, psa, uio, mp0, controlp,
2788 		    flagsp));
2789 
2790 	/*
2791 	 * Enforce restrictions on use.
2792 	 */
2793 	KASSERT((pr->pr_flags & PR_WANTRCVD) == 0,
2794 	    ("soreceive_dgram: wantrcvd"));
2795 	KASSERT(pr->pr_flags & PR_ATOMIC, ("soreceive_dgram: !atomic"));
2796 	KASSERT((so->so_rcv.sb_state & SBS_RCVATMARK) == 0,
2797 	    ("soreceive_dgram: SBS_RCVATMARK"));
2798 	KASSERT((so->so_proto->pr_flags & PR_CONNREQUIRED) == 0,
2799 	    ("soreceive_dgram: P_CONNREQUIRED"));
2800 
2801 	/*
2802 	 * Loop blocking while waiting for a datagram.
2803 	 */
2804 	SOCKBUF_LOCK(&so->so_rcv);
2805 	while ((m = so->so_rcv.sb_mb) == NULL) {
2806 		KASSERT(sbavail(&so->so_rcv) == 0,
2807 		    ("soreceive_dgram: sb_mb NULL but sbavail %u",
2808 		    sbavail(&so->so_rcv)));
2809 		if (so->so_error) {
2810 			error = so->so_error;
2811 			so->so_error = 0;
2812 			SOCKBUF_UNLOCK(&so->so_rcv);
2813 			return (error);
2814 		}
2815 		if (so->so_rcv.sb_state & SBS_CANTRCVMORE ||
2816 		    uio->uio_resid == 0) {
2817 			SOCKBUF_UNLOCK(&so->so_rcv);
2818 			return (0);
2819 		}
2820 		if ((so->so_state & SS_NBIO) ||
2821 		    (flags & (MSG_DONTWAIT|MSG_NBIO))) {
2822 			SOCKBUF_UNLOCK(&so->so_rcv);
2823 			return (EWOULDBLOCK);
2824 		}
2825 		SBLASTRECORDCHK(&so->so_rcv);
2826 		SBLASTMBUFCHK(&so->so_rcv);
2827 		error = sbwait(so, SO_RCV);
2828 		if (error) {
2829 			SOCKBUF_UNLOCK(&so->so_rcv);
2830 			return (error);
2831 		}
2832 	}
2833 	SOCKBUF_LOCK_ASSERT(&so->so_rcv);
2834 
2835 	if (uio->uio_td)
2836 		uio->uio_td->td_ru.ru_msgrcv++;
2837 	SBLASTRECORDCHK(&so->so_rcv);
2838 	SBLASTMBUFCHK(&so->so_rcv);
2839 	nextrecord = m->m_nextpkt;
2840 	if (nextrecord == NULL) {
2841 		KASSERT(so->so_rcv.sb_lastrecord == m,
2842 		    ("soreceive_dgram: lastrecord != m"));
2843 	}
2844 
2845 	KASSERT(so->so_rcv.sb_mb->m_nextpkt == nextrecord,
2846 	    ("soreceive_dgram: m_nextpkt != nextrecord"));
2847 
2848 	/*
2849 	 * Pull 'm' and its chain off the front of the packet queue.
2850 	 */
2851 	so->so_rcv.sb_mb = NULL;
2852 	sockbuf_pushsync(&so->so_rcv, nextrecord);
2853 
2854 	/*
2855 	 * Walk 'm's chain and free that many bytes from the socket buffer.
2856 	 */
2857 	for (m2 = m; m2 != NULL; m2 = m2->m_next)
2858 		sbfree(&so->so_rcv, m2);
2859 
2860 	/*
2861 	 * Do a few last checks before we let go of the lock.
2862 	 */
2863 	SBLASTRECORDCHK(&so->so_rcv);
2864 	SBLASTMBUFCHK(&so->so_rcv);
2865 	SOCKBUF_UNLOCK(&so->so_rcv);
2866 
2867 	if (pr->pr_flags & PR_ADDR) {
2868 		KASSERT(m->m_type == MT_SONAME,
2869 		    ("m->m_type == %d", m->m_type));
2870 		if (psa != NULL)
2871 			*psa = sodupsockaddr(mtod(m, struct sockaddr *),
2872 			    M_NOWAIT);
2873 		m = m_free(m);
2874 	}
2875 	if (m == NULL) {
2876 		/* XXXRW: Can this happen? */
2877 		return (0);
2878 	}
2879 
2880 	/*
2881 	 * Packet to copyout() is now in 'm' and it is disconnected from the
2882 	 * queue.
2883 	 *
2884 	 * Process one or more MT_CONTROL mbufs present before any data mbufs
2885 	 * in the first mbuf chain on the socket buffer.  We call into the
2886 	 * protocol to perform externalization (or freeing if controlp ==
2887 	 * NULL). In some cases there can be only MT_CONTROL mbufs without
2888 	 * MT_DATA mbufs.
2889 	 */
2890 	if (m->m_type == MT_CONTROL) {
2891 		struct mbuf *cm = NULL, *cmn;
2892 		struct mbuf **cme = &cm;
2893 
2894 		do {
2895 			m2 = m->m_next;
2896 			m->m_next = NULL;
2897 			*cme = m;
2898 			cme = &(*cme)->m_next;
2899 			m = m2;
2900 		} while (m != NULL && m->m_type == MT_CONTROL);
2901 		while (cm != NULL) {
2902 			cmn = cm->m_next;
2903 			cm->m_next = NULL;
2904 			if (pr->pr_domain->dom_externalize != NULL) {
2905 				error = (*pr->pr_domain->dom_externalize)
2906 				    (cm, controlp, flags);
2907 			} else if (controlp != NULL)
2908 				*controlp = cm;
2909 			else
2910 				m_freem(cm);
2911 			if (controlp != NULL) {
2912 				while (*controlp != NULL)
2913 					controlp = &(*controlp)->m_next;
2914 			}
2915 			cm = cmn;
2916 		}
2917 	}
2918 	KASSERT(m == NULL || m->m_type == MT_DATA,
2919 	    ("soreceive_dgram: !data"));
2920 	while (m != NULL && uio->uio_resid > 0) {
2921 		len = uio->uio_resid;
2922 		if (len > m->m_len)
2923 			len = m->m_len;
2924 		error = uiomove(mtod(m, char *), (int)len, uio);
2925 		if (error) {
2926 			m_freem(m);
2927 			return (error);
2928 		}
2929 		if (len == m->m_len)
2930 			m = m_free(m);
2931 		else {
2932 			m->m_data += len;
2933 			m->m_len -= len;
2934 		}
2935 	}
2936 	if (m != NULL) {
2937 		flags |= MSG_TRUNC;
2938 		m_freem(m);
2939 	}
2940 	if (flagsp != NULL)
2941 		*flagsp |= flags;
2942 	return (0);
2943 }
2944 
2945 int
2946 soreceive(struct socket *so, struct sockaddr **psa, struct uio *uio,
2947     struct mbuf **mp0, struct mbuf **controlp, int *flagsp)
2948 {
2949 	int error;
2950 
2951 	CURVNET_SET(so->so_vnet);
2952 	error = so->so_proto->pr_soreceive(so, psa, uio, mp0, controlp, flagsp);
2953 	CURVNET_RESTORE();
2954 	return (error);
2955 }
2956 
2957 int
2958 soshutdown(struct socket *so, enum shutdown_how how)
2959 {
2960 	int error;
2961 
2962 	CURVNET_SET(so->so_vnet);
2963 	error = so->so_proto->pr_shutdown(so, how);
2964 	CURVNET_RESTORE();
2965 
2966 	return (error);
2967 }
2968 
2969 /*
2970  * Used by several pr_shutdown implementations that use generic socket buffers.
2971  */
2972 void
2973 sorflush(struct socket *so)
2974 {
2975 	int error;
2976 
2977 	VNET_SO_ASSERT(so);
2978 
2979 	/*
2980 	 * Dislodge threads currently blocked in receive and wait to acquire
2981 	 * a lock against other simultaneous readers before clearing the
2982 	 * socket buffer.  Don't let our acquire be interrupted by a signal
2983 	 * despite any existing socket disposition on interruptable waiting.
2984 	 *
2985 	 * The SOCK_IO_RECV_LOCK() is important here as there some pr_soreceive
2986 	 * methods that read the top of the socket buffer without acquisition
2987 	 * of the socket buffer mutex, assuming that top of the buffer
2988 	 * exclusively belongs to the read(2) syscall.  This is handy when
2989 	 * performing MSG_PEEK.
2990 	 */
2991 	socantrcvmore(so);
2992 
2993 	error = SOCK_IO_RECV_LOCK(so, SBL_WAIT | SBL_NOINTR);
2994 	if (error != 0) {
2995 		KASSERT(SOLISTENING(so),
2996 		    ("%s: soiolock(%p) failed", __func__, so));
2997 		return;
2998 	}
2999 
3000 	sbrelease(so, SO_RCV);
3001 	SOCK_IO_RECV_UNLOCK(so);
3002 
3003 }
3004 
3005 /*
3006  * Wrapper for Socket established helper hook.
3007  * Parameters: socket, context of the hook point, hook id.
3008  */
3009 static int inline
3010 hhook_run_socket(struct socket *so, void *hctx, int32_t h_id)
3011 {
3012 	struct socket_hhook_data hhook_data = {
3013 		.so = so,
3014 		.hctx = hctx,
3015 		.m = NULL,
3016 		.status = 0
3017 	};
3018 
3019 	CURVNET_SET(so->so_vnet);
3020 	HHOOKS_RUN_IF(V_socket_hhh[h_id], &hhook_data, &so->osd);
3021 	CURVNET_RESTORE();
3022 
3023 	/* Ugly but needed, since hhooks return void for now */
3024 	return (hhook_data.status);
3025 }
3026 
3027 /*
3028  * Perhaps this routine, and sooptcopyout(), below, ought to come in an
3029  * additional variant to handle the case where the option value needs to be
3030  * some kind of integer, but not a specific size.  In addition to their use
3031  * here, these functions are also called by the protocol-level pr_ctloutput()
3032  * routines.
3033  */
3034 int
3035 sooptcopyin(struct sockopt *sopt, void *buf, size_t len, size_t minlen)
3036 {
3037 	size_t	valsize;
3038 
3039 	/*
3040 	 * If the user gives us more than we wanted, we ignore it, but if we
3041 	 * don't get the minimum length the caller wants, we return EINVAL.
3042 	 * On success, sopt->sopt_valsize is set to however much we actually
3043 	 * retrieved.
3044 	 */
3045 	if ((valsize = sopt->sopt_valsize) < minlen)
3046 		return EINVAL;
3047 	if (valsize > len)
3048 		sopt->sopt_valsize = valsize = len;
3049 
3050 	if (sopt->sopt_td != NULL)
3051 		return (copyin(sopt->sopt_val, buf, valsize));
3052 
3053 	bcopy(sopt->sopt_val, buf, valsize);
3054 	return (0);
3055 }
3056 
3057 /*
3058  * Kernel version of setsockopt(2).
3059  *
3060  * XXX: optlen is size_t, not socklen_t
3061  */
3062 int
3063 so_setsockopt(struct socket *so, int level, int optname, void *optval,
3064     size_t optlen)
3065 {
3066 	struct sockopt sopt;
3067 
3068 	sopt.sopt_level = level;
3069 	sopt.sopt_name = optname;
3070 	sopt.sopt_dir = SOPT_SET;
3071 	sopt.sopt_val = optval;
3072 	sopt.sopt_valsize = optlen;
3073 	sopt.sopt_td = NULL;
3074 	return (sosetopt(so, &sopt));
3075 }
3076 
3077 int
3078 sosetopt(struct socket *so, struct sockopt *sopt)
3079 {
3080 	int	error, optval;
3081 	struct	linger l;
3082 	struct	timeval tv;
3083 	sbintime_t val, *valp;
3084 	uint32_t val32;
3085 #ifdef MAC
3086 	struct mac extmac;
3087 #endif
3088 
3089 	CURVNET_SET(so->so_vnet);
3090 	error = 0;
3091 	if (sopt->sopt_level != SOL_SOCKET) {
3092 		if (so->so_proto->pr_ctloutput != NULL)
3093 			error = (*so->so_proto->pr_ctloutput)(so, sopt);
3094 		else
3095 			error = ENOPROTOOPT;
3096 	} else {
3097 		switch (sopt->sopt_name) {
3098 		case SO_ACCEPTFILTER:
3099 			error = accept_filt_setopt(so, sopt);
3100 			if (error)
3101 				goto bad;
3102 			break;
3103 
3104 		case SO_LINGER:
3105 			error = sooptcopyin(sopt, &l, sizeof l, sizeof l);
3106 			if (error)
3107 				goto bad;
3108 			if (l.l_linger < 0 ||
3109 			    l.l_linger > USHRT_MAX ||
3110 			    l.l_linger > (INT_MAX / hz)) {
3111 				error = EDOM;
3112 				goto bad;
3113 			}
3114 			SOCK_LOCK(so);
3115 			so->so_linger = l.l_linger;
3116 			if (l.l_onoff)
3117 				so->so_options |= SO_LINGER;
3118 			else
3119 				so->so_options &= ~SO_LINGER;
3120 			SOCK_UNLOCK(so);
3121 			break;
3122 
3123 		case SO_DEBUG:
3124 		case SO_KEEPALIVE:
3125 		case SO_DONTROUTE:
3126 		case SO_USELOOPBACK:
3127 		case SO_BROADCAST:
3128 		case SO_REUSEADDR:
3129 		case SO_REUSEPORT:
3130 		case SO_REUSEPORT_LB:
3131 		case SO_OOBINLINE:
3132 		case SO_TIMESTAMP:
3133 		case SO_BINTIME:
3134 		case SO_NOSIGPIPE:
3135 		case SO_NO_DDP:
3136 		case SO_NO_OFFLOAD:
3137 		case SO_RERROR:
3138 			error = sooptcopyin(sopt, &optval, sizeof optval,
3139 			    sizeof optval);
3140 			if (error)
3141 				goto bad;
3142 			SOCK_LOCK(so);
3143 			if (optval)
3144 				so->so_options |= sopt->sopt_name;
3145 			else
3146 				so->so_options &= ~sopt->sopt_name;
3147 			SOCK_UNLOCK(so);
3148 			break;
3149 
3150 		case SO_SETFIB:
3151 			error = sooptcopyin(sopt, &optval, sizeof optval,
3152 			    sizeof optval);
3153 			if (error)
3154 				goto bad;
3155 
3156 			if (optval < 0 || optval >= rt_numfibs) {
3157 				error = EINVAL;
3158 				goto bad;
3159 			}
3160 			if (((so->so_proto->pr_domain->dom_family == PF_INET) ||
3161 			   (so->so_proto->pr_domain->dom_family == PF_INET6) ||
3162 			   (so->so_proto->pr_domain->dom_family == PF_ROUTE)))
3163 				so->so_fibnum = optval;
3164 			else
3165 				so->so_fibnum = 0;
3166 			break;
3167 
3168 		case SO_USER_COOKIE:
3169 			error = sooptcopyin(sopt, &val32, sizeof val32,
3170 			    sizeof val32);
3171 			if (error)
3172 				goto bad;
3173 			so->so_user_cookie = val32;
3174 			break;
3175 
3176 		case SO_SNDBUF:
3177 		case SO_RCVBUF:
3178 		case SO_SNDLOWAT:
3179 		case SO_RCVLOWAT:
3180 			error = so->so_proto->pr_setsbopt(so, sopt);
3181 			if (error)
3182 				goto bad;
3183 			break;
3184 
3185 		case SO_SNDTIMEO:
3186 		case SO_RCVTIMEO:
3187 #ifdef COMPAT_FREEBSD32
3188 			if (SV_CURPROC_FLAG(SV_ILP32)) {
3189 				struct timeval32 tv32;
3190 
3191 				error = sooptcopyin(sopt, &tv32, sizeof tv32,
3192 				    sizeof tv32);
3193 				CP(tv32, tv, tv_sec);
3194 				CP(tv32, tv, tv_usec);
3195 			} else
3196 #endif
3197 				error = sooptcopyin(sopt, &tv, sizeof tv,
3198 				    sizeof tv);
3199 			if (error)
3200 				goto bad;
3201 			if (tv.tv_sec < 0 || tv.tv_usec < 0 ||
3202 			    tv.tv_usec >= 1000000) {
3203 				error = EDOM;
3204 				goto bad;
3205 			}
3206 			if (tv.tv_sec > INT32_MAX)
3207 				val = SBT_MAX;
3208 			else
3209 				val = tvtosbt(tv);
3210 			SOCK_LOCK(so);
3211 			valp = sopt->sopt_name == SO_SNDTIMEO ?
3212 			    (SOLISTENING(so) ? &so->sol_sbsnd_timeo :
3213 			    &so->so_snd.sb_timeo) :
3214 			    (SOLISTENING(so) ? &so->sol_sbrcv_timeo :
3215 			    &so->so_rcv.sb_timeo);
3216 			*valp = val;
3217 			SOCK_UNLOCK(so);
3218 			break;
3219 
3220 		case SO_LABEL:
3221 #ifdef MAC
3222 			error = sooptcopyin(sopt, &extmac, sizeof extmac,
3223 			    sizeof extmac);
3224 			if (error)
3225 				goto bad;
3226 			error = mac_setsockopt_label(sopt->sopt_td->td_ucred,
3227 			    so, &extmac);
3228 #else
3229 			error = EOPNOTSUPP;
3230 #endif
3231 			break;
3232 
3233 		case SO_TS_CLOCK:
3234 			error = sooptcopyin(sopt, &optval, sizeof optval,
3235 			    sizeof optval);
3236 			if (error)
3237 				goto bad;
3238 			if (optval < 0 || optval > SO_TS_CLOCK_MAX) {
3239 				error = EINVAL;
3240 				goto bad;
3241 			}
3242 			so->so_ts_clock = optval;
3243 			break;
3244 
3245 		case SO_MAX_PACING_RATE:
3246 			error = sooptcopyin(sopt, &val32, sizeof(val32),
3247 			    sizeof(val32));
3248 			if (error)
3249 				goto bad;
3250 			so->so_max_pacing_rate = val32;
3251 			break;
3252 
3253 		default:
3254 			if (V_socket_hhh[HHOOK_SOCKET_OPT]->hhh_nhooks > 0)
3255 				error = hhook_run_socket(so, sopt,
3256 				    HHOOK_SOCKET_OPT);
3257 			else
3258 				error = ENOPROTOOPT;
3259 			break;
3260 		}
3261 		if (error == 0 && so->so_proto->pr_ctloutput != NULL)
3262 			(void)(*so->so_proto->pr_ctloutput)(so, sopt);
3263 	}
3264 bad:
3265 	CURVNET_RESTORE();
3266 	return (error);
3267 }
3268 
3269 /*
3270  * Helper routine for getsockopt.
3271  */
3272 int
3273 sooptcopyout(struct sockopt *sopt, const void *buf, size_t len)
3274 {
3275 	int	error;
3276 	size_t	valsize;
3277 
3278 	error = 0;
3279 
3280 	/*
3281 	 * Documented get behavior is that we always return a value, possibly
3282 	 * truncated to fit in the user's buffer.  Traditional behavior is
3283 	 * that we always tell the user precisely how much we copied, rather
3284 	 * than something useful like the total amount we had available for
3285 	 * her.  Note that this interface is not idempotent; the entire
3286 	 * answer must be generated ahead of time.
3287 	 */
3288 	valsize = min(len, sopt->sopt_valsize);
3289 	sopt->sopt_valsize = valsize;
3290 	if (sopt->sopt_val != NULL) {
3291 		if (sopt->sopt_td != NULL)
3292 			error = copyout(buf, sopt->sopt_val, valsize);
3293 		else
3294 			bcopy(buf, sopt->sopt_val, valsize);
3295 	}
3296 	return (error);
3297 }
3298 
3299 int
3300 sogetopt(struct socket *so, struct sockopt *sopt)
3301 {
3302 	int	error, optval;
3303 	struct	linger l;
3304 	struct	timeval tv;
3305 #ifdef MAC
3306 	struct mac extmac;
3307 #endif
3308 
3309 	CURVNET_SET(so->so_vnet);
3310 	error = 0;
3311 	if (sopt->sopt_level != SOL_SOCKET) {
3312 		if (so->so_proto->pr_ctloutput != NULL)
3313 			error = (*so->so_proto->pr_ctloutput)(so, sopt);
3314 		else
3315 			error = ENOPROTOOPT;
3316 		CURVNET_RESTORE();
3317 		return (error);
3318 	} else {
3319 		switch (sopt->sopt_name) {
3320 		case SO_ACCEPTFILTER:
3321 			error = accept_filt_getopt(so, sopt);
3322 			break;
3323 
3324 		case SO_LINGER:
3325 			SOCK_LOCK(so);
3326 			l.l_onoff = so->so_options & SO_LINGER;
3327 			l.l_linger = so->so_linger;
3328 			SOCK_UNLOCK(so);
3329 			error = sooptcopyout(sopt, &l, sizeof l);
3330 			break;
3331 
3332 		case SO_USELOOPBACK:
3333 		case SO_DONTROUTE:
3334 		case SO_DEBUG:
3335 		case SO_KEEPALIVE:
3336 		case SO_REUSEADDR:
3337 		case SO_REUSEPORT:
3338 		case SO_REUSEPORT_LB:
3339 		case SO_BROADCAST:
3340 		case SO_OOBINLINE:
3341 		case SO_ACCEPTCONN:
3342 		case SO_TIMESTAMP:
3343 		case SO_BINTIME:
3344 		case SO_NOSIGPIPE:
3345 		case SO_NO_DDP:
3346 		case SO_NO_OFFLOAD:
3347 		case SO_RERROR:
3348 			optval = so->so_options & sopt->sopt_name;
3349 integer:
3350 			error = sooptcopyout(sopt, &optval, sizeof optval);
3351 			break;
3352 
3353 		case SO_DOMAIN:
3354 			optval = so->so_proto->pr_domain->dom_family;
3355 			goto integer;
3356 
3357 		case SO_TYPE:
3358 			optval = so->so_type;
3359 			goto integer;
3360 
3361 		case SO_PROTOCOL:
3362 			optval = so->so_proto->pr_protocol;
3363 			goto integer;
3364 
3365 		case SO_ERROR:
3366 			SOCK_LOCK(so);
3367 			if (so->so_error) {
3368 				optval = so->so_error;
3369 				so->so_error = 0;
3370 			} else {
3371 				optval = so->so_rerror;
3372 				so->so_rerror = 0;
3373 			}
3374 			SOCK_UNLOCK(so);
3375 			goto integer;
3376 
3377 		case SO_SNDBUF:
3378 			optval = SOLISTENING(so) ? so->sol_sbsnd_hiwat :
3379 			    so->so_snd.sb_hiwat;
3380 			goto integer;
3381 
3382 		case SO_RCVBUF:
3383 			optval = SOLISTENING(so) ? so->sol_sbrcv_hiwat :
3384 			    so->so_rcv.sb_hiwat;
3385 			goto integer;
3386 
3387 		case SO_SNDLOWAT:
3388 			optval = SOLISTENING(so) ? so->sol_sbsnd_lowat :
3389 			    so->so_snd.sb_lowat;
3390 			goto integer;
3391 
3392 		case SO_RCVLOWAT:
3393 			optval = SOLISTENING(so) ? so->sol_sbrcv_lowat :
3394 			    so->so_rcv.sb_lowat;
3395 			goto integer;
3396 
3397 		case SO_SNDTIMEO:
3398 		case SO_RCVTIMEO:
3399 			SOCK_LOCK(so);
3400 			tv = sbttotv(sopt->sopt_name == SO_SNDTIMEO ?
3401 			    (SOLISTENING(so) ? so->sol_sbsnd_timeo :
3402 			    so->so_snd.sb_timeo) :
3403 			    (SOLISTENING(so) ? so->sol_sbrcv_timeo :
3404 			    so->so_rcv.sb_timeo));
3405 			SOCK_UNLOCK(so);
3406 #ifdef COMPAT_FREEBSD32
3407 			if (SV_CURPROC_FLAG(SV_ILP32)) {
3408 				struct timeval32 tv32;
3409 
3410 				CP(tv, tv32, tv_sec);
3411 				CP(tv, tv32, tv_usec);
3412 				error = sooptcopyout(sopt, &tv32, sizeof tv32);
3413 			} else
3414 #endif
3415 				error = sooptcopyout(sopt, &tv, sizeof tv);
3416 			break;
3417 
3418 		case SO_LABEL:
3419 #ifdef MAC
3420 			error = sooptcopyin(sopt, &extmac, sizeof(extmac),
3421 			    sizeof(extmac));
3422 			if (error)
3423 				goto bad;
3424 			error = mac_getsockopt_label(sopt->sopt_td->td_ucred,
3425 			    so, &extmac);
3426 			if (error)
3427 				goto bad;
3428 			/* Don't copy out extmac, it is unchanged. */
3429 #else
3430 			error = EOPNOTSUPP;
3431 #endif
3432 			break;
3433 
3434 		case SO_PEERLABEL:
3435 #ifdef MAC
3436 			error = sooptcopyin(sopt, &extmac, sizeof(extmac),
3437 			    sizeof(extmac));
3438 			if (error)
3439 				goto bad;
3440 			error = mac_getsockopt_peerlabel(
3441 			    sopt->sopt_td->td_ucred, so, &extmac);
3442 			if (error)
3443 				goto bad;
3444 			/* Don't copy out extmac, it is unchanged. */
3445 #else
3446 			error = EOPNOTSUPP;
3447 #endif
3448 			break;
3449 
3450 		case SO_LISTENQLIMIT:
3451 			optval = SOLISTENING(so) ? so->sol_qlimit : 0;
3452 			goto integer;
3453 
3454 		case SO_LISTENQLEN:
3455 			optval = SOLISTENING(so) ? so->sol_qlen : 0;
3456 			goto integer;
3457 
3458 		case SO_LISTENINCQLEN:
3459 			optval = SOLISTENING(so) ? so->sol_incqlen : 0;
3460 			goto integer;
3461 
3462 		case SO_TS_CLOCK:
3463 			optval = so->so_ts_clock;
3464 			goto integer;
3465 
3466 		case SO_MAX_PACING_RATE:
3467 			optval = so->so_max_pacing_rate;
3468 			goto integer;
3469 
3470 		default:
3471 			if (V_socket_hhh[HHOOK_SOCKET_OPT]->hhh_nhooks > 0)
3472 				error = hhook_run_socket(so, sopt,
3473 				    HHOOK_SOCKET_OPT);
3474 			else
3475 				error = ENOPROTOOPT;
3476 			break;
3477 		}
3478 	}
3479 #ifdef MAC
3480 bad:
3481 #endif
3482 	CURVNET_RESTORE();
3483 	return (error);
3484 }
3485 
3486 int
3487 soopt_getm(struct sockopt *sopt, struct mbuf **mp)
3488 {
3489 	struct mbuf *m, *m_prev;
3490 	int sopt_size = sopt->sopt_valsize;
3491 
3492 	MGET(m, sopt->sopt_td ? M_WAITOK : M_NOWAIT, MT_DATA);
3493 	if (m == NULL)
3494 		return ENOBUFS;
3495 	if (sopt_size > MLEN) {
3496 		MCLGET(m, sopt->sopt_td ? M_WAITOK : M_NOWAIT);
3497 		if ((m->m_flags & M_EXT) == 0) {
3498 			m_free(m);
3499 			return ENOBUFS;
3500 		}
3501 		m->m_len = min(MCLBYTES, sopt_size);
3502 	} else {
3503 		m->m_len = min(MLEN, sopt_size);
3504 	}
3505 	sopt_size -= m->m_len;
3506 	*mp = m;
3507 	m_prev = m;
3508 
3509 	while (sopt_size) {
3510 		MGET(m, sopt->sopt_td ? M_WAITOK : M_NOWAIT, MT_DATA);
3511 		if (m == NULL) {
3512 			m_freem(*mp);
3513 			return ENOBUFS;
3514 		}
3515 		if (sopt_size > MLEN) {
3516 			MCLGET(m, sopt->sopt_td != NULL ? M_WAITOK :
3517 			    M_NOWAIT);
3518 			if ((m->m_flags & M_EXT) == 0) {
3519 				m_freem(m);
3520 				m_freem(*mp);
3521 				return ENOBUFS;
3522 			}
3523 			m->m_len = min(MCLBYTES, sopt_size);
3524 		} else {
3525 			m->m_len = min(MLEN, sopt_size);
3526 		}
3527 		sopt_size -= m->m_len;
3528 		m_prev->m_next = m;
3529 		m_prev = m;
3530 	}
3531 	return (0);
3532 }
3533 
3534 int
3535 soopt_mcopyin(struct sockopt *sopt, struct mbuf *m)
3536 {
3537 	struct mbuf *m0 = m;
3538 
3539 	if (sopt->sopt_val == NULL)
3540 		return (0);
3541 	while (m != NULL && sopt->sopt_valsize >= m->m_len) {
3542 		if (sopt->sopt_td != NULL) {
3543 			int error;
3544 
3545 			error = copyin(sopt->sopt_val, mtod(m, char *),
3546 			    m->m_len);
3547 			if (error != 0) {
3548 				m_freem(m0);
3549 				return(error);
3550 			}
3551 		} else
3552 			bcopy(sopt->sopt_val, mtod(m, char *), m->m_len);
3553 		sopt->sopt_valsize -= m->m_len;
3554 		sopt->sopt_val = (char *)sopt->sopt_val + m->m_len;
3555 		m = m->m_next;
3556 	}
3557 	if (m != NULL) /* should be allocated enoughly at ip6_sooptmcopyin() */
3558 		panic("ip6_sooptmcopyin");
3559 	return (0);
3560 }
3561 
3562 int
3563 soopt_mcopyout(struct sockopt *sopt, struct mbuf *m)
3564 {
3565 	struct mbuf *m0 = m;
3566 	size_t valsize = 0;
3567 
3568 	if (sopt->sopt_val == NULL)
3569 		return (0);
3570 	while (m != NULL && sopt->sopt_valsize >= m->m_len) {
3571 		if (sopt->sopt_td != NULL) {
3572 			int error;
3573 
3574 			error = copyout(mtod(m, char *), sopt->sopt_val,
3575 			    m->m_len);
3576 			if (error != 0) {
3577 				m_freem(m0);
3578 				return(error);
3579 			}
3580 		} else
3581 			bcopy(mtod(m, char *), sopt->sopt_val, m->m_len);
3582 		sopt->sopt_valsize -= m->m_len;
3583 		sopt->sopt_val = (char *)sopt->sopt_val + m->m_len;
3584 		valsize += m->m_len;
3585 		m = m->m_next;
3586 	}
3587 	if (m != NULL) {
3588 		/* enough soopt buffer should be given from user-land */
3589 		m_freem(m0);
3590 		return(EINVAL);
3591 	}
3592 	sopt->sopt_valsize = valsize;
3593 	return (0);
3594 }
3595 
3596 /*
3597  * sohasoutofband(): protocol notifies socket layer of the arrival of new
3598  * out-of-band data, which will then notify socket consumers.
3599  */
3600 void
3601 sohasoutofband(struct socket *so)
3602 {
3603 
3604 	if (so->so_sigio != NULL)
3605 		pgsigio(&so->so_sigio, SIGURG, 0);
3606 	selwakeuppri(&so->so_rdsel, PSOCK);
3607 }
3608 
3609 int
3610 sopoll(struct socket *so, int events, struct ucred *active_cred,
3611     struct thread *td)
3612 {
3613 
3614 	/*
3615 	 * We do not need to set or assert curvnet as long as everyone uses
3616 	 * sopoll_generic().
3617 	 */
3618 	return (so->so_proto->pr_sopoll(so, events, active_cred, td));
3619 }
3620 
3621 int
3622 sopoll_generic(struct socket *so, int events, struct ucred *active_cred,
3623     struct thread *td)
3624 {
3625 	int revents;
3626 
3627 	SOCK_LOCK(so);
3628 	if (SOLISTENING(so)) {
3629 		if (!(events & (POLLIN | POLLRDNORM)))
3630 			revents = 0;
3631 		else if (!TAILQ_EMPTY(&so->sol_comp))
3632 			revents = events & (POLLIN | POLLRDNORM);
3633 		else if ((events & POLLINIGNEOF) == 0 && so->so_error)
3634 			revents = (events & (POLLIN | POLLRDNORM)) | POLLHUP;
3635 		else {
3636 			selrecord(td, &so->so_rdsel);
3637 			revents = 0;
3638 		}
3639 	} else {
3640 		revents = 0;
3641 		SOCK_SENDBUF_LOCK(so);
3642 		SOCK_RECVBUF_LOCK(so);
3643 		if (events & (POLLIN | POLLRDNORM))
3644 			if (soreadabledata(so))
3645 				revents |= events & (POLLIN | POLLRDNORM);
3646 		if (events & (POLLOUT | POLLWRNORM))
3647 			if (sowriteable(so))
3648 				revents |= events & (POLLOUT | POLLWRNORM);
3649 		if (events & (POLLPRI | POLLRDBAND))
3650 			if (so->so_oobmark ||
3651 			    (so->so_rcv.sb_state & SBS_RCVATMARK))
3652 				revents |= events & (POLLPRI | POLLRDBAND);
3653 		if ((events & POLLINIGNEOF) == 0) {
3654 			if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
3655 				revents |= events & (POLLIN | POLLRDNORM);
3656 				if (so->so_snd.sb_state & SBS_CANTSENDMORE)
3657 					revents |= POLLHUP;
3658 			}
3659 		}
3660 		if (so->so_rcv.sb_state & SBS_CANTRCVMORE)
3661 			revents |= events & POLLRDHUP;
3662 		if (revents == 0) {
3663 			if (events &
3664 			    (POLLIN | POLLPRI | POLLRDNORM | POLLRDBAND | POLLRDHUP)) {
3665 				selrecord(td, &so->so_rdsel);
3666 				so->so_rcv.sb_flags |= SB_SEL;
3667 			}
3668 			if (events & (POLLOUT | POLLWRNORM)) {
3669 				selrecord(td, &so->so_wrsel);
3670 				so->so_snd.sb_flags |= SB_SEL;
3671 			}
3672 		}
3673 		SOCK_RECVBUF_UNLOCK(so);
3674 		SOCK_SENDBUF_UNLOCK(so);
3675 	}
3676 	SOCK_UNLOCK(so);
3677 	return (revents);
3678 }
3679 
3680 int
3681 soo_kqfilter(struct file *fp, struct knote *kn)
3682 {
3683 	struct socket *so = kn->kn_fp->f_data;
3684 	struct sockbuf *sb;
3685 	sb_which which;
3686 	struct knlist *knl;
3687 
3688 	switch (kn->kn_filter) {
3689 	case EVFILT_READ:
3690 		kn->kn_fop = &soread_filtops;
3691 		knl = &so->so_rdsel.si_note;
3692 		sb = &so->so_rcv;
3693 		which = SO_RCV;
3694 		break;
3695 	case EVFILT_WRITE:
3696 		kn->kn_fop = &sowrite_filtops;
3697 		knl = &so->so_wrsel.si_note;
3698 		sb = &so->so_snd;
3699 		which = SO_SND;
3700 		break;
3701 	case EVFILT_EMPTY:
3702 		kn->kn_fop = &soempty_filtops;
3703 		knl = &so->so_wrsel.si_note;
3704 		sb = &so->so_snd;
3705 		which = SO_SND;
3706 		break;
3707 	default:
3708 		return (EINVAL);
3709 	}
3710 
3711 	SOCK_LOCK(so);
3712 	if (SOLISTENING(so)) {
3713 		knlist_add(knl, kn, 1);
3714 	} else {
3715 		SOCK_BUF_LOCK(so, which);
3716 		knlist_add(knl, kn, 1);
3717 		sb->sb_flags |= SB_KNOTE;
3718 		SOCK_BUF_UNLOCK(so, which);
3719 	}
3720 	SOCK_UNLOCK(so);
3721 	return (0);
3722 }
3723 
3724 static void
3725 filt_sordetach(struct knote *kn)
3726 {
3727 	struct socket *so = kn->kn_fp->f_data;
3728 
3729 	so_rdknl_lock(so);
3730 	knlist_remove(&so->so_rdsel.si_note, kn, 1);
3731 	if (!SOLISTENING(so) && knlist_empty(&so->so_rdsel.si_note))
3732 		so->so_rcv.sb_flags &= ~SB_KNOTE;
3733 	so_rdknl_unlock(so);
3734 }
3735 
3736 /*ARGSUSED*/
3737 static int
3738 filt_soread(struct knote *kn, long hint)
3739 {
3740 	struct socket *so;
3741 
3742 	so = kn->kn_fp->f_data;
3743 
3744 	if (SOLISTENING(so)) {
3745 		SOCK_LOCK_ASSERT(so);
3746 		kn->kn_data = so->sol_qlen;
3747 		if (so->so_error) {
3748 			kn->kn_flags |= EV_EOF;
3749 			kn->kn_fflags = so->so_error;
3750 			return (1);
3751 		}
3752 		return (!TAILQ_EMPTY(&so->sol_comp));
3753 	}
3754 
3755 	SOCK_RECVBUF_LOCK_ASSERT(so);
3756 
3757 	kn->kn_data = sbavail(&so->so_rcv) - so->so_rcv.sb_ctl;
3758 	if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
3759 		kn->kn_flags |= EV_EOF;
3760 		kn->kn_fflags = so->so_error;
3761 		return (1);
3762 	} else if (so->so_error || so->so_rerror)
3763 		return (1);
3764 
3765 	if (kn->kn_sfflags & NOTE_LOWAT) {
3766 		if (kn->kn_data >= kn->kn_sdata)
3767 			return (1);
3768 	} else if (sbavail(&so->so_rcv) >= so->so_rcv.sb_lowat)
3769 		return (1);
3770 
3771 	/* This hook returning non-zero indicates an event, not error */
3772 	return (hhook_run_socket(so, NULL, HHOOK_FILT_SOREAD));
3773 }
3774 
3775 static void
3776 filt_sowdetach(struct knote *kn)
3777 {
3778 	struct socket *so = kn->kn_fp->f_data;
3779 
3780 	so_wrknl_lock(so);
3781 	knlist_remove(&so->so_wrsel.si_note, kn, 1);
3782 	if (!SOLISTENING(so) && knlist_empty(&so->so_wrsel.si_note))
3783 		so->so_snd.sb_flags &= ~SB_KNOTE;
3784 	so_wrknl_unlock(so);
3785 }
3786 
3787 /*ARGSUSED*/
3788 static int
3789 filt_sowrite(struct knote *kn, long hint)
3790 {
3791 	struct socket *so;
3792 
3793 	so = kn->kn_fp->f_data;
3794 
3795 	if (SOLISTENING(so))
3796 		return (0);
3797 
3798 	SOCK_SENDBUF_LOCK_ASSERT(so);
3799 	kn->kn_data = sbspace(&so->so_snd);
3800 
3801 	hhook_run_socket(so, kn, HHOOK_FILT_SOWRITE);
3802 
3803 	if (so->so_snd.sb_state & SBS_CANTSENDMORE) {
3804 		kn->kn_flags |= EV_EOF;
3805 		kn->kn_fflags = so->so_error;
3806 		return (1);
3807 	} else if (so->so_error)	/* temporary udp error */
3808 		return (1);
3809 	else if (((so->so_state & SS_ISCONNECTED) == 0) &&
3810 	    (so->so_proto->pr_flags & PR_CONNREQUIRED))
3811 		return (0);
3812 	else if (kn->kn_sfflags & NOTE_LOWAT)
3813 		return (kn->kn_data >= kn->kn_sdata);
3814 	else
3815 		return (kn->kn_data >= so->so_snd.sb_lowat);
3816 }
3817 
3818 static int
3819 filt_soempty(struct knote *kn, long hint)
3820 {
3821 	struct socket *so;
3822 
3823 	so = kn->kn_fp->f_data;
3824 
3825 	if (SOLISTENING(so))
3826 		return (1);
3827 
3828 	SOCK_SENDBUF_LOCK_ASSERT(so);
3829 	kn->kn_data = sbused(&so->so_snd);
3830 
3831 	if (kn->kn_data == 0)
3832 		return (1);
3833 	else
3834 		return (0);
3835 }
3836 
3837 int
3838 socheckuid(struct socket *so, uid_t uid)
3839 {
3840 
3841 	if (so == NULL)
3842 		return (EPERM);
3843 	if (so->so_cred->cr_uid != uid)
3844 		return (EPERM);
3845 	return (0);
3846 }
3847 
3848 /*
3849  * These functions are used by protocols to notify the socket layer (and its
3850  * consumers) of state changes in the sockets driven by protocol-side events.
3851  */
3852 
3853 /*
3854  * Procedures to manipulate state flags of socket and do appropriate wakeups.
3855  *
3856  * Normal sequence from the active (originating) side is that
3857  * soisconnecting() is called during processing of connect() call, resulting
3858  * in an eventual call to soisconnected() if/when the connection is
3859  * established.  When the connection is torn down soisdisconnecting() is
3860  * called during processing of disconnect() call, and soisdisconnected() is
3861  * called when the connection to the peer is totally severed.  The semantics
3862  * of these routines are such that connectionless protocols can call
3863  * soisconnected() and soisdisconnected() only, bypassing the in-progress
3864  * calls when setting up a ``connection'' takes no time.
3865  *
3866  * From the passive side, a socket is created with two queues of sockets:
3867  * so_incomp for connections in progress and so_comp for connections already
3868  * made and awaiting user acceptance.  As a protocol is preparing incoming
3869  * connections, it creates a socket structure queued on so_incomp by calling
3870  * sonewconn().  When the connection is established, soisconnected() is
3871  * called, and transfers the socket structure to so_comp, making it available
3872  * to accept().
3873  *
3874  * If a socket is closed with sockets on either so_incomp or so_comp, these
3875  * sockets are dropped.
3876  *
3877  * If higher-level protocols are implemented in the kernel, the wakeups done
3878  * here will sometimes cause software-interrupt process scheduling.
3879  */
3880 void
3881 soisconnecting(struct socket *so)
3882 {
3883 
3884 	SOCK_LOCK(so);
3885 	so->so_state &= ~(SS_ISCONNECTED|SS_ISDISCONNECTING);
3886 	so->so_state |= SS_ISCONNECTING;
3887 	SOCK_UNLOCK(so);
3888 }
3889 
3890 void
3891 soisconnected(struct socket *so)
3892 {
3893 	bool last __diagused;
3894 
3895 	SOCK_LOCK(so);
3896 	so->so_state &= ~(SS_ISCONNECTING|SS_ISDISCONNECTING);
3897 	so->so_state |= SS_ISCONNECTED;
3898 
3899 	if (so->so_qstate == SQ_INCOMP) {
3900 		struct socket *head = so->so_listen;
3901 		int ret;
3902 
3903 		KASSERT(head, ("%s: so %p on incomp of NULL", __func__, so));
3904 		/*
3905 		 * Promoting a socket from incomplete queue to complete, we
3906 		 * need to go through reverse order of locking.  We first do
3907 		 * trylock, and if that doesn't succeed, we go the hard way
3908 		 * leaving a reference and rechecking consistency after proper
3909 		 * locking.
3910 		 */
3911 		if (__predict_false(SOLISTEN_TRYLOCK(head) == 0)) {
3912 			soref(head);
3913 			SOCK_UNLOCK(so);
3914 			SOLISTEN_LOCK(head);
3915 			SOCK_LOCK(so);
3916 			if (__predict_false(head != so->so_listen)) {
3917 				/*
3918 				 * The socket went off the listen queue,
3919 				 * should be lost race to close(2) of sol.
3920 				 * The socket is about to soabort().
3921 				 */
3922 				SOCK_UNLOCK(so);
3923 				sorele_locked(head);
3924 				return;
3925 			}
3926 			last = refcount_release(&head->so_count);
3927 			KASSERT(!last, ("%s: released last reference for %p",
3928 			    __func__, head));
3929 		}
3930 again:
3931 		if ((so->so_options & SO_ACCEPTFILTER) == 0) {
3932 			TAILQ_REMOVE(&head->sol_incomp, so, so_list);
3933 			head->sol_incqlen--;
3934 			TAILQ_INSERT_TAIL(&head->sol_comp, so, so_list);
3935 			head->sol_qlen++;
3936 			so->so_qstate = SQ_COMP;
3937 			SOCK_UNLOCK(so);
3938 			solisten_wakeup(head);	/* unlocks */
3939 		} else {
3940 			SOCK_RECVBUF_LOCK(so);
3941 			soupcall_set(so, SO_RCV,
3942 			    head->sol_accept_filter->accf_callback,
3943 			    head->sol_accept_filter_arg);
3944 			so->so_options &= ~SO_ACCEPTFILTER;
3945 			ret = head->sol_accept_filter->accf_callback(so,
3946 			    head->sol_accept_filter_arg, M_NOWAIT);
3947 			if (ret == SU_ISCONNECTED) {
3948 				soupcall_clear(so, SO_RCV);
3949 				SOCK_RECVBUF_UNLOCK(so);
3950 				goto again;
3951 			}
3952 			SOCK_RECVBUF_UNLOCK(so);
3953 			SOCK_UNLOCK(so);
3954 			SOLISTEN_UNLOCK(head);
3955 		}
3956 		return;
3957 	}
3958 	SOCK_UNLOCK(so);
3959 	wakeup(&so->so_timeo);
3960 	sorwakeup(so);
3961 	sowwakeup(so);
3962 }
3963 
3964 void
3965 soisdisconnecting(struct socket *so)
3966 {
3967 
3968 	SOCK_LOCK(so);
3969 	so->so_state &= ~SS_ISCONNECTING;
3970 	so->so_state |= SS_ISDISCONNECTING;
3971 
3972 	if (!SOLISTENING(so)) {
3973 		SOCK_RECVBUF_LOCK(so);
3974 		socantrcvmore_locked(so);
3975 		SOCK_SENDBUF_LOCK(so);
3976 		socantsendmore_locked(so);
3977 	}
3978 	SOCK_UNLOCK(so);
3979 	wakeup(&so->so_timeo);
3980 }
3981 
3982 void
3983 soisdisconnected(struct socket *so)
3984 {
3985 
3986 	SOCK_LOCK(so);
3987 
3988 	/*
3989 	 * There is at least one reader of so_state that does not
3990 	 * acquire socket lock, namely soreceive_generic().  Ensure
3991 	 * that it never sees all flags that track connection status
3992 	 * cleared, by ordering the update with a barrier semantic of
3993 	 * our release thread fence.
3994 	 */
3995 	so->so_state |= SS_ISDISCONNECTED;
3996 	atomic_thread_fence_rel();
3997 	so->so_state &= ~(SS_ISCONNECTING|SS_ISCONNECTED|SS_ISDISCONNECTING);
3998 
3999 	if (!SOLISTENING(so)) {
4000 		SOCK_UNLOCK(so);
4001 		SOCK_RECVBUF_LOCK(so);
4002 		socantrcvmore_locked(so);
4003 		SOCK_SENDBUF_LOCK(so);
4004 		sbdrop_locked(&so->so_snd, sbused(&so->so_snd));
4005 		socantsendmore_locked(so);
4006 	} else
4007 		SOCK_UNLOCK(so);
4008 	wakeup(&so->so_timeo);
4009 }
4010 
4011 int
4012 soiolock(struct socket *so, struct sx *sx, int flags)
4013 {
4014 	int error;
4015 
4016 	KASSERT((flags & SBL_VALID) == flags,
4017 	    ("soiolock: invalid flags %#x", flags));
4018 
4019 	if ((flags & SBL_WAIT) != 0) {
4020 		if ((flags & SBL_NOINTR) != 0) {
4021 			sx_xlock(sx);
4022 		} else {
4023 			error = sx_xlock_sig(sx);
4024 			if (error != 0)
4025 				return (error);
4026 		}
4027 	} else if (!sx_try_xlock(sx)) {
4028 		return (EWOULDBLOCK);
4029 	}
4030 
4031 	if (__predict_false(SOLISTENING(so))) {
4032 		sx_xunlock(sx);
4033 		return (ENOTCONN);
4034 	}
4035 	return (0);
4036 }
4037 
4038 void
4039 soiounlock(struct sx *sx)
4040 {
4041 	sx_xunlock(sx);
4042 }
4043 
4044 /*
4045  * Make a copy of a sockaddr in a malloced buffer of type M_SONAME.
4046  */
4047 struct sockaddr *
4048 sodupsockaddr(const struct sockaddr *sa, int mflags)
4049 {
4050 	struct sockaddr *sa2;
4051 
4052 	sa2 = malloc(sa->sa_len, M_SONAME, mflags);
4053 	if (sa2)
4054 		bcopy(sa, sa2, sa->sa_len);
4055 	return sa2;
4056 }
4057 
4058 /*
4059  * Register per-socket destructor.
4060  */
4061 void
4062 sodtor_set(struct socket *so, so_dtor_t *func)
4063 {
4064 
4065 	SOCK_LOCK_ASSERT(so);
4066 	so->so_dtor = func;
4067 }
4068 
4069 /*
4070  * Register per-socket buffer upcalls.
4071  */
4072 void
4073 soupcall_set(struct socket *so, sb_which which, so_upcall_t func, void *arg)
4074 {
4075 	struct sockbuf *sb;
4076 
4077 	KASSERT(!SOLISTENING(so), ("%s: so %p listening", __func__, so));
4078 
4079 	switch (which) {
4080 	case SO_RCV:
4081 		sb = &so->so_rcv;
4082 		break;
4083 	case SO_SND:
4084 		sb = &so->so_snd;
4085 		break;
4086 	}
4087 	SOCK_BUF_LOCK_ASSERT(so, which);
4088 	sb->sb_upcall = func;
4089 	sb->sb_upcallarg = arg;
4090 	sb->sb_flags |= SB_UPCALL;
4091 }
4092 
4093 void
4094 soupcall_clear(struct socket *so, sb_which which)
4095 {
4096 	struct sockbuf *sb;
4097 
4098 	KASSERT(!SOLISTENING(so), ("%s: so %p listening", __func__, so));
4099 
4100 	switch (which) {
4101 	case SO_RCV:
4102 		sb = &so->so_rcv;
4103 		break;
4104 	case SO_SND:
4105 		sb = &so->so_snd;
4106 		break;
4107 	}
4108 	SOCK_BUF_LOCK_ASSERT(so, which);
4109 	KASSERT(sb->sb_upcall != NULL,
4110 	    ("%s: so %p no upcall to clear", __func__, so));
4111 	sb->sb_upcall = NULL;
4112 	sb->sb_upcallarg = NULL;
4113 	sb->sb_flags &= ~SB_UPCALL;
4114 }
4115 
4116 void
4117 solisten_upcall_set(struct socket *so, so_upcall_t func, void *arg)
4118 {
4119 
4120 	SOLISTEN_LOCK_ASSERT(so);
4121 	so->sol_upcall = func;
4122 	so->sol_upcallarg = arg;
4123 }
4124 
4125 static void
4126 so_rdknl_lock(void *arg)
4127 {
4128 	struct socket *so = arg;
4129 
4130 retry:
4131 	if (SOLISTENING(so)) {
4132 		SOLISTEN_LOCK(so);
4133 	} else {
4134 		SOCK_RECVBUF_LOCK(so);
4135 		if (__predict_false(SOLISTENING(so))) {
4136 			SOCK_RECVBUF_UNLOCK(so);
4137 			goto retry;
4138 		}
4139 	}
4140 }
4141 
4142 static void
4143 so_rdknl_unlock(void *arg)
4144 {
4145 	struct socket *so = arg;
4146 
4147 	if (SOLISTENING(so))
4148 		SOLISTEN_UNLOCK(so);
4149 	else
4150 		SOCK_RECVBUF_UNLOCK(so);
4151 }
4152 
4153 static void
4154 so_rdknl_assert_lock(void *arg, int what)
4155 {
4156 	struct socket *so = arg;
4157 
4158 	if (what == LA_LOCKED) {
4159 		if (SOLISTENING(so))
4160 			SOLISTEN_LOCK_ASSERT(so);
4161 		else
4162 			SOCK_RECVBUF_LOCK_ASSERT(so);
4163 	} else {
4164 		if (SOLISTENING(so))
4165 			SOLISTEN_UNLOCK_ASSERT(so);
4166 		else
4167 			SOCK_RECVBUF_UNLOCK_ASSERT(so);
4168 	}
4169 }
4170 
4171 static void
4172 so_wrknl_lock(void *arg)
4173 {
4174 	struct socket *so = arg;
4175 
4176 retry:
4177 	if (SOLISTENING(so)) {
4178 		SOLISTEN_LOCK(so);
4179 	} else {
4180 		SOCK_SENDBUF_LOCK(so);
4181 		if (__predict_false(SOLISTENING(so))) {
4182 			SOCK_SENDBUF_UNLOCK(so);
4183 			goto retry;
4184 		}
4185 	}
4186 }
4187 
4188 static void
4189 so_wrknl_unlock(void *arg)
4190 {
4191 	struct socket *so = arg;
4192 
4193 	if (SOLISTENING(so))
4194 		SOLISTEN_UNLOCK(so);
4195 	else
4196 		SOCK_SENDBUF_UNLOCK(so);
4197 }
4198 
4199 static void
4200 so_wrknl_assert_lock(void *arg, int what)
4201 {
4202 	struct socket *so = arg;
4203 
4204 	if (what == LA_LOCKED) {
4205 		if (SOLISTENING(so))
4206 			SOLISTEN_LOCK_ASSERT(so);
4207 		else
4208 			SOCK_SENDBUF_LOCK_ASSERT(so);
4209 	} else {
4210 		if (SOLISTENING(so))
4211 			SOLISTEN_UNLOCK_ASSERT(so);
4212 		else
4213 			SOCK_SENDBUF_UNLOCK_ASSERT(so);
4214 	}
4215 }
4216 
4217 /*
4218  * Create an external-format (``xsocket'') structure using the information in
4219  * the kernel-format socket structure pointed to by so.  This is done to
4220  * reduce the spew of irrelevant information over this interface, to isolate
4221  * user code from changes in the kernel structure, and potentially to provide
4222  * information-hiding if we decide that some of this information should be
4223  * hidden from users.
4224  */
4225 void
4226 sotoxsocket(struct socket *so, struct xsocket *xso)
4227 {
4228 
4229 	bzero(xso, sizeof(*xso));
4230 	xso->xso_len = sizeof *xso;
4231 	xso->xso_so = (uintptr_t)so;
4232 	xso->so_type = so->so_type;
4233 	xso->so_options = so->so_options;
4234 	xso->so_linger = so->so_linger;
4235 	xso->so_state = so->so_state;
4236 	xso->so_pcb = (uintptr_t)so->so_pcb;
4237 	xso->xso_protocol = so->so_proto->pr_protocol;
4238 	xso->xso_family = so->so_proto->pr_domain->dom_family;
4239 	xso->so_timeo = so->so_timeo;
4240 	xso->so_error = so->so_error;
4241 	xso->so_uid = so->so_cred->cr_uid;
4242 	xso->so_pgid = so->so_sigio ? so->so_sigio->sio_pgid : 0;
4243 	if (SOLISTENING(so)) {
4244 		xso->so_qlen = so->sol_qlen;
4245 		xso->so_incqlen = so->sol_incqlen;
4246 		xso->so_qlimit = so->sol_qlimit;
4247 		xso->so_oobmark = 0;
4248 	} else {
4249 		xso->so_state |= so->so_qstate;
4250 		xso->so_qlen = xso->so_incqlen = xso->so_qlimit = 0;
4251 		xso->so_oobmark = so->so_oobmark;
4252 		sbtoxsockbuf(&so->so_snd, &xso->so_snd);
4253 		sbtoxsockbuf(&so->so_rcv, &xso->so_rcv);
4254 	}
4255 }
4256 
4257 int
4258 so_options_get(const struct socket *so)
4259 {
4260 
4261 	return (so->so_options);
4262 }
4263 
4264 void
4265 so_options_set(struct socket *so, int val)
4266 {
4267 
4268 	so->so_options = val;
4269 }
4270 
4271 int
4272 so_error_get(const struct socket *so)
4273 {
4274 
4275 	return (so->so_error);
4276 }
4277 
4278 void
4279 so_error_set(struct socket *so, int val)
4280 {
4281 
4282 	so->so_error = val;
4283 }
4284