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