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