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