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