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