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