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