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