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