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