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