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