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