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