xref: /freebsd-14.2/sys/kern/uipc_socket.c (revision c3fe41b3)
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 	SOCKBUF_LOCK(sb);
2564 
2565 #ifdef KERN_TLS
2566 	if (sb->sb_tls_info != NULL) {
2567 		SOCKBUF_UNLOCK(sb);
2568 		SOCK_IO_RECV_UNLOCK(so);
2569 		return (soreceive_generic(so, psa, uio, mp0, controlp,
2570 		    flagsp));
2571 	}
2572 #endif
2573 
2574 	/* Easy one, no space to copyout anything. */
2575 	if (uio->uio_resid == 0) {
2576 		error = EINVAL;
2577 		goto out;
2578 	}
2579 	oresid = uio->uio_resid;
2580 
2581 	/* We will never ever get anything unless we are or were connected. */
2582 	if (!(so->so_state & (SS_ISCONNECTED|SS_ISDISCONNECTED))) {
2583 		error = ENOTCONN;
2584 		goto out;
2585 	}
2586 
2587 restart:
2588 	SOCKBUF_LOCK_ASSERT(&so->so_rcv);
2589 
2590 	/* Abort if socket has reported problems. */
2591 	if (so->so_error) {
2592 		if (sbavail(sb) > 0)
2593 			goto deliver;
2594 		if (oresid > uio->uio_resid)
2595 			goto out;
2596 		error = so->so_error;
2597 		if (!(flags & MSG_PEEK))
2598 			so->so_error = 0;
2599 		goto out;
2600 	}
2601 
2602 	/* Door is closed.  Deliver what is left, if any. */
2603 	if (sb->sb_state & SBS_CANTRCVMORE) {
2604 		if (sbavail(sb) > 0)
2605 			goto deliver;
2606 		else
2607 			goto out;
2608 	}
2609 
2610 	/* Socket buffer is empty and we shall not block. */
2611 	if (sbavail(sb) == 0 &&
2612 	    ((so->so_state & SS_NBIO) || (flags & (MSG_DONTWAIT|MSG_NBIO)))) {
2613 		error = EAGAIN;
2614 		goto out;
2615 	}
2616 
2617 	/* Socket buffer got some data that we shall deliver now. */
2618 	if (sbavail(sb) > 0 && !(flags & MSG_WAITALL) &&
2619 	    ((so->so_state & SS_NBIO) ||
2620 	     (flags & (MSG_DONTWAIT|MSG_NBIO)) ||
2621 	     sbavail(sb) >= sb->sb_lowat ||
2622 	     sbavail(sb) >= uio->uio_resid ||
2623 	     sbavail(sb) >= sb->sb_hiwat) ) {
2624 		goto deliver;
2625 	}
2626 
2627 	/* On MSG_WAITALL we must wait until all data or error arrives. */
2628 	if ((flags & MSG_WAITALL) &&
2629 	    (sbavail(sb) >= uio->uio_resid || sbavail(sb) >= sb->sb_hiwat))
2630 		goto deliver;
2631 
2632 	/*
2633 	 * Wait and block until (more) data comes in.
2634 	 * NB: Drops the sockbuf lock during wait.
2635 	 */
2636 	error = sbwait(so, SO_RCV);
2637 	if (error)
2638 		goto out;
2639 	goto restart;
2640 
2641 deliver:
2642 	SOCKBUF_LOCK_ASSERT(&so->so_rcv);
2643 	KASSERT(sbavail(sb) > 0, ("%s: sockbuf empty", __func__));
2644 	KASSERT(sb->sb_mb != NULL, ("%s: sb_mb == NULL", __func__));
2645 
2646 	/* Statistics. */
2647 	if (uio->uio_td)
2648 		uio->uio_td->td_ru.ru_msgrcv++;
2649 
2650 	/* Fill uio until full or current end of socket buffer is reached. */
2651 	len = min(uio->uio_resid, sbavail(sb));
2652 	if (mp0 != NULL) {
2653 		/* Dequeue as many mbufs as possible. */
2654 		if (!(flags & MSG_PEEK) && len >= sb->sb_mb->m_len) {
2655 			if (*mp0 == NULL)
2656 				*mp0 = sb->sb_mb;
2657 			else
2658 				m_cat(*mp0, sb->sb_mb);
2659 			for (m = sb->sb_mb;
2660 			     m != NULL && m->m_len <= len;
2661 			     m = m->m_next) {
2662 				KASSERT(!(m->m_flags & M_NOTAVAIL),
2663 				    ("%s: m %p not available", __func__, m));
2664 				len -= m->m_len;
2665 				uio->uio_resid -= m->m_len;
2666 				sbfree(sb, m);
2667 				n = m;
2668 			}
2669 			n->m_next = NULL;
2670 			sb->sb_mb = m;
2671 			sb->sb_lastrecord = sb->sb_mb;
2672 			if (sb->sb_mb == NULL)
2673 				SB_EMPTY_FIXUP(sb);
2674 		}
2675 		/* Copy the remainder. */
2676 		if (len > 0) {
2677 			KASSERT(sb->sb_mb != NULL,
2678 			    ("%s: len > 0 && sb->sb_mb empty", __func__));
2679 
2680 			m = m_copym(sb->sb_mb, 0, len, M_NOWAIT);
2681 			if (m == NULL)
2682 				len = 0;	/* Don't flush data from sockbuf. */
2683 			else
2684 				uio->uio_resid -= len;
2685 			if (*mp0 != NULL)
2686 				m_cat(*mp0, m);
2687 			else
2688 				*mp0 = m;
2689 			if (*mp0 == NULL) {
2690 				error = ENOBUFS;
2691 				goto out;
2692 			}
2693 		}
2694 	} else {
2695 		/* NB: Must unlock socket buffer as uiomove may sleep. */
2696 		SOCKBUF_UNLOCK(sb);
2697 		error = m_mbuftouio(uio, sb->sb_mb, len);
2698 		SOCKBUF_LOCK(sb);
2699 		if (error)
2700 			goto out;
2701 	}
2702 	SBLASTRECORDCHK(sb);
2703 	SBLASTMBUFCHK(sb);
2704 
2705 	/*
2706 	 * Remove the delivered data from the socket buffer unless we
2707 	 * were only peeking.
2708 	 */
2709 	if (!(flags & MSG_PEEK)) {
2710 		if (len > 0)
2711 			sbdrop_locked(sb, len);
2712 
2713 		/* Notify protocol that we drained some data. */
2714 		if ((so->so_proto->pr_flags & PR_WANTRCVD) &&
2715 		    (((flags & MSG_WAITALL) && uio->uio_resid > 0) ||
2716 		     !(flags & MSG_SOCALLBCK))) {
2717 			SOCKBUF_UNLOCK(sb);
2718 			VNET_SO_ASSERT(so);
2719 			so->so_proto->pr_rcvd(so, flags);
2720 			SOCKBUF_LOCK(sb);
2721 		}
2722 	}
2723 
2724 	/*
2725 	 * For MSG_WAITALL we may have to loop again and wait for
2726 	 * more data to come in.
2727 	 */
2728 	if ((flags & MSG_WAITALL) && uio->uio_resid > 0)
2729 		goto restart;
2730 out:
2731 	SBLASTRECORDCHK(sb);
2732 	SBLASTMBUFCHK(sb);
2733 	SOCKBUF_UNLOCK(sb);
2734 	SOCK_IO_RECV_UNLOCK(so);
2735 	return (error);
2736 }
2737 
2738 /*
2739  * Optimized version of soreceive() for simple datagram cases from userspace.
2740  * Unlike in the stream case, we're able to drop a datagram if copyout()
2741  * fails, and because we handle datagrams atomically, we don't need to use a
2742  * sleep lock to prevent I/O interlacing.
2743  */
2744 int
2745 soreceive_dgram(struct socket *so, struct sockaddr **psa, struct uio *uio,
2746     struct mbuf **mp0, struct mbuf **controlp, int *flagsp)
2747 {
2748 	struct mbuf *m, *m2;
2749 	int flags, error;
2750 	ssize_t len;
2751 	struct protosw *pr = so->so_proto;
2752 	struct mbuf *nextrecord;
2753 
2754 	if (psa != NULL)
2755 		*psa = NULL;
2756 	if (controlp != NULL)
2757 		*controlp = NULL;
2758 	if (flagsp != NULL)
2759 		flags = *flagsp &~ MSG_EOR;
2760 	else
2761 		flags = 0;
2762 
2763 	/*
2764 	 * For any complicated cases, fall back to the full
2765 	 * soreceive_generic().
2766 	 */
2767 	if (mp0 != NULL || (flags & (MSG_PEEK | MSG_OOB | MSG_TRUNC)))
2768 		return (soreceive_generic(so, psa, uio, mp0, controlp,
2769 		    flagsp));
2770 
2771 	/*
2772 	 * Enforce restrictions on use.
2773 	 */
2774 	KASSERT((pr->pr_flags & PR_WANTRCVD) == 0,
2775 	    ("soreceive_dgram: wantrcvd"));
2776 	KASSERT(pr->pr_flags & PR_ATOMIC, ("soreceive_dgram: !atomic"));
2777 	KASSERT((so->so_rcv.sb_state & SBS_RCVATMARK) == 0,
2778 	    ("soreceive_dgram: SBS_RCVATMARK"));
2779 	KASSERT((so->so_proto->pr_flags & PR_CONNREQUIRED) == 0,
2780 	    ("soreceive_dgram: P_CONNREQUIRED"));
2781 
2782 	/*
2783 	 * Loop blocking while waiting for a datagram.
2784 	 */
2785 	SOCKBUF_LOCK(&so->so_rcv);
2786 	while ((m = so->so_rcv.sb_mb) == NULL) {
2787 		KASSERT(sbavail(&so->so_rcv) == 0,
2788 		    ("soreceive_dgram: sb_mb NULL but sbavail %u",
2789 		    sbavail(&so->so_rcv)));
2790 		if (so->so_error) {
2791 			error = so->so_error;
2792 			so->so_error = 0;
2793 			SOCKBUF_UNLOCK(&so->so_rcv);
2794 			return (error);
2795 		}
2796 		if (so->so_rcv.sb_state & SBS_CANTRCVMORE ||
2797 		    uio->uio_resid == 0) {
2798 			SOCKBUF_UNLOCK(&so->so_rcv);
2799 			return (0);
2800 		}
2801 		if ((so->so_state & SS_NBIO) ||
2802 		    (flags & (MSG_DONTWAIT|MSG_NBIO))) {
2803 			SOCKBUF_UNLOCK(&so->so_rcv);
2804 			return (EWOULDBLOCK);
2805 		}
2806 		SBLASTRECORDCHK(&so->so_rcv);
2807 		SBLASTMBUFCHK(&so->so_rcv);
2808 		error = sbwait(so, SO_RCV);
2809 		if (error) {
2810 			SOCKBUF_UNLOCK(&so->so_rcv);
2811 			return (error);
2812 		}
2813 	}
2814 	SOCKBUF_LOCK_ASSERT(&so->so_rcv);
2815 
2816 	if (uio->uio_td)
2817 		uio->uio_td->td_ru.ru_msgrcv++;
2818 	SBLASTRECORDCHK(&so->so_rcv);
2819 	SBLASTMBUFCHK(&so->so_rcv);
2820 	nextrecord = m->m_nextpkt;
2821 	if (nextrecord == NULL) {
2822 		KASSERT(so->so_rcv.sb_lastrecord == m,
2823 		    ("soreceive_dgram: lastrecord != m"));
2824 	}
2825 
2826 	KASSERT(so->so_rcv.sb_mb->m_nextpkt == nextrecord,
2827 	    ("soreceive_dgram: m_nextpkt != nextrecord"));
2828 
2829 	/*
2830 	 * Pull 'm' and its chain off the front of the packet queue.
2831 	 */
2832 	so->so_rcv.sb_mb = NULL;
2833 	sockbuf_pushsync(&so->so_rcv, nextrecord);
2834 
2835 	/*
2836 	 * Walk 'm's chain and free that many bytes from the socket buffer.
2837 	 */
2838 	for (m2 = m; m2 != NULL; m2 = m2->m_next)
2839 		sbfree(&so->so_rcv, m2);
2840 
2841 	/*
2842 	 * Do a few last checks before we let go of the lock.
2843 	 */
2844 	SBLASTRECORDCHK(&so->so_rcv);
2845 	SBLASTMBUFCHK(&so->so_rcv);
2846 	SOCKBUF_UNLOCK(&so->so_rcv);
2847 
2848 	if (pr->pr_flags & PR_ADDR) {
2849 		KASSERT(m->m_type == MT_SONAME,
2850 		    ("m->m_type == %d", m->m_type));
2851 		if (psa != NULL)
2852 			*psa = sodupsockaddr(mtod(m, struct sockaddr *),
2853 			    M_NOWAIT);
2854 		m = m_free(m);
2855 	}
2856 	if (m == NULL) {
2857 		/* XXXRW: Can this happen? */
2858 		return (0);
2859 	}
2860 
2861 	/*
2862 	 * Packet to copyout() is now in 'm' and it is disconnected from the
2863 	 * queue.
2864 	 *
2865 	 * Process one or more MT_CONTROL mbufs present before any data mbufs
2866 	 * in the first mbuf chain on the socket buffer.  We call into the
2867 	 * protocol to perform externalization (or freeing if controlp ==
2868 	 * NULL). In some cases there can be only MT_CONTROL mbufs without
2869 	 * MT_DATA mbufs.
2870 	 */
2871 	if (m->m_type == MT_CONTROL) {
2872 		struct mbuf *cm = NULL, *cmn;
2873 		struct mbuf **cme = &cm;
2874 
2875 		do {
2876 			m2 = m->m_next;
2877 			m->m_next = NULL;
2878 			*cme = m;
2879 			cme = &(*cme)->m_next;
2880 			m = m2;
2881 		} while (m != NULL && m->m_type == MT_CONTROL);
2882 		while (cm != NULL) {
2883 			cmn = cm->m_next;
2884 			cm->m_next = NULL;
2885 			if (pr->pr_domain->dom_externalize != NULL) {
2886 				error = (*pr->pr_domain->dom_externalize)
2887 				    (cm, controlp, flags);
2888 			} else if (controlp != NULL)
2889 				*controlp = cm;
2890 			else
2891 				m_freem(cm);
2892 			if (controlp != NULL) {
2893 				while (*controlp != NULL)
2894 					controlp = &(*controlp)->m_next;
2895 			}
2896 			cm = cmn;
2897 		}
2898 	}
2899 	KASSERT(m == NULL || m->m_type == MT_DATA,
2900 	    ("soreceive_dgram: !data"));
2901 	while (m != NULL && uio->uio_resid > 0) {
2902 		len = uio->uio_resid;
2903 		if (len > m->m_len)
2904 			len = m->m_len;
2905 		error = uiomove(mtod(m, char *), (int)len, uio);
2906 		if (error) {
2907 			m_freem(m);
2908 			return (error);
2909 		}
2910 		if (len == m->m_len)
2911 			m = m_free(m);
2912 		else {
2913 			m->m_data += len;
2914 			m->m_len -= len;
2915 		}
2916 	}
2917 	if (m != NULL) {
2918 		flags |= MSG_TRUNC;
2919 		m_freem(m);
2920 	}
2921 	if (flagsp != NULL)
2922 		*flagsp |= flags;
2923 	return (0);
2924 }
2925 
2926 int
2927 soreceive(struct socket *so, struct sockaddr **psa, struct uio *uio,
2928     struct mbuf **mp0, struct mbuf **controlp, int *flagsp)
2929 {
2930 	int error;
2931 
2932 	CURVNET_SET(so->so_vnet);
2933 	error = so->so_proto->pr_soreceive(so, psa, uio, mp0, controlp, flagsp);
2934 	CURVNET_RESTORE();
2935 	return (error);
2936 }
2937 
2938 int
2939 soshutdown(struct socket *so, int how)
2940 {
2941 	struct protosw *pr;
2942 	int error, soerror_enotconn;
2943 
2944 	if (!(how == SHUT_RD || how == SHUT_WR || how == SHUT_RDWR))
2945 		return (EINVAL);
2946 
2947 	soerror_enotconn = 0;
2948 	SOCK_LOCK(so);
2949 	if ((so->so_state &
2950 	    (SS_ISCONNECTED | SS_ISCONNECTING | SS_ISDISCONNECTING)) == 0) {
2951 		/*
2952 		 * POSIX mandates us to return ENOTCONN when shutdown(2) is
2953 		 * invoked on a datagram sockets, however historically we would
2954 		 * actually tear socket down. This is known to be leveraged by
2955 		 * some applications to unblock process waiting in recvXXX(2)
2956 		 * by other process that it shares that socket with. Try to meet
2957 		 * both backward-compatibility and POSIX requirements by forcing
2958 		 * ENOTCONN but still asking protocol to perform pru_shutdown().
2959 		 */
2960 		if (so->so_type != SOCK_DGRAM && !SOLISTENING(so)) {
2961 			SOCK_UNLOCK(so);
2962 			return (ENOTCONN);
2963 		}
2964 		soerror_enotconn = 1;
2965 	}
2966 
2967 	if (SOLISTENING(so)) {
2968 		if (how != SHUT_WR) {
2969 			so->so_error = ECONNABORTED;
2970 			solisten_wakeup(so);	/* unlocks so */
2971 		} else {
2972 			SOCK_UNLOCK(so);
2973 		}
2974 		goto done;
2975 	}
2976 	SOCK_UNLOCK(so);
2977 
2978 	CURVNET_SET(so->so_vnet);
2979 	pr = so->so_proto;
2980 	if (pr->pr_flush != NULL)
2981 		pr->pr_flush(so, how);
2982 	if (how != SHUT_WR)
2983 		sorflush(so);
2984 	if (how != SHUT_RD) {
2985 		error = pr->pr_shutdown(so);
2986 		wakeup(&so->so_timeo);
2987 		CURVNET_RESTORE();
2988 		return ((error == 0 && soerror_enotconn) ? ENOTCONN : error);
2989 	}
2990 	wakeup(&so->so_timeo);
2991 	CURVNET_RESTORE();
2992 
2993 done:
2994 	return (soerror_enotconn ? ENOTCONN : 0);
2995 }
2996 
2997 void
2998 sorflush(struct socket *so)
2999 {
3000 	struct protosw *pr;
3001 	int error;
3002 
3003 	VNET_SO_ASSERT(so);
3004 
3005 	/*
3006 	 * Dislodge threads currently blocked in receive and wait to acquire
3007 	 * a lock against other simultaneous readers before clearing the
3008 	 * socket buffer.  Don't let our acquire be interrupted by a signal
3009 	 * despite any existing socket disposition on interruptable waiting.
3010 	 */
3011 	socantrcvmore(so);
3012 
3013 	error = SOCK_IO_RECV_LOCK(so, SBL_WAIT | SBL_NOINTR);
3014 	if (error != 0) {
3015 		KASSERT(SOLISTENING(so),
3016 		    ("%s: soiolock(%p) failed", __func__, so));
3017 		return;
3018 	}
3019 
3020 	pr = so->so_proto;
3021 	if (pr->pr_flags & PR_RIGHTS) {
3022 		MPASS(pr->pr_domain->dom_dispose != NULL);
3023 		(*pr->pr_domain->dom_dispose)(so);
3024 	} else {
3025 		sbrelease(so, SO_RCV);
3026 		SOCK_IO_RECV_UNLOCK(so);
3027 	}
3028 
3029 }
3030 
3031 /*
3032  * Wrapper for Socket established helper hook.
3033  * Parameters: socket, context of the hook point, hook id.
3034  */
3035 static int inline
3036 hhook_run_socket(struct socket *so, void *hctx, int32_t h_id)
3037 {
3038 	struct socket_hhook_data hhook_data = {
3039 		.so = so,
3040 		.hctx = hctx,
3041 		.m = NULL,
3042 		.status = 0
3043 	};
3044 
3045 	CURVNET_SET(so->so_vnet);
3046 	HHOOKS_RUN_IF(V_socket_hhh[h_id], &hhook_data, &so->osd);
3047 	CURVNET_RESTORE();
3048 
3049 	/* Ugly but needed, since hhooks return void for now */
3050 	return (hhook_data.status);
3051 }
3052 
3053 /*
3054  * Perhaps this routine, and sooptcopyout(), below, ought to come in an
3055  * additional variant to handle the case where the option value needs to be
3056  * some kind of integer, but not a specific size.  In addition to their use
3057  * here, these functions are also called by the protocol-level pr_ctloutput()
3058  * routines.
3059  */
3060 int
3061 sooptcopyin(struct sockopt *sopt, void *buf, size_t len, size_t minlen)
3062 {
3063 	size_t	valsize;
3064 
3065 	/*
3066 	 * If the user gives us more than we wanted, we ignore it, but if we
3067 	 * don't get the minimum length the caller wants, we return EINVAL.
3068 	 * On success, sopt->sopt_valsize is set to however much we actually
3069 	 * retrieved.
3070 	 */
3071 	if ((valsize = sopt->sopt_valsize) < minlen)
3072 		return EINVAL;
3073 	if (valsize > len)
3074 		sopt->sopt_valsize = valsize = len;
3075 
3076 	if (sopt->sopt_td != NULL)
3077 		return (copyin(sopt->sopt_val, buf, valsize));
3078 
3079 	bcopy(sopt->sopt_val, buf, valsize);
3080 	return (0);
3081 }
3082 
3083 /*
3084  * Kernel version of setsockopt(2).
3085  *
3086  * XXX: optlen is size_t, not socklen_t
3087  */
3088 int
3089 so_setsockopt(struct socket *so, int level, int optname, void *optval,
3090     size_t optlen)
3091 {
3092 	struct sockopt sopt;
3093 
3094 	sopt.sopt_level = level;
3095 	sopt.sopt_name = optname;
3096 	sopt.sopt_dir = SOPT_SET;
3097 	sopt.sopt_val = optval;
3098 	sopt.sopt_valsize = optlen;
3099 	sopt.sopt_td = NULL;
3100 	return (sosetopt(so, &sopt));
3101 }
3102 
3103 int
3104 sosetopt(struct socket *so, struct sockopt *sopt)
3105 {
3106 	int	error, optval;
3107 	struct	linger l;
3108 	struct	timeval tv;
3109 	sbintime_t val, *valp;
3110 	uint32_t val32;
3111 #ifdef MAC
3112 	struct mac extmac;
3113 #endif
3114 
3115 	CURVNET_SET(so->so_vnet);
3116 	error = 0;
3117 	if (sopt->sopt_level != SOL_SOCKET) {
3118 		if (so->so_proto->pr_ctloutput != NULL)
3119 			error = (*so->so_proto->pr_ctloutput)(so, sopt);
3120 		else
3121 			error = ENOPROTOOPT;
3122 	} else {
3123 		switch (sopt->sopt_name) {
3124 		case SO_ACCEPTFILTER:
3125 			error = accept_filt_setopt(so, sopt);
3126 			if (error)
3127 				goto bad;
3128 			break;
3129 
3130 		case SO_LINGER:
3131 			error = sooptcopyin(sopt, &l, sizeof l, sizeof l);
3132 			if (error)
3133 				goto bad;
3134 			if (l.l_linger < 0 ||
3135 			    l.l_linger > USHRT_MAX ||
3136 			    l.l_linger > (INT_MAX / hz)) {
3137 				error = EDOM;
3138 				goto bad;
3139 			}
3140 			SOCK_LOCK(so);
3141 			so->so_linger = l.l_linger;
3142 			if (l.l_onoff)
3143 				so->so_options |= SO_LINGER;
3144 			else
3145 				so->so_options &= ~SO_LINGER;
3146 			SOCK_UNLOCK(so);
3147 			break;
3148 
3149 		case SO_DEBUG:
3150 		case SO_KEEPALIVE:
3151 		case SO_DONTROUTE:
3152 		case SO_USELOOPBACK:
3153 		case SO_BROADCAST:
3154 		case SO_REUSEADDR:
3155 		case SO_REUSEPORT:
3156 		case SO_REUSEPORT_LB:
3157 		case SO_OOBINLINE:
3158 		case SO_TIMESTAMP:
3159 		case SO_BINTIME:
3160 		case SO_NOSIGPIPE:
3161 		case SO_NO_DDP:
3162 		case SO_NO_OFFLOAD:
3163 		case SO_RERROR:
3164 			error = sooptcopyin(sopt, &optval, sizeof optval,
3165 			    sizeof optval);
3166 			if (error)
3167 				goto bad;
3168 			SOCK_LOCK(so);
3169 			if (optval)
3170 				so->so_options |= sopt->sopt_name;
3171 			else
3172 				so->so_options &= ~sopt->sopt_name;
3173 			SOCK_UNLOCK(so);
3174 			break;
3175 
3176 		case SO_SETFIB:
3177 			error = sooptcopyin(sopt, &optval, sizeof optval,
3178 			    sizeof optval);
3179 			if (error)
3180 				goto bad;
3181 
3182 			if (optval < 0 || optval >= rt_numfibs) {
3183 				error = EINVAL;
3184 				goto bad;
3185 			}
3186 			if (((so->so_proto->pr_domain->dom_family == PF_INET) ||
3187 			   (so->so_proto->pr_domain->dom_family == PF_INET6) ||
3188 			   (so->so_proto->pr_domain->dom_family == PF_ROUTE)))
3189 				so->so_fibnum = optval;
3190 			else
3191 				so->so_fibnum = 0;
3192 			break;
3193 
3194 		case SO_USER_COOKIE:
3195 			error = sooptcopyin(sopt, &val32, sizeof val32,
3196 			    sizeof val32);
3197 			if (error)
3198 				goto bad;
3199 			so->so_user_cookie = val32;
3200 			break;
3201 
3202 		case SO_SNDBUF:
3203 		case SO_RCVBUF:
3204 		case SO_SNDLOWAT:
3205 		case SO_RCVLOWAT:
3206 			error = so->so_proto->pr_setsbopt(so, sopt);
3207 			if (error)
3208 				goto bad;
3209 			break;
3210 
3211 		case SO_SNDTIMEO:
3212 		case SO_RCVTIMEO:
3213 #ifdef COMPAT_FREEBSD32
3214 			if (SV_CURPROC_FLAG(SV_ILP32)) {
3215 				struct timeval32 tv32;
3216 
3217 				error = sooptcopyin(sopt, &tv32, sizeof tv32,
3218 				    sizeof tv32);
3219 				CP(tv32, tv, tv_sec);
3220 				CP(tv32, tv, tv_usec);
3221 			} else
3222 #endif
3223 				error = sooptcopyin(sopt, &tv, sizeof tv,
3224 				    sizeof tv);
3225 			if (error)
3226 				goto bad;
3227 			if (tv.tv_sec < 0 || tv.tv_usec < 0 ||
3228 			    tv.tv_usec >= 1000000) {
3229 				error = EDOM;
3230 				goto bad;
3231 			}
3232 			if (tv.tv_sec > INT32_MAX)
3233 				val = SBT_MAX;
3234 			else
3235 				val = tvtosbt(tv);
3236 			SOCK_LOCK(so);
3237 			valp = sopt->sopt_name == SO_SNDTIMEO ?
3238 			    (SOLISTENING(so) ? &so->sol_sbsnd_timeo :
3239 			    &so->so_snd.sb_timeo) :
3240 			    (SOLISTENING(so) ? &so->sol_sbrcv_timeo :
3241 			    &so->so_rcv.sb_timeo);
3242 			*valp = val;
3243 			SOCK_UNLOCK(so);
3244 			break;
3245 
3246 		case SO_LABEL:
3247 #ifdef MAC
3248 			error = sooptcopyin(sopt, &extmac, sizeof extmac,
3249 			    sizeof extmac);
3250 			if (error)
3251 				goto bad;
3252 			error = mac_setsockopt_label(sopt->sopt_td->td_ucred,
3253 			    so, &extmac);
3254 #else
3255 			error = EOPNOTSUPP;
3256 #endif
3257 			break;
3258 
3259 		case SO_TS_CLOCK:
3260 			error = sooptcopyin(sopt, &optval, sizeof optval,
3261 			    sizeof optval);
3262 			if (error)
3263 				goto bad;
3264 			if (optval < 0 || optval > SO_TS_CLOCK_MAX) {
3265 				error = EINVAL;
3266 				goto bad;
3267 			}
3268 			so->so_ts_clock = optval;
3269 			break;
3270 
3271 		case SO_MAX_PACING_RATE:
3272 			error = sooptcopyin(sopt, &val32, sizeof(val32),
3273 			    sizeof(val32));
3274 			if (error)
3275 				goto bad;
3276 			so->so_max_pacing_rate = val32;
3277 			break;
3278 
3279 		default:
3280 			if (V_socket_hhh[HHOOK_SOCKET_OPT]->hhh_nhooks > 0)
3281 				error = hhook_run_socket(so, sopt,
3282 				    HHOOK_SOCKET_OPT);
3283 			else
3284 				error = ENOPROTOOPT;
3285 			break;
3286 		}
3287 		if (error == 0 && so->so_proto->pr_ctloutput != NULL)
3288 			(void)(*so->so_proto->pr_ctloutput)(so, sopt);
3289 	}
3290 bad:
3291 	CURVNET_RESTORE();
3292 	return (error);
3293 }
3294 
3295 /*
3296  * Helper routine for getsockopt.
3297  */
3298 int
3299 sooptcopyout(struct sockopt *sopt, const void *buf, size_t len)
3300 {
3301 	int	error;
3302 	size_t	valsize;
3303 
3304 	error = 0;
3305 
3306 	/*
3307 	 * Documented get behavior is that we always return a value, possibly
3308 	 * truncated to fit in the user's buffer.  Traditional behavior is
3309 	 * that we always tell the user precisely how much we copied, rather
3310 	 * than something useful like the total amount we had available for
3311 	 * her.  Note that this interface is not idempotent; the entire
3312 	 * answer must be generated ahead of time.
3313 	 */
3314 	valsize = min(len, sopt->sopt_valsize);
3315 	sopt->sopt_valsize = valsize;
3316 	if (sopt->sopt_val != NULL) {
3317 		if (sopt->sopt_td != NULL)
3318 			error = copyout(buf, sopt->sopt_val, valsize);
3319 		else
3320 			bcopy(buf, sopt->sopt_val, valsize);
3321 	}
3322 	return (error);
3323 }
3324 
3325 int
3326 sogetopt(struct socket *so, struct sockopt *sopt)
3327 {
3328 	int	error, optval;
3329 	struct	linger l;
3330 	struct	timeval tv;
3331 #ifdef MAC
3332 	struct mac extmac;
3333 #endif
3334 
3335 	CURVNET_SET(so->so_vnet);
3336 	error = 0;
3337 	if (sopt->sopt_level != SOL_SOCKET) {
3338 		if (so->so_proto->pr_ctloutput != NULL)
3339 			error = (*so->so_proto->pr_ctloutput)(so, sopt);
3340 		else
3341 			error = ENOPROTOOPT;
3342 		CURVNET_RESTORE();
3343 		return (error);
3344 	} else {
3345 		switch (sopt->sopt_name) {
3346 		case SO_ACCEPTFILTER:
3347 			error = accept_filt_getopt(so, sopt);
3348 			break;
3349 
3350 		case SO_LINGER:
3351 			SOCK_LOCK(so);
3352 			l.l_onoff = so->so_options & SO_LINGER;
3353 			l.l_linger = so->so_linger;
3354 			SOCK_UNLOCK(so);
3355 			error = sooptcopyout(sopt, &l, sizeof l);
3356 			break;
3357 
3358 		case SO_USELOOPBACK:
3359 		case SO_DONTROUTE:
3360 		case SO_DEBUG:
3361 		case SO_KEEPALIVE:
3362 		case SO_REUSEADDR:
3363 		case SO_REUSEPORT:
3364 		case SO_REUSEPORT_LB:
3365 		case SO_BROADCAST:
3366 		case SO_OOBINLINE:
3367 		case SO_ACCEPTCONN:
3368 		case SO_TIMESTAMP:
3369 		case SO_BINTIME:
3370 		case SO_NOSIGPIPE:
3371 		case SO_NO_DDP:
3372 		case SO_NO_OFFLOAD:
3373 		case SO_RERROR:
3374 			optval = so->so_options & sopt->sopt_name;
3375 integer:
3376 			error = sooptcopyout(sopt, &optval, sizeof optval);
3377 			break;
3378 
3379 		case SO_DOMAIN:
3380 			optval = so->so_proto->pr_domain->dom_family;
3381 			goto integer;
3382 
3383 		case SO_TYPE:
3384 			optval = so->so_type;
3385 			goto integer;
3386 
3387 		case SO_PROTOCOL:
3388 			optval = so->so_proto->pr_protocol;
3389 			goto integer;
3390 
3391 		case SO_ERROR:
3392 			SOCK_LOCK(so);
3393 			if (so->so_error) {
3394 				optval = so->so_error;
3395 				so->so_error = 0;
3396 			} else {
3397 				optval = so->so_rerror;
3398 				so->so_rerror = 0;
3399 			}
3400 			SOCK_UNLOCK(so);
3401 			goto integer;
3402 
3403 		case SO_SNDBUF:
3404 			optval = SOLISTENING(so) ? so->sol_sbsnd_hiwat :
3405 			    so->so_snd.sb_hiwat;
3406 			goto integer;
3407 
3408 		case SO_RCVBUF:
3409 			optval = SOLISTENING(so) ? so->sol_sbrcv_hiwat :
3410 			    so->so_rcv.sb_hiwat;
3411 			goto integer;
3412 
3413 		case SO_SNDLOWAT:
3414 			optval = SOLISTENING(so) ? so->sol_sbsnd_lowat :
3415 			    so->so_snd.sb_lowat;
3416 			goto integer;
3417 
3418 		case SO_RCVLOWAT:
3419 			optval = SOLISTENING(so) ? so->sol_sbrcv_lowat :
3420 			    so->so_rcv.sb_lowat;
3421 			goto integer;
3422 
3423 		case SO_SNDTIMEO:
3424 		case SO_RCVTIMEO:
3425 			SOCK_LOCK(so);
3426 			tv = sbttotv(sopt->sopt_name == SO_SNDTIMEO ?
3427 			    (SOLISTENING(so) ? so->sol_sbsnd_timeo :
3428 			    so->so_snd.sb_timeo) :
3429 			    (SOLISTENING(so) ? so->sol_sbrcv_timeo :
3430 			    so->so_rcv.sb_timeo));
3431 			SOCK_UNLOCK(so);
3432 #ifdef COMPAT_FREEBSD32
3433 			if (SV_CURPROC_FLAG(SV_ILP32)) {
3434 				struct timeval32 tv32;
3435 
3436 				CP(tv, tv32, tv_sec);
3437 				CP(tv, tv32, tv_usec);
3438 				error = sooptcopyout(sopt, &tv32, sizeof tv32);
3439 			} else
3440 #endif
3441 				error = sooptcopyout(sopt, &tv, sizeof tv);
3442 			break;
3443 
3444 		case SO_LABEL:
3445 #ifdef MAC
3446 			error = sooptcopyin(sopt, &extmac, sizeof(extmac),
3447 			    sizeof(extmac));
3448 			if (error)
3449 				goto bad;
3450 			error = mac_getsockopt_label(sopt->sopt_td->td_ucred,
3451 			    so, &extmac);
3452 			if (error)
3453 				goto bad;
3454 			error = sooptcopyout(sopt, &extmac, sizeof extmac);
3455 #else
3456 			error = EOPNOTSUPP;
3457 #endif
3458 			break;
3459 
3460 		case SO_PEERLABEL:
3461 #ifdef MAC
3462 			error = sooptcopyin(sopt, &extmac, sizeof(extmac),
3463 			    sizeof(extmac));
3464 			if (error)
3465 				goto bad;
3466 			error = mac_getsockopt_peerlabel(
3467 			    sopt->sopt_td->td_ucred, so, &extmac);
3468 			if (error)
3469 				goto bad;
3470 			error = sooptcopyout(sopt, &extmac, sizeof extmac);
3471 #else
3472 			error = EOPNOTSUPP;
3473 #endif
3474 			break;
3475 
3476 		case SO_LISTENQLIMIT:
3477 			optval = SOLISTENING(so) ? so->sol_qlimit : 0;
3478 			goto integer;
3479 
3480 		case SO_LISTENQLEN:
3481 			optval = SOLISTENING(so) ? so->sol_qlen : 0;
3482 			goto integer;
3483 
3484 		case SO_LISTENINCQLEN:
3485 			optval = SOLISTENING(so) ? so->sol_incqlen : 0;
3486 			goto integer;
3487 
3488 		case SO_TS_CLOCK:
3489 			optval = so->so_ts_clock;
3490 			goto integer;
3491 
3492 		case SO_MAX_PACING_RATE:
3493 			optval = so->so_max_pacing_rate;
3494 			goto integer;
3495 
3496 		default:
3497 			if (V_socket_hhh[HHOOK_SOCKET_OPT]->hhh_nhooks > 0)
3498 				error = hhook_run_socket(so, sopt,
3499 				    HHOOK_SOCKET_OPT);
3500 			else
3501 				error = ENOPROTOOPT;
3502 			break;
3503 		}
3504 	}
3505 #ifdef MAC
3506 bad:
3507 #endif
3508 	CURVNET_RESTORE();
3509 	return (error);
3510 }
3511 
3512 int
3513 soopt_getm(struct sockopt *sopt, struct mbuf **mp)
3514 {
3515 	struct mbuf *m, *m_prev;
3516 	int sopt_size = sopt->sopt_valsize;
3517 
3518 	MGET(m, sopt->sopt_td ? M_WAITOK : M_NOWAIT, MT_DATA);
3519 	if (m == NULL)
3520 		return ENOBUFS;
3521 	if (sopt_size > MLEN) {
3522 		MCLGET(m, sopt->sopt_td ? M_WAITOK : M_NOWAIT);
3523 		if ((m->m_flags & M_EXT) == 0) {
3524 			m_free(m);
3525 			return ENOBUFS;
3526 		}
3527 		m->m_len = min(MCLBYTES, sopt_size);
3528 	} else {
3529 		m->m_len = min(MLEN, sopt_size);
3530 	}
3531 	sopt_size -= m->m_len;
3532 	*mp = m;
3533 	m_prev = m;
3534 
3535 	while (sopt_size) {
3536 		MGET(m, sopt->sopt_td ? M_WAITOK : M_NOWAIT, MT_DATA);
3537 		if (m == NULL) {
3538 			m_freem(*mp);
3539 			return ENOBUFS;
3540 		}
3541 		if (sopt_size > MLEN) {
3542 			MCLGET(m, sopt->sopt_td != NULL ? M_WAITOK :
3543 			    M_NOWAIT);
3544 			if ((m->m_flags & M_EXT) == 0) {
3545 				m_freem(m);
3546 				m_freem(*mp);
3547 				return ENOBUFS;
3548 			}
3549 			m->m_len = min(MCLBYTES, sopt_size);
3550 		} else {
3551 			m->m_len = min(MLEN, sopt_size);
3552 		}
3553 		sopt_size -= m->m_len;
3554 		m_prev->m_next = m;
3555 		m_prev = m;
3556 	}
3557 	return (0);
3558 }
3559 
3560 int
3561 soopt_mcopyin(struct sockopt *sopt, struct mbuf *m)
3562 {
3563 	struct mbuf *m0 = m;
3564 
3565 	if (sopt->sopt_val == NULL)
3566 		return (0);
3567 	while (m != NULL && sopt->sopt_valsize >= m->m_len) {
3568 		if (sopt->sopt_td != NULL) {
3569 			int error;
3570 
3571 			error = copyin(sopt->sopt_val, mtod(m, char *),
3572 			    m->m_len);
3573 			if (error != 0) {
3574 				m_freem(m0);
3575 				return(error);
3576 			}
3577 		} else
3578 			bcopy(sopt->sopt_val, mtod(m, char *), m->m_len);
3579 		sopt->sopt_valsize -= m->m_len;
3580 		sopt->sopt_val = (char *)sopt->sopt_val + m->m_len;
3581 		m = m->m_next;
3582 	}
3583 	if (m != NULL) /* should be allocated enoughly at ip6_sooptmcopyin() */
3584 		panic("ip6_sooptmcopyin");
3585 	return (0);
3586 }
3587 
3588 int
3589 soopt_mcopyout(struct sockopt *sopt, struct mbuf *m)
3590 {
3591 	struct mbuf *m0 = m;
3592 	size_t valsize = 0;
3593 
3594 	if (sopt->sopt_val == NULL)
3595 		return (0);
3596 	while (m != NULL && sopt->sopt_valsize >= m->m_len) {
3597 		if (sopt->sopt_td != NULL) {
3598 			int error;
3599 
3600 			error = copyout(mtod(m, char *), sopt->sopt_val,
3601 			    m->m_len);
3602 			if (error != 0) {
3603 				m_freem(m0);
3604 				return(error);
3605 			}
3606 		} else
3607 			bcopy(mtod(m, char *), sopt->sopt_val, m->m_len);
3608 		sopt->sopt_valsize -= m->m_len;
3609 		sopt->sopt_val = (char *)sopt->sopt_val + m->m_len;
3610 		valsize += m->m_len;
3611 		m = m->m_next;
3612 	}
3613 	if (m != NULL) {
3614 		/* enough soopt buffer should be given from user-land */
3615 		m_freem(m0);
3616 		return(EINVAL);
3617 	}
3618 	sopt->sopt_valsize = valsize;
3619 	return (0);
3620 }
3621 
3622 /*
3623  * sohasoutofband(): protocol notifies socket layer of the arrival of new
3624  * out-of-band data, which will then notify socket consumers.
3625  */
3626 void
3627 sohasoutofband(struct socket *so)
3628 {
3629 
3630 	if (so->so_sigio != NULL)
3631 		pgsigio(&so->so_sigio, SIGURG, 0);
3632 	selwakeuppri(&so->so_rdsel, PSOCK);
3633 }
3634 
3635 int
3636 sopoll(struct socket *so, int events, struct ucred *active_cred,
3637     struct thread *td)
3638 {
3639 
3640 	/*
3641 	 * We do not need to set or assert curvnet as long as everyone uses
3642 	 * sopoll_generic().
3643 	 */
3644 	return (so->so_proto->pr_sopoll(so, events, active_cred, td));
3645 }
3646 
3647 int
3648 sopoll_generic(struct socket *so, int events, struct ucred *active_cred,
3649     struct thread *td)
3650 {
3651 	int revents;
3652 
3653 	SOCK_LOCK(so);
3654 	if (SOLISTENING(so)) {
3655 		if (!(events & (POLLIN | POLLRDNORM)))
3656 			revents = 0;
3657 		else if (!TAILQ_EMPTY(&so->sol_comp))
3658 			revents = events & (POLLIN | POLLRDNORM);
3659 		else if ((events & POLLINIGNEOF) == 0 && so->so_error)
3660 			revents = (events & (POLLIN | POLLRDNORM)) | POLLHUP;
3661 		else {
3662 			selrecord(td, &so->so_rdsel);
3663 			revents = 0;
3664 		}
3665 	} else {
3666 		revents = 0;
3667 		SOCK_SENDBUF_LOCK(so);
3668 		SOCK_RECVBUF_LOCK(so);
3669 		if (events & (POLLIN | POLLRDNORM))
3670 			if (soreadabledata(so))
3671 				revents |= events & (POLLIN | POLLRDNORM);
3672 		if (events & (POLLOUT | POLLWRNORM))
3673 			if (sowriteable(so))
3674 				revents |= events & (POLLOUT | POLLWRNORM);
3675 		if (events & (POLLPRI | POLLRDBAND))
3676 			if (so->so_oobmark ||
3677 			    (so->so_rcv.sb_state & SBS_RCVATMARK))
3678 				revents |= events & (POLLPRI | POLLRDBAND);
3679 		if ((events & POLLINIGNEOF) == 0) {
3680 			if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
3681 				revents |= events & (POLLIN | POLLRDNORM);
3682 				if (so->so_snd.sb_state & SBS_CANTSENDMORE)
3683 					revents |= POLLHUP;
3684 			}
3685 		}
3686 		if (so->so_rcv.sb_state & SBS_CANTRCVMORE)
3687 			revents |= events & POLLRDHUP;
3688 		if (revents == 0) {
3689 			if (events &
3690 			    (POLLIN | POLLPRI | POLLRDNORM | POLLRDBAND | POLLRDHUP)) {
3691 				selrecord(td, &so->so_rdsel);
3692 				so->so_rcv.sb_flags |= SB_SEL;
3693 			}
3694 			if (events & (POLLOUT | POLLWRNORM)) {
3695 				selrecord(td, &so->so_wrsel);
3696 				so->so_snd.sb_flags |= SB_SEL;
3697 			}
3698 		}
3699 		SOCK_RECVBUF_UNLOCK(so);
3700 		SOCK_SENDBUF_UNLOCK(so);
3701 	}
3702 	SOCK_UNLOCK(so);
3703 	return (revents);
3704 }
3705 
3706 int
3707 soo_kqfilter(struct file *fp, struct knote *kn)
3708 {
3709 	struct socket *so = kn->kn_fp->f_data;
3710 	struct sockbuf *sb;
3711 	sb_which which;
3712 	struct knlist *knl;
3713 
3714 	switch (kn->kn_filter) {
3715 	case EVFILT_READ:
3716 		kn->kn_fop = &soread_filtops;
3717 		knl = &so->so_rdsel.si_note;
3718 		sb = &so->so_rcv;
3719 		which = SO_RCV;
3720 		break;
3721 	case EVFILT_WRITE:
3722 		kn->kn_fop = &sowrite_filtops;
3723 		knl = &so->so_wrsel.si_note;
3724 		sb = &so->so_snd;
3725 		which = SO_SND;
3726 		break;
3727 	case EVFILT_EMPTY:
3728 		kn->kn_fop = &soempty_filtops;
3729 		knl = &so->so_wrsel.si_note;
3730 		sb = &so->so_snd;
3731 		which = SO_SND;
3732 		break;
3733 	default:
3734 		return (EINVAL);
3735 	}
3736 
3737 	SOCK_LOCK(so);
3738 	if (SOLISTENING(so)) {
3739 		knlist_add(knl, kn, 1);
3740 	} else {
3741 		SOCK_BUF_LOCK(so, which);
3742 		knlist_add(knl, kn, 1);
3743 		sb->sb_flags |= SB_KNOTE;
3744 		SOCK_BUF_UNLOCK(so, which);
3745 	}
3746 	SOCK_UNLOCK(so);
3747 	return (0);
3748 }
3749 
3750 static void
3751 filt_sordetach(struct knote *kn)
3752 {
3753 	struct socket *so = kn->kn_fp->f_data;
3754 
3755 	so_rdknl_lock(so);
3756 	knlist_remove(&so->so_rdsel.si_note, kn, 1);
3757 	if (!SOLISTENING(so) && knlist_empty(&so->so_rdsel.si_note))
3758 		so->so_rcv.sb_flags &= ~SB_KNOTE;
3759 	so_rdknl_unlock(so);
3760 }
3761 
3762 /*ARGSUSED*/
3763 static int
3764 filt_soread(struct knote *kn, long hint)
3765 {
3766 	struct socket *so;
3767 
3768 	so = kn->kn_fp->f_data;
3769 
3770 	if (SOLISTENING(so)) {
3771 		SOCK_LOCK_ASSERT(so);
3772 		kn->kn_data = so->sol_qlen;
3773 		if (so->so_error) {
3774 			kn->kn_flags |= EV_EOF;
3775 			kn->kn_fflags = so->so_error;
3776 			return (1);
3777 		}
3778 		return (!TAILQ_EMPTY(&so->sol_comp));
3779 	}
3780 
3781 	SOCK_RECVBUF_LOCK_ASSERT(so);
3782 
3783 	kn->kn_data = sbavail(&so->so_rcv) - so->so_rcv.sb_ctl;
3784 	if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
3785 		kn->kn_flags |= EV_EOF;
3786 		kn->kn_fflags = so->so_error;
3787 		return (1);
3788 	} else if (so->so_error || so->so_rerror)
3789 		return (1);
3790 
3791 	if (kn->kn_sfflags & NOTE_LOWAT) {
3792 		if (kn->kn_data >= kn->kn_sdata)
3793 			return (1);
3794 	} else if (sbavail(&so->so_rcv) >= so->so_rcv.sb_lowat)
3795 		return (1);
3796 
3797 	/* This hook returning non-zero indicates an event, not error */
3798 	return (hhook_run_socket(so, NULL, HHOOK_FILT_SOREAD));
3799 }
3800 
3801 static void
3802 filt_sowdetach(struct knote *kn)
3803 {
3804 	struct socket *so = kn->kn_fp->f_data;
3805 
3806 	so_wrknl_lock(so);
3807 	knlist_remove(&so->so_wrsel.si_note, kn, 1);
3808 	if (!SOLISTENING(so) && knlist_empty(&so->so_wrsel.si_note))
3809 		so->so_snd.sb_flags &= ~SB_KNOTE;
3810 	so_wrknl_unlock(so);
3811 }
3812 
3813 /*ARGSUSED*/
3814 static int
3815 filt_sowrite(struct knote *kn, long hint)
3816 {
3817 	struct socket *so;
3818 
3819 	so = kn->kn_fp->f_data;
3820 
3821 	if (SOLISTENING(so))
3822 		return (0);
3823 
3824 	SOCK_SENDBUF_LOCK_ASSERT(so);
3825 	kn->kn_data = sbspace(&so->so_snd);
3826 
3827 	hhook_run_socket(so, kn, HHOOK_FILT_SOWRITE);
3828 
3829 	if (so->so_snd.sb_state & SBS_CANTSENDMORE) {
3830 		kn->kn_flags |= EV_EOF;
3831 		kn->kn_fflags = so->so_error;
3832 		return (1);
3833 	} else if (so->so_error)	/* temporary udp error */
3834 		return (1);
3835 	else if (((so->so_state & SS_ISCONNECTED) == 0) &&
3836 	    (so->so_proto->pr_flags & PR_CONNREQUIRED))
3837 		return (0);
3838 	else if (kn->kn_sfflags & NOTE_LOWAT)
3839 		return (kn->kn_data >= kn->kn_sdata);
3840 	else
3841 		return (kn->kn_data >= so->so_snd.sb_lowat);
3842 }
3843 
3844 static int
3845 filt_soempty(struct knote *kn, long hint)
3846 {
3847 	struct socket *so;
3848 
3849 	so = kn->kn_fp->f_data;
3850 
3851 	if (SOLISTENING(so))
3852 		return (1);
3853 
3854 	SOCK_SENDBUF_LOCK_ASSERT(so);
3855 	kn->kn_data = sbused(&so->so_snd);
3856 
3857 	if (kn->kn_data == 0)
3858 		return (1);
3859 	else
3860 		return (0);
3861 }
3862 
3863 int
3864 socheckuid(struct socket *so, uid_t uid)
3865 {
3866 
3867 	if (so == NULL)
3868 		return (EPERM);
3869 	if (so->so_cred->cr_uid != uid)
3870 		return (EPERM);
3871 	return (0);
3872 }
3873 
3874 /*
3875  * These functions are used by protocols to notify the socket layer (and its
3876  * consumers) of state changes in the sockets driven by protocol-side events.
3877  */
3878 
3879 /*
3880  * Procedures to manipulate state flags of socket and do appropriate wakeups.
3881  *
3882  * Normal sequence from the active (originating) side is that
3883  * soisconnecting() is called during processing of connect() call, resulting
3884  * in an eventual call to soisconnected() if/when the connection is
3885  * established.  When the connection is torn down soisdisconnecting() is
3886  * called during processing of disconnect() call, and soisdisconnected() is
3887  * called when the connection to the peer is totally severed.  The semantics
3888  * of these routines are such that connectionless protocols can call
3889  * soisconnected() and soisdisconnected() only, bypassing the in-progress
3890  * calls when setting up a ``connection'' takes no time.
3891  *
3892  * From the passive side, a socket is created with two queues of sockets:
3893  * so_incomp for connections in progress and so_comp for connections already
3894  * made and awaiting user acceptance.  As a protocol is preparing incoming
3895  * connections, it creates a socket structure queued on so_incomp by calling
3896  * sonewconn().  When the connection is established, soisconnected() is
3897  * called, and transfers the socket structure to so_comp, making it available
3898  * to accept().
3899  *
3900  * If a socket is closed with sockets on either so_incomp or so_comp, these
3901  * sockets are dropped.
3902  *
3903  * If higher-level protocols are implemented in the kernel, the wakeups done
3904  * here will sometimes cause software-interrupt process scheduling.
3905  */
3906 void
3907 soisconnecting(struct socket *so)
3908 {
3909 
3910 	SOCK_LOCK(so);
3911 	so->so_state &= ~(SS_ISCONNECTED|SS_ISDISCONNECTING);
3912 	so->so_state |= SS_ISCONNECTING;
3913 	SOCK_UNLOCK(so);
3914 }
3915 
3916 void
3917 soisconnected(struct socket *so)
3918 {
3919 	bool last __diagused;
3920 
3921 	SOCK_LOCK(so);
3922 	so->so_state &= ~(SS_ISCONNECTING|SS_ISDISCONNECTING|SS_ISCONFIRMING);
3923 	so->so_state |= SS_ISCONNECTED;
3924 
3925 	if (so->so_qstate == SQ_INCOMP) {
3926 		struct socket *head = so->so_listen;
3927 		int ret;
3928 
3929 		KASSERT(head, ("%s: so %p on incomp of NULL", __func__, so));
3930 		/*
3931 		 * Promoting a socket from incomplete queue to complete, we
3932 		 * need to go through reverse order of locking.  We first do
3933 		 * trylock, and if that doesn't succeed, we go the hard way
3934 		 * leaving a reference and rechecking consistency after proper
3935 		 * locking.
3936 		 */
3937 		if (__predict_false(SOLISTEN_TRYLOCK(head) == 0)) {
3938 			soref(head);
3939 			SOCK_UNLOCK(so);
3940 			SOLISTEN_LOCK(head);
3941 			SOCK_LOCK(so);
3942 			if (__predict_false(head != so->so_listen)) {
3943 				/*
3944 				 * The socket went off the listen queue,
3945 				 * should be lost race to close(2) of sol.
3946 				 * The socket is about to soabort().
3947 				 */
3948 				SOCK_UNLOCK(so);
3949 				sorele_locked(head);
3950 				return;
3951 			}
3952 			last = refcount_release(&head->so_count);
3953 			KASSERT(!last, ("%s: released last reference for %p",
3954 			    __func__, head));
3955 		}
3956 again:
3957 		if ((so->so_options & SO_ACCEPTFILTER) == 0) {
3958 			TAILQ_REMOVE(&head->sol_incomp, so, so_list);
3959 			head->sol_incqlen--;
3960 			TAILQ_INSERT_TAIL(&head->sol_comp, so, so_list);
3961 			head->sol_qlen++;
3962 			so->so_qstate = SQ_COMP;
3963 			SOCK_UNLOCK(so);
3964 			solisten_wakeup(head);	/* unlocks */
3965 		} else {
3966 			SOCK_RECVBUF_LOCK(so);
3967 			soupcall_set(so, SO_RCV,
3968 			    head->sol_accept_filter->accf_callback,
3969 			    head->sol_accept_filter_arg);
3970 			so->so_options &= ~SO_ACCEPTFILTER;
3971 			ret = head->sol_accept_filter->accf_callback(so,
3972 			    head->sol_accept_filter_arg, M_NOWAIT);
3973 			if (ret == SU_ISCONNECTED) {
3974 				soupcall_clear(so, SO_RCV);
3975 				SOCK_RECVBUF_UNLOCK(so);
3976 				goto again;
3977 			}
3978 			SOCK_RECVBUF_UNLOCK(so);
3979 			SOCK_UNLOCK(so);
3980 			SOLISTEN_UNLOCK(head);
3981 		}
3982 		return;
3983 	}
3984 	SOCK_UNLOCK(so);
3985 	wakeup(&so->so_timeo);
3986 	sorwakeup(so);
3987 	sowwakeup(so);
3988 }
3989 
3990 void
3991 soisdisconnecting(struct socket *so)
3992 {
3993 
3994 	SOCK_LOCK(so);
3995 	so->so_state &= ~SS_ISCONNECTING;
3996 	so->so_state |= SS_ISDISCONNECTING;
3997 
3998 	if (!SOLISTENING(so)) {
3999 		SOCK_RECVBUF_LOCK(so);
4000 		socantrcvmore_locked(so);
4001 		SOCK_SENDBUF_LOCK(so);
4002 		socantsendmore_locked(so);
4003 	}
4004 	SOCK_UNLOCK(so);
4005 	wakeup(&so->so_timeo);
4006 }
4007 
4008 void
4009 soisdisconnected(struct socket *so)
4010 {
4011 
4012 	SOCK_LOCK(so);
4013 
4014 	/*
4015 	 * There is at least one reader of so_state that does not
4016 	 * acquire socket lock, namely soreceive_generic().  Ensure
4017 	 * that it never sees all flags that track connection status
4018 	 * cleared, by ordering the update with a barrier semantic of
4019 	 * our release thread fence.
4020 	 */
4021 	so->so_state |= SS_ISDISCONNECTED;
4022 	atomic_thread_fence_rel();
4023 	so->so_state &= ~(SS_ISCONNECTING|SS_ISCONNECTED|SS_ISDISCONNECTING);
4024 
4025 	if (!SOLISTENING(so)) {
4026 		SOCK_UNLOCK(so);
4027 		SOCK_RECVBUF_LOCK(so);
4028 		socantrcvmore_locked(so);
4029 		SOCK_SENDBUF_LOCK(so);
4030 		sbdrop_locked(&so->so_snd, sbused(&so->so_snd));
4031 		socantsendmore_locked(so);
4032 	} else
4033 		SOCK_UNLOCK(so);
4034 	wakeup(&so->so_timeo);
4035 }
4036 
4037 int
4038 soiolock(struct socket *so, struct sx *sx, int flags)
4039 {
4040 	int error;
4041 
4042 	KASSERT((flags & SBL_VALID) == flags,
4043 	    ("soiolock: invalid flags %#x", flags));
4044 
4045 	if ((flags & SBL_WAIT) != 0) {
4046 		if ((flags & SBL_NOINTR) != 0) {
4047 			sx_xlock(sx);
4048 		} else {
4049 			error = sx_xlock_sig(sx);
4050 			if (error != 0)
4051 				return (error);
4052 		}
4053 	} else if (!sx_try_xlock(sx)) {
4054 		return (EWOULDBLOCK);
4055 	}
4056 
4057 	if (__predict_false(SOLISTENING(so))) {
4058 		sx_xunlock(sx);
4059 		return (ENOTCONN);
4060 	}
4061 	return (0);
4062 }
4063 
4064 void
4065 soiounlock(struct sx *sx)
4066 {
4067 	sx_xunlock(sx);
4068 }
4069 
4070 /*
4071  * Make a copy of a sockaddr in a malloced buffer of type M_SONAME.
4072  */
4073 struct sockaddr *
4074 sodupsockaddr(const struct sockaddr *sa, int mflags)
4075 {
4076 	struct sockaddr *sa2;
4077 
4078 	sa2 = malloc(sa->sa_len, M_SONAME, mflags);
4079 	if (sa2)
4080 		bcopy(sa, sa2, sa->sa_len);
4081 	return sa2;
4082 }
4083 
4084 /*
4085  * Register per-socket destructor.
4086  */
4087 void
4088 sodtor_set(struct socket *so, so_dtor_t *func)
4089 {
4090 
4091 	SOCK_LOCK_ASSERT(so);
4092 	so->so_dtor = func;
4093 }
4094 
4095 /*
4096  * Register per-socket buffer upcalls.
4097  */
4098 void
4099 soupcall_set(struct socket *so, sb_which which, so_upcall_t func, void *arg)
4100 {
4101 	struct sockbuf *sb;
4102 
4103 	KASSERT(!SOLISTENING(so), ("%s: so %p listening", __func__, so));
4104 
4105 	switch (which) {
4106 	case SO_RCV:
4107 		sb = &so->so_rcv;
4108 		break;
4109 	case SO_SND:
4110 		sb = &so->so_snd;
4111 		break;
4112 	}
4113 	SOCK_BUF_LOCK_ASSERT(so, which);
4114 	sb->sb_upcall = func;
4115 	sb->sb_upcallarg = arg;
4116 	sb->sb_flags |= SB_UPCALL;
4117 }
4118 
4119 void
4120 soupcall_clear(struct socket *so, sb_which which)
4121 {
4122 	struct sockbuf *sb;
4123 
4124 	KASSERT(!SOLISTENING(so), ("%s: so %p listening", __func__, so));
4125 
4126 	switch (which) {
4127 	case SO_RCV:
4128 		sb = &so->so_rcv;
4129 		break;
4130 	case SO_SND:
4131 		sb = &so->so_snd;
4132 		break;
4133 	}
4134 	SOCK_BUF_LOCK_ASSERT(so, which);
4135 	KASSERT(sb->sb_upcall != NULL,
4136 	    ("%s: so %p no upcall to clear", __func__, so));
4137 	sb->sb_upcall = NULL;
4138 	sb->sb_upcallarg = NULL;
4139 	sb->sb_flags &= ~SB_UPCALL;
4140 }
4141 
4142 void
4143 solisten_upcall_set(struct socket *so, so_upcall_t func, void *arg)
4144 {
4145 
4146 	SOLISTEN_LOCK_ASSERT(so);
4147 	so->sol_upcall = func;
4148 	so->sol_upcallarg = arg;
4149 }
4150 
4151 static void
4152 so_rdknl_lock(void *arg)
4153 {
4154 	struct socket *so = arg;
4155 
4156 retry:
4157 	if (SOLISTENING(so)) {
4158 		SOLISTEN_LOCK(so);
4159 	} else {
4160 		SOCK_RECVBUF_LOCK(so);
4161 		if (__predict_false(SOLISTENING(so))) {
4162 			SOCK_RECVBUF_UNLOCK(so);
4163 			goto retry;
4164 		}
4165 	}
4166 }
4167 
4168 static void
4169 so_rdknl_unlock(void *arg)
4170 {
4171 	struct socket *so = arg;
4172 
4173 	if (SOLISTENING(so))
4174 		SOLISTEN_UNLOCK(so);
4175 	else
4176 		SOCK_RECVBUF_UNLOCK(so);
4177 }
4178 
4179 static void
4180 so_rdknl_assert_lock(void *arg, int what)
4181 {
4182 	struct socket *so = arg;
4183 
4184 	if (what == LA_LOCKED) {
4185 		if (SOLISTENING(so))
4186 			SOLISTEN_LOCK_ASSERT(so);
4187 		else
4188 			SOCK_RECVBUF_LOCK_ASSERT(so);
4189 	} else {
4190 		if (SOLISTENING(so))
4191 			SOLISTEN_UNLOCK_ASSERT(so);
4192 		else
4193 			SOCK_RECVBUF_UNLOCK_ASSERT(so);
4194 	}
4195 }
4196 
4197 static void
4198 so_wrknl_lock(void *arg)
4199 {
4200 	struct socket *so = arg;
4201 
4202 retry:
4203 	if (SOLISTENING(so)) {
4204 		SOLISTEN_LOCK(so);
4205 	} else {
4206 		SOCK_SENDBUF_LOCK(so);
4207 		if (__predict_false(SOLISTENING(so))) {
4208 			SOCK_SENDBUF_UNLOCK(so);
4209 			goto retry;
4210 		}
4211 	}
4212 }
4213 
4214 static void
4215 so_wrknl_unlock(void *arg)
4216 {
4217 	struct socket *so = arg;
4218 
4219 	if (SOLISTENING(so))
4220 		SOLISTEN_UNLOCK(so);
4221 	else
4222 		SOCK_SENDBUF_UNLOCK(so);
4223 }
4224 
4225 static void
4226 so_wrknl_assert_lock(void *arg, int what)
4227 {
4228 	struct socket *so = arg;
4229 
4230 	if (what == LA_LOCKED) {
4231 		if (SOLISTENING(so))
4232 			SOLISTEN_LOCK_ASSERT(so);
4233 		else
4234 			SOCK_SENDBUF_LOCK_ASSERT(so);
4235 	} else {
4236 		if (SOLISTENING(so))
4237 			SOLISTEN_UNLOCK_ASSERT(so);
4238 		else
4239 			SOCK_SENDBUF_UNLOCK_ASSERT(so);
4240 	}
4241 }
4242 
4243 /*
4244  * Create an external-format (``xsocket'') structure using the information in
4245  * the kernel-format socket structure pointed to by so.  This is done to
4246  * reduce the spew of irrelevant information over this interface, to isolate
4247  * user code from changes in the kernel structure, and potentially to provide
4248  * information-hiding if we decide that some of this information should be
4249  * hidden from users.
4250  */
4251 void
4252 sotoxsocket(struct socket *so, struct xsocket *xso)
4253 {
4254 
4255 	bzero(xso, sizeof(*xso));
4256 	xso->xso_len = sizeof *xso;
4257 	xso->xso_so = (uintptr_t)so;
4258 	xso->so_type = so->so_type;
4259 	xso->so_options = so->so_options;
4260 	xso->so_linger = so->so_linger;
4261 	xso->so_state = so->so_state;
4262 	xso->so_pcb = (uintptr_t)so->so_pcb;
4263 	xso->xso_protocol = so->so_proto->pr_protocol;
4264 	xso->xso_family = so->so_proto->pr_domain->dom_family;
4265 	xso->so_timeo = so->so_timeo;
4266 	xso->so_error = so->so_error;
4267 	xso->so_uid = so->so_cred->cr_uid;
4268 	xso->so_pgid = so->so_sigio ? so->so_sigio->sio_pgid : 0;
4269 	if (SOLISTENING(so)) {
4270 		xso->so_qlen = so->sol_qlen;
4271 		xso->so_incqlen = so->sol_incqlen;
4272 		xso->so_qlimit = so->sol_qlimit;
4273 		xso->so_oobmark = 0;
4274 	} else {
4275 		xso->so_state |= so->so_qstate;
4276 		xso->so_qlen = xso->so_incqlen = xso->so_qlimit = 0;
4277 		xso->so_oobmark = so->so_oobmark;
4278 		sbtoxsockbuf(&so->so_snd, &xso->so_snd);
4279 		sbtoxsockbuf(&so->so_rcv, &xso->so_rcv);
4280 	}
4281 }
4282 
4283 struct sockbuf *
4284 so_sockbuf_rcv(struct socket *so)
4285 {
4286 
4287 	return (&so->so_rcv);
4288 }
4289 
4290 struct sockbuf *
4291 so_sockbuf_snd(struct socket *so)
4292 {
4293 
4294 	return (&so->so_snd);
4295 }
4296 
4297 int
4298 so_state_get(const struct socket *so)
4299 {
4300 
4301 	return (so->so_state);
4302 }
4303 
4304 void
4305 so_state_set(struct socket *so, int val)
4306 {
4307 
4308 	so->so_state = val;
4309 }
4310 
4311 int
4312 so_options_get(const struct socket *so)
4313 {
4314 
4315 	return (so->so_options);
4316 }
4317 
4318 void
4319 so_options_set(struct socket *so, int val)
4320 {
4321 
4322 	so->so_options = val;
4323 }
4324 
4325 int
4326 so_error_get(const struct socket *so)
4327 {
4328 
4329 	return (so->so_error);
4330 }
4331 
4332 void
4333 so_error_set(struct socket *so, int val)
4334 {
4335 
4336 	so->so_error = val;
4337 }
4338 
4339 int
4340 so_linger_get(const struct socket *so)
4341 {
4342 
4343 	return (so->so_linger);
4344 }
4345 
4346 void
4347 so_linger_set(struct socket *so, int val)
4348 {
4349 
4350 	KASSERT(val >= 0 && val <= USHRT_MAX && val <= (INT_MAX / hz),
4351 	    ("%s: val %d out of range", __func__, val));
4352 
4353 	so->so_linger = val;
4354 }
4355 
4356 struct protosw *
4357 so_protosw_get(const struct socket *so)
4358 {
4359 
4360 	return (so->so_proto);
4361 }
4362 
4363 void
4364 so_protosw_set(struct socket *so, struct protosw *val)
4365 {
4366 
4367 	so->so_proto = val;
4368 }
4369 
4370 void
4371 so_sorwakeup(struct socket *so)
4372 {
4373 
4374 	sorwakeup(so);
4375 }
4376 
4377 void
4378 so_sowwakeup(struct socket *so)
4379 {
4380 
4381 	sowwakeup(so);
4382 }
4383 
4384 void
4385 so_sorwakeup_locked(struct socket *so)
4386 {
4387 
4388 	sorwakeup_locked(so);
4389 }
4390 
4391 void
4392 so_sowwakeup_locked(struct socket *so)
4393 {
4394 
4395 	sowwakeup_locked(so);
4396 }
4397 
4398 void
4399 so_lock(struct socket *so)
4400 {
4401 
4402 	SOCK_LOCK(so);
4403 }
4404 
4405 void
4406 so_unlock(struct socket *so)
4407 {
4408 
4409 	SOCK_UNLOCK(so);
4410 }
4411