xref: /freebsd/sys/kern/uipc_socket.c (revision e4e9813eb92cd7c4d4b819a8fbed5cbd3d92f5d8)
1 /*-
2  * Copyright (c) 1982, 1986, 1988, 1990, 1993
3  *	The Regents of the University of California.  All rights reserved.
4  * Copyright (c) 2004 The FreeBSD Foundation
5  * Copyright (c) 2004-2006 Robert N. M. Watson
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 4. Neither the name of the University nor the names of its contributors
16  *    may be used to endorse or promote products derived from this software
17  *    without specific prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29  * SUCH DAMAGE.
30  *
31  *	@(#)uipc_socket.c	8.3 (Berkeley) 4/15/94
32  */
33 
34 /*
35  * Comments on the socket life cycle:
36  *
37  * soalloc() sets of socket layer state for a socket, called only by
38  * socreate() and sonewconn().  Socket layer private.
39  *
40  * sodealloc() tears down socket layer state for a socket, called only by
41  * sofree() and sonewconn().  Socket layer private.
42  *
43  * pru_attach() associates protocol layer state with an allocated socket;
44  * called only once, may fail, aborting socket allocation.  This is called
45  * from socreate() and sonewconn().  Socket layer private.
46  *
47  * pru_detach() disassociates protocol layer state from an attached socket,
48  * and will be called exactly once for sockets in which pru_attach() has
49  * been successfully called.  If pru_attach() returned an error,
50  * pru_detach() will not be called.  Socket layer private.
51  *
52  * pru_abort() and pru_close() notify the protocol layer that the last
53  * consumer of a socket is starting to tear down the socket, and that the
54  * protocol should terminate the connection.  Historically, pru_abort() also
55  * detached protocol state from the socket state, but this is no longer the
56  * case.
57  *
58  * socreate() creates a socket and attaches protocol state.  This is a public
59  * interface that may be used by socket layer consumers to create new
60  * sockets.
61  *
62  * sonewconn() creates a socket and attaches protocol state.  This is a
63  * public interface  that may be used by protocols to create new sockets when
64  * a new connection is received and will be available for accept() on a
65  * listen socket.
66  *
67  * soclose() destroys a socket after possibly waiting for it to disconnect.
68  * This is a public interface that socket consumers should use to close and
69  * release a socket when done with it.
70  *
71  * soabort() destroys a socket without waiting for it to disconnect (used
72  * only for incoming connections that are already partially or fully
73  * connected).  This is used internally by the socket layer when clearing
74  * listen socket queues (due to overflow or close on the listen socket), but
75  * is also a public interface protocols may use to abort connections in
76  * their incomplete listen queues should they no longer be required.  Sockets
77  * placed in completed connection listen queues should not be aborted for
78  * reasons described in the comment above the soclose() implementation.  This
79  * is not a general purpose close routine, and except in the specific
80  * circumstances described here, should not be used.
81  *
82  * sofree() will free a socket and its protocol state if all references on
83  * the socket have been released, and is the public interface to attempt to
84  * free a socket when a reference is removed.  This is a socket layer private
85  * interface.
86  *
87  * NOTE: In addition to socreate() and soclose(), which provide a single
88  * socket reference to the consumer to be managed as required, there are two
89  * calls to explicitly manage socket references, soref(), and sorele().
90  * Currently, these are generally required only when transitioning a socket
91  * from a listen queue to a file descriptor, in order to prevent garbage
92  * collection of the socket at an untimely moment.  For a number of reasons,
93  * these interfaces are not preferred, and should be avoided.
94  */
95 
96 #include <sys/cdefs.h>
97 __FBSDID("$FreeBSD$");
98 
99 #include "opt_inet.h"
100 #include "opt_mac.h"
101 #include "opt_zero.h"
102 #include "opt_compat.h"
103 
104 #include <sys/param.h>
105 #include <sys/systm.h>
106 #include <sys/fcntl.h>
107 #include <sys/limits.h>
108 #include <sys/lock.h>
109 #include <sys/mac.h>
110 #include <sys/malloc.h>
111 #include <sys/mbuf.h>
112 #include <sys/mutex.h>
113 #include <sys/domain.h>
114 #include <sys/file.h>			/* for struct knote */
115 #include <sys/kernel.h>
116 #include <sys/event.h>
117 #include <sys/eventhandler.h>
118 #include <sys/poll.h>
119 #include <sys/proc.h>
120 #include <sys/protosw.h>
121 #include <sys/socket.h>
122 #include <sys/socketvar.h>
123 #include <sys/resourcevar.h>
124 #include <sys/signalvar.h>
125 #include <sys/sysctl.h>
126 #include <sys/uio.h>
127 #include <sys/jail.h>
128 
129 #include <vm/uma.h>
130 
131 #ifdef COMPAT_IA32
132 #include <sys/mount.h>
133 #include <compat/freebsd32/freebsd32.h>
134 
135 extern struct sysentvec ia32_freebsd_sysvec;
136 #endif
137 
138 static int	soreceive_rcvoob(struct socket *so, struct uio *uio,
139 		    int flags);
140 
141 static void	filt_sordetach(struct knote *kn);
142 static int	filt_soread(struct knote *kn, long hint);
143 static void	filt_sowdetach(struct knote *kn);
144 static int	filt_sowrite(struct knote *kn, long hint);
145 static int	filt_solisten(struct knote *kn, long hint);
146 
147 static struct filterops solisten_filtops =
148 	{ 1, NULL, filt_sordetach, filt_solisten };
149 static struct filterops soread_filtops =
150 	{ 1, NULL, filt_sordetach, filt_soread };
151 static struct filterops sowrite_filtops =
152 	{ 1, NULL, filt_sowdetach, filt_sowrite };
153 
154 uma_zone_t socket_zone;
155 so_gen_t	so_gencnt;	/* generation count for sockets */
156 
157 int	maxsockets;
158 
159 MALLOC_DEFINE(M_SONAME, "soname", "socket name");
160 MALLOC_DEFINE(M_PCB, "pcb", "protocol control block");
161 
162 static int somaxconn = SOMAXCONN;
163 static int somaxconn_sysctl(SYSCTL_HANDLER_ARGS);
164 /* XXX: we dont have SYSCTL_USHORT */
165 SYSCTL_PROC(_kern_ipc, KIPC_SOMAXCONN, somaxconn, CTLTYPE_UINT | CTLFLAG_RW,
166     0, sizeof(int), somaxconn_sysctl, "I", "Maximum pending socket connection "
167     "queue size");
168 static int numopensockets;
169 SYSCTL_INT(_kern_ipc, OID_AUTO, numopensockets, CTLFLAG_RD,
170     &numopensockets, 0, "Number of open sockets");
171 #ifdef ZERO_COPY_SOCKETS
172 /* These aren't static because they're used in other files. */
173 int so_zero_copy_send = 1;
174 int so_zero_copy_receive = 1;
175 SYSCTL_NODE(_kern_ipc, OID_AUTO, zero_copy, CTLFLAG_RD, 0,
176     "Zero copy controls");
177 SYSCTL_INT(_kern_ipc_zero_copy, OID_AUTO, receive, CTLFLAG_RW,
178     &so_zero_copy_receive, 0, "Enable zero copy receive");
179 SYSCTL_INT(_kern_ipc_zero_copy, OID_AUTO, send, CTLFLAG_RW,
180     &so_zero_copy_send, 0, "Enable zero copy send");
181 #endif /* ZERO_COPY_SOCKETS */
182 
183 /*
184  * accept_mtx locks down per-socket fields relating to accept queues.  See
185  * socketvar.h for an annotation of the protected fields of struct socket.
186  */
187 struct mtx accept_mtx;
188 MTX_SYSINIT(accept_mtx, &accept_mtx, "accept", MTX_DEF);
189 
190 /*
191  * so_global_mtx protects so_gencnt, numopensockets, and the per-socket
192  * so_gencnt field.
193  */
194 static struct mtx so_global_mtx;
195 MTX_SYSINIT(so_global_mtx, &so_global_mtx, "so_glabel", MTX_DEF);
196 
197 /*
198  * General IPC sysctl name space, used by sockets and a variety of other IPC
199  * types.
200  */
201 SYSCTL_NODE(_kern, KERN_IPC, ipc, CTLFLAG_RW, 0, "IPC");
202 
203 /*
204  * Sysctl to get and set the maximum global sockets limit.  Notify protocols
205  * of the change so that they can update their dependent limits as required.
206  */
207 static int
208 sysctl_maxsockets(SYSCTL_HANDLER_ARGS)
209 {
210 	int error, newmaxsockets;
211 
212 	newmaxsockets = maxsockets;
213 	error = sysctl_handle_int(oidp, &newmaxsockets, sizeof(int), req);
214 	if (error == 0 && req->newptr) {
215 		if (newmaxsockets > maxsockets) {
216 			maxsockets = newmaxsockets;
217 			if (maxsockets > ((maxfiles / 4) * 3)) {
218 				maxfiles = (maxsockets * 5) / 4;
219 				maxfilesperproc = (maxfiles * 9) / 10;
220 			}
221 			EVENTHANDLER_INVOKE(maxsockets_change);
222 		} else
223 			error = EINVAL;
224 	}
225 	return (error);
226 }
227 
228 SYSCTL_PROC(_kern_ipc, OID_AUTO, maxsockets, CTLTYPE_INT|CTLFLAG_RW,
229     &maxsockets, 0, sysctl_maxsockets, "IU",
230     "Maximum number of sockets avaliable");
231 
232 /*
233  * Initialise maxsockets.
234  */
235 static void init_maxsockets(void *ignored)
236 {
237 	TUNABLE_INT_FETCH("kern.ipc.maxsockets", &maxsockets);
238 	maxsockets = imax(maxsockets, imax(maxfiles, nmbclusters));
239 }
240 SYSINIT(param, SI_SUB_TUNABLES, SI_ORDER_ANY, init_maxsockets, NULL);
241 
242 /*
243  * Socket operation routines.  These routines are called by the routines in
244  * sys_socket.c or from a system process, and implement the semantics of
245  * socket operations by switching out to the protocol specific routines.
246  */
247 
248 /*
249  * Get a socket structure from our zone, and initialize it.  Note that it
250  * would probably be better to allocate socket and PCB at the same time, but
251  * I'm not convinced that all the protocols can be easily modified to do
252  * this.
253  *
254  * soalloc() returns a socket with a ref count of 0.
255  */
256 static struct socket *
257 soalloc(int mflags)
258 {
259 	struct socket *so;
260 
261 	so = uma_zalloc(socket_zone, mflags | M_ZERO);
262 	if (so == NULL)
263 		return (NULL);
264 #ifdef MAC
265 	if (mac_init_socket(so, mflags) != 0) {
266 		uma_zfree(socket_zone, so);
267 		return (NULL);
268 	}
269 #endif
270 	SOCKBUF_LOCK_INIT(&so->so_snd, "so_snd");
271 	SOCKBUF_LOCK_INIT(&so->so_rcv, "so_rcv");
272 	TAILQ_INIT(&so->so_aiojobq);
273 	mtx_lock(&so_global_mtx);
274 	so->so_gencnt = ++so_gencnt;
275 	++numopensockets;
276 	mtx_unlock(&so_global_mtx);
277 	return (so);
278 }
279 
280 /*
281  * Free the storage associated with a socket at the socket layer, tear down
282  * locks, labels, etc.  All protocol state is assumed already to have been
283  * torn down (and possibly never set up) by the caller.
284  */
285 static void
286 sodealloc(struct socket *so)
287 {
288 
289 	KASSERT(so->so_count == 0, ("sodealloc(): so_count %d", so->so_count));
290 	KASSERT(so->so_pcb == NULL, ("sodealloc(): so_pcb != NULL"));
291 
292 	mtx_lock(&so_global_mtx);
293 	so->so_gencnt = ++so_gencnt;
294 	--numopensockets;	/* Could be below, but faster here. */
295 	mtx_unlock(&so_global_mtx);
296 	if (so->so_rcv.sb_hiwat)
297 		(void)chgsbsize(so->so_cred->cr_uidinfo,
298 		    &so->so_rcv.sb_hiwat, 0, RLIM_INFINITY);
299 	if (so->so_snd.sb_hiwat)
300 		(void)chgsbsize(so->so_cred->cr_uidinfo,
301 		    &so->so_snd.sb_hiwat, 0, RLIM_INFINITY);
302 #ifdef INET
303 	/* remove acccept filter if one is present. */
304 	if (so->so_accf != NULL)
305 		do_setopt_accept_filter(so, NULL);
306 #endif
307 #ifdef MAC
308 	mac_destroy_socket(so);
309 #endif
310 	crfree(so->so_cred);
311 	SOCKBUF_LOCK_DESTROY(&so->so_snd);
312 	SOCKBUF_LOCK_DESTROY(&so->so_rcv);
313 	uma_zfree(socket_zone, so);
314 }
315 
316 /*
317  * socreate returns a socket with a ref count of 1.  The socket should be
318  * closed with soclose().
319  */
320 int
321 socreate(dom, aso, type, proto, cred, td)
322 	int dom;
323 	struct socket **aso;
324 	int type;
325 	int proto;
326 	struct ucred *cred;
327 	struct thread *td;
328 {
329 	struct protosw *prp;
330 	struct socket *so;
331 	int error;
332 
333 	if (proto)
334 		prp = pffindproto(dom, proto, type);
335 	else
336 		prp = pffindtype(dom, type);
337 
338 	if (prp == NULL || prp->pr_usrreqs->pru_attach == NULL ||
339 	    prp->pr_usrreqs->pru_attach == pru_attach_notsupp)
340 		return (EPROTONOSUPPORT);
341 
342 	if (jailed(cred) && jail_socket_unixiproute_only &&
343 	    prp->pr_domain->dom_family != PF_LOCAL &&
344 	    prp->pr_domain->dom_family != PF_INET &&
345 	    prp->pr_domain->dom_family != PF_ROUTE) {
346 		return (EPROTONOSUPPORT);
347 	}
348 
349 	if (prp->pr_type != type)
350 		return (EPROTOTYPE);
351 	so = soalloc(M_WAITOK);
352 	if (so == NULL)
353 		return (ENOBUFS);
354 
355 	TAILQ_INIT(&so->so_incomp);
356 	TAILQ_INIT(&so->so_comp);
357 	so->so_type = type;
358 	so->so_cred = crhold(cred);
359 	so->so_proto = prp;
360 #ifdef MAC
361 	mac_create_socket(cred, so);
362 #endif
363 	knlist_init(&so->so_rcv.sb_sel.si_note, SOCKBUF_MTX(&so->so_rcv),
364 	    NULL, NULL, NULL);
365 	knlist_init(&so->so_snd.sb_sel.si_note, SOCKBUF_MTX(&so->so_snd),
366 	    NULL, NULL, NULL);
367 	so->so_count = 1;
368 	error = (*prp->pr_usrreqs->pru_attach)(so, proto, td);
369 	if (error) {
370 		sodealloc(so);
371 		return (error);
372 	}
373 	*aso = so;
374 	return (0);
375 }
376 
377 #ifdef REGRESSION
378 static int regression_sonewconn_earlytest = 1;
379 SYSCTL_INT(_regression, OID_AUTO, sonewconn_earlytest, CTLFLAG_RW,
380     &regression_sonewconn_earlytest, 0, "Perform early sonewconn limit test");
381 #endif
382 
383 /*
384  * When an attempt at a new connection is noted on a socket which accepts
385  * connections, sonewconn is called.  If the connection is possible (subject
386  * to space constraints, etc.) then we allocate a new structure, propoerly
387  * linked into the data structure of the original socket, and return this.
388  * Connstatus may be 0, or SO_ISCONFIRMING, or SO_ISCONNECTED.
389  *
390  * Note: the ref count on the socket is 0 on return.
391  */
392 struct socket *
393 sonewconn(head, connstatus)
394 	register struct socket *head;
395 	int connstatus;
396 {
397 	register struct socket *so;
398 	int over;
399 
400 	ACCEPT_LOCK();
401 	over = (head->so_qlen > 3 * head->so_qlimit / 2);
402 	ACCEPT_UNLOCK();
403 #ifdef REGRESSION
404 	if (regression_sonewconn_earlytest && over)
405 #else
406 	if (over)
407 #endif
408 		return (NULL);
409 	so = soalloc(M_NOWAIT);
410 	if (so == NULL)
411 		return (NULL);
412 	if ((head->so_options & SO_ACCEPTFILTER) != 0)
413 		connstatus = 0;
414 	so->so_head = head;
415 	so->so_type = head->so_type;
416 	so->so_options = head->so_options &~ SO_ACCEPTCONN;
417 	so->so_linger = head->so_linger;
418 	so->so_state = head->so_state | SS_NOFDREF;
419 	so->so_proto = head->so_proto;
420 	so->so_timeo = head->so_timeo;
421 	so->so_cred = crhold(head->so_cred);
422 #ifdef MAC
423 	SOCK_LOCK(head);
424 	mac_create_socket_from_socket(head, so);
425 	SOCK_UNLOCK(head);
426 #endif
427 	knlist_init(&so->so_rcv.sb_sel.si_note, SOCKBUF_MTX(&so->so_rcv),
428 	    NULL, NULL, NULL);
429 	knlist_init(&so->so_snd.sb_sel.si_note, SOCKBUF_MTX(&so->so_snd),
430 	    NULL, NULL, NULL);
431 	if (soreserve(so, head->so_snd.sb_hiwat, head->so_rcv.sb_hiwat) ||
432 	    (*so->so_proto->pr_usrreqs->pru_attach)(so, 0, NULL)) {
433 		sodealloc(so);
434 		return (NULL);
435 	}
436 	so->so_state |= connstatus;
437 	ACCEPT_LOCK();
438 	if (connstatus) {
439 		TAILQ_INSERT_TAIL(&head->so_comp, so, so_list);
440 		so->so_qstate |= SQ_COMP;
441 		head->so_qlen++;
442 	} else {
443 		/*
444 		 * Keep removing sockets from the head until there's room for
445 		 * us to insert on the tail.  In pre-locking revisions, this
446 		 * was a simple if(), but as we could be racing with other
447 		 * threads and soabort() requires dropping locks, we must
448 		 * loop waiting for the condition to be true.
449 		 */
450 		while (head->so_incqlen > head->so_qlimit) {
451 			struct socket *sp;
452 			sp = TAILQ_FIRST(&head->so_incomp);
453 			TAILQ_REMOVE(&head->so_incomp, sp, so_list);
454 			head->so_incqlen--;
455 			sp->so_qstate &= ~SQ_INCOMP;
456 			sp->so_head = NULL;
457 			ACCEPT_UNLOCK();
458 			soabort(sp);
459 			ACCEPT_LOCK();
460 		}
461 		TAILQ_INSERT_TAIL(&head->so_incomp, so, so_list);
462 		so->so_qstate |= SQ_INCOMP;
463 		head->so_incqlen++;
464 	}
465 	ACCEPT_UNLOCK();
466 	if (connstatus) {
467 		sorwakeup(head);
468 		wakeup_one(&head->so_timeo);
469 	}
470 	return (so);
471 }
472 
473 int
474 sobind(so, nam, td)
475 	struct socket *so;
476 	struct sockaddr *nam;
477 	struct thread *td;
478 {
479 
480 	return ((*so->so_proto->pr_usrreqs->pru_bind)(so, nam, td));
481 }
482 
483 /*
484  * solisten() transitions a socket from a non-listening state to a listening
485  * state, but can also be used to update the listen queue depth on an
486  * existing listen socket.  The protocol will call back into the sockets
487  * layer using solisten_proto_check() and solisten_proto() to check and set
488  * socket-layer listen state.  Call backs are used so that the protocol can
489  * acquire both protocol and socket layer locks in whatever order is required
490  * by the protocol.
491  *
492  * Protocol implementors are advised to hold the socket lock across the
493  * socket-layer test and set to avoid races at the socket layer.
494  */
495 int
496 solisten(so, backlog, td)
497 	struct socket *so;
498 	int backlog;
499 	struct thread *td;
500 {
501 
502 	return ((*so->so_proto->pr_usrreqs->pru_listen)(so, backlog, td));
503 }
504 
505 int
506 solisten_proto_check(so)
507 	struct socket *so;
508 {
509 
510 	SOCK_LOCK_ASSERT(so);
511 
512 	if (so->so_state & (SS_ISCONNECTED | SS_ISCONNECTING |
513 	    SS_ISDISCONNECTING))
514 		return (EINVAL);
515 	return (0);
516 }
517 
518 void
519 solisten_proto(so, backlog)
520 	struct socket *so;
521 	int backlog;
522 {
523 
524 	SOCK_LOCK_ASSERT(so);
525 
526 	if (backlog < 0 || backlog > somaxconn)
527 		backlog = somaxconn;
528 	so->so_qlimit = backlog;
529 	so->so_options |= SO_ACCEPTCONN;
530 }
531 
532 /*
533  * Attempt to free a socket.  This should really be sotryfree().
534  *
535  * sofree() will succeed if:
536  *
537  * - There are no outstanding file descriptor references or related consumers
538  *   (so_count == 0).
539  *
540  * - The socket has been closed by user space, if ever open (SS_NOFDREF).
541  *
542  * - The protocol does not have an outstanding strong reference on the socket
543  *   (SS_PROTOREF).
544  *
545  * - The socket is not in a completed connection queue, so a process has been
546  *   notified that it is present.  If it is removed, the user process may
547  *   block in accept() despite select() saying the socket was ready.
548  *
549  * Otherwise, it will quietly abort so that a future call to sofree(), when
550  * conditions are right, can succeed.
551  */
552 void
553 sofree(so)
554 	struct socket *so;
555 {
556 	struct protosw *pr = so->so_proto;
557 	struct socket *head;
558 
559 	ACCEPT_LOCK_ASSERT();
560 	SOCK_LOCK_ASSERT(so);
561 
562 	if ((so->so_state & SS_NOFDREF) == 0 || so->so_count != 0 ||
563 	    (so->so_state & SS_PROTOREF) || (so->so_qstate & SQ_COMP)) {
564 		SOCK_UNLOCK(so);
565 		ACCEPT_UNLOCK();
566 		return;
567 	}
568 
569 	head = so->so_head;
570 	if (head != NULL) {
571 		KASSERT((so->so_qstate & SQ_COMP) != 0 ||
572 		    (so->so_qstate & SQ_INCOMP) != 0,
573 		    ("sofree: so_head != NULL, but neither SQ_COMP nor "
574 		    "SQ_INCOMP"));
575 		KASSERT((so->so_qstate & SQ_COMP) == 0 ||
576 		    (so->so_qstate & SQ_INCOMP) == 0,
577 		    ("sofree: so->so_qstate is SQ_COMP and also SQ_INCOMP"));
578 		TAILQ_REMOVE(&head->so_incomp, so, so_list);
579 		head->so_incqlen--;
580 		so->so_qstate &= ~SQ_INCOMP;
581 		so->so_head = NULL;
582 	}
583 	KASSERT((so->so_qstate & SQ_COMP) == 0 &&
584 	    (so->so_qstate & SQ_INCOMP) == 0,
585 	    ("sofree: so_head == NULL, but still SQ_COMP(%d) or SQ_INCOMP(%d)",
586 	    so->so_qstate & SQ_COMP, so->so_qstate & SQ_INCOMP));
587 	SOCK_UNLOCK(so);
588 	ACCEPT_UNLOCK();
589 
590 	/*
591 	 * From this point on, we assume that no other references to this
592 	 * socket exist anywhere else in the stack.  Therefore, no locks need
593 	 * to be acquired or held.
594 	 *
595 	 * We used to do a lot of socket buffer and socket locking here, as
596 	 * well as invoke sorflush() and perform wakeups.  The direct call to
597 	 * dom_dispose() and sbrelease_internal() are an inlining of what was
598 	 * necessary from sorflush().
599 	 *
600 	 * Notice that the socket buffer and kqueue state are torn down
601 	 * before calling pru_detach.  This means that protocols shold not
602 	 * assume they can perform socket wakeups, etc, in their detach
603 	 * code.
604 	 */
605 	KASSERT((so->so_snd.sb_flags & SB_LOCK) == 0, ("sofree: snd sblock"));
606 	KASSERT((so->so_rcv.sb_flags & SB_LOCK) == 0, ("sofree: rcv sblock"));
607 	sbdestroy(&so->so_snd, so);
608 	if (pr->pr_flags & PR_RIGHTS && pr->pr_domain->dom_dispose != NULL)
609 		(*pr->pr_domain->dom_dispose)(so->so_rcv.sb_mb);
610 	sbdestroy(&so->so_rcv, so);
611 	if (pr->pr_usrreqs->pru_detach != NULL)
612 		(*pr->pr_usrreqs->pru_detach)(so);
613 	knlist_destroy(&so->so_rcv.sb_sel.si_note);
614 	knlist_destroy(&so->so_snd.sb_sel.si_note);
615 	sodealloc(so);
616 }
617 
618 /*
619  * Close a socket on last file table reference removal.  Initiate disconnect
620  * if connected.  Free socket when disconnect complete.
621  *
622  * This function will sorele() the socket.  Note that soclose() may be called
623  * prior to the ref count reaching zero.  The actual socket structure will
624  * not be freed until the ref count reaches zero.
625  */
626 int
627 soclose(so)
628 	struct socket *so;
629 {
630 	int error = 0;
631 
632 	KASSERT(!(so->so_state & SS_NOFDREF), ("soclose: SS_NOFDREF on enter"));
633 
634 	funsetown(&so->so_sigio);
635 	if (so->so_options & SO_ACCEPTCONN) {
636 		struct socket *sp;
637 		ACCEPT_LOCK();
638 		while ((sp = TAILQ_FIRST(&so->so_incomp)) != NULL) {
639 			TAILQ_REMOVE(&so->so_incomp, sp, so_list);
640 			so->so_incqlen--;
641 			sp->so_qstate &= ~SQ_INCOMP;
642 			sp->so_head = NULL;
643 			ACCEPT_UNLOCK();
644 			soabort(sp);
645 			ACCEPT_LOCK();
646 		}
647 		while ((sp = TAILQ_FIRST(&so->so_comp)) != NULL) {
648 			TAILQ_REMOVE(&so->so_comp, sp, so_list);
649 			so->so_qlen--;
650 			sp->so_qstate &= ~SQ_COMP;
651 			sp->so_head = NULL;
652 			ACCEPT_UNLOCK();
653 			soabort(sp);
654 			ACCEPT_LOCK();
655 		}
656 		ACCEPT_UNLOCK();
657 	}
658 	if (so->so_state & SS_ISCONNECTED) {
659 		if ((so->so_state & SS_ISDISCONNECTING) == 0) {
660 			error = sodisconnect(so);
661 			if (error)
662 				goto drop;
663 		}
664 		if (so->so_options & SO_LINGER) {
665 			if ((so->so_state & SS_ISDISCONNECTING) &&
666 			    (so->so_state & SS_NBIO))
667 				goto drop;
668 			while (so->so_state & SS_ISCONNECTED) {
669 				error = tsleep(&so->so_timeo,
670 				    PSOCK | PCATCH, "soclos", so->so_linger * hz);
671 				if (error)
672 					break;
673 			}
674 		}
675 	}
676 
677 drop:
678 	if (so->so_proto->pr_usrreqs->pru_close != NULL)
679 		(*so->so_proto->pr_usrreqs->pru_close)(so);
680 	ACCEPT_LOCK();
681 	SOCK_LOCK(so);
682 	KASSERT((so->so_state & SS_NOFDREF) == 0, ("soclose: NOFDREF"));
683 	so->so_state |= SS_NOFDREF;
684 	sorele(so);
685 	return (error);
686 }
687 
688 /*
689  * soabort() is used to abruptly tear down a connection, such as when a
690  * resource limit is reached (listen queue depth exceeded), or if a listen
691  * socket is closed while there are sockets waiting to be accepted.
692  *
693  * This interface is tricky, because it is called on an unreferenced socket,
694  * and must be called only by a thread that has actually removed the socket
695  * from the listen queue it was on, or races with other threads are risked.
696  *
697  * This interface will call into the protocol code, so must not be called
698  * with any socket locks held.  Protocols do call it while holding their own
699  * recursible protocol mutexes, but this is something that should be subject
700  * to review in the future.
701  */
702 void
703 soabort(so)
704 	struct socket *so;
705 {
706 
707 	/*
708 	 * In as much as is possible, assert that no references to this
709 	 * socket are held.  This is not quite the same as asserting that the
710 	 * current thread is responsible for arranging for no references, but
711 	 * is as close as we can get for now.
712 	 */
713 	KASSERT(so->so_count == 0, ("soabort: so_count"));
714 	KASSERT((so->so_state & SS_PROTOREF) == 0, ("soabort: SS_PROTOREF"));
715 	KASSERT(so->so_state & SS_NOFDREF, ("soabort: !SS_NOFDREF"));
716 	KASSERT((so->so_state & SQ_COMP) == 0, ("soabort: SQ_COMP"));
717 	KASSERT((so->so_state & SQ_INCOMP) == 0, ("soabort: SQ_INCOMP"));
718 
719 	if (so->so_proto->pr_usrreqs->pru_abort != NULL)
720 		(*so->so_proto->pr_usrreqs->pru_abort)(so);
721 	ACCEPT_LOCK();
722 	SOCK_LOCK(so);
723 	sofree(so);
724 }
725 
726 int
727 soaccept(so, nam)
728 	struct socket *so;
729 	struct sockaddr **nam;
730 {
731 	int error;
732 
733 	SOCK_LOCK(so);
734 	KASSERT((so->so_state & SS_NOFDREF) != 0, ("soaccept: !NOFDREF"));
735 	so->so_state &= ~SS_NOFDREF;
736 	SOCK_UNLOCK(so);
737 	error = (*so->so_proto->pr_usrreqs->pru_accept)(so, nam);
738 	return (error);
739 }
740 
741 int
742 soconnect(so, nam, td)
743 	struct socket *so;
744 	struct sockaddr *nam;
745 	struct thread *td;
746 {
747 	int error;
748 
749 	if (so->so_options & SO_ACCEPTCONN)
750 		return (EOPNOTSUPP);
751 	/*
752 	 * If protocol is connection-based, can only connect once.
753 	 * Otherwise, if connected, try to disconnect first.  This allows
754 	 * user to disconnect by connecting to, e.g., a null address.
755 	 */
756 	if (so->so_state & (SS_ISCONNECTED|SS_ISCONNECTING) &&
757 	    ((so->so_proto->pr_flags & PR_CONNREQUIRED) ||
758 	    (error = sodisconnect(so)))) {
759 		error = EISCONN;
760 	} else {
761 		/*
762 		 * Prevent accumulated error from previous connection from
763 		 * biting us.
764 		 */
765 		so->so_error = 0;
766 		error = (*so->so_proto->pr_usrreqs->pru_connect)(so, nam, td);
767 	}
768 
769 	return (error);
770 }
771 
772 int
773 soconnect2(so1, so2)
774 	struct socket *so1;
775 	struct socket *so2;
776 {
777 
778 	return ((*so1->so_proto->pr_usrreqs->pru_connect2)(so1, so2));
779 }
780 
781 int
782 sodisconnect(so)
783 	struct socket *so;
784 {
785 	int error;
786 
787 	if ((so->so_state & SS_ISCONNECTED) == 0)
788 		return (ENOTCONN);
789 	if (so->so_state & SS_ISDISCONNECTING)
790 		return (EALREADY);
791 	error = (*so->so_proto->pr_usrreqs->pru_disconnect)(so);
792 	return (error);
793 }
794 
795 #ifdef ZERO_COPY_SOCKETS
796 struct so_zerocopy_stats{
797 	int size_ok;
798 	int align_ok;
799 	int found_ifp;
800 };
801 struct so_zerocopy_stats so_zerocp_stats = {0,0,0};
802 #include <netinet/in.h>
803 #include <net/route.h>
804 #include <netinet/in_pcb.h>
805 #include <vm/vm.h>
806 #include <vm/vm_page.h>
807 #include <vm/vm_object.h>
808 #endif /*ZERO_COPY_SOCKETS*/
809 
810 /*
811  * sosend_copyin() accepts a uio and prepares an mbuf chain holding part or
812  * all of the data referenced by the uio.  If desired, it uses zero-copy.
813  * *space will be updated to reflect data copied in.
814  *
815  * NB: If atomic I/O is requested, the caller must already have checked that
816  * space can hold resid bytes.
817  *
818  * NB: In the event of an error, the caller may need to free the partial
819  * chain pointed to by *mpp.  The contents of both *uio and *space may be
820  * modified even in the case of an error.
821  */
822 static int
823 sosend_copyin(struct uio *uio, struct mbuf **retmp, int atomic, long *space,
824     int flags)
825 {
826 	struct mbuf *m, **mp, *top;
827 	long len, resid;
828 	int error;
829 #ifdef ZERO_COPY_SOCKETS
830 	int cow_send;
831 #endif
832 
833 	*retmp = top = NULL;
834 	mp = &top;
835 	len = 0;
836 	resid = uio->uio_resid;
837 	error = 0;
838 	do {
839 #ifdef ZERO_COPY_SOCKETS
840 		cow_send = 0;
841 #endif /* ZERO_COPY_SOCKETS */
842 		if (resid >= MINCLSIZE) {
843 #ifdef ZERO_COPY_SOCKETS
844 			if (top == NULL) {
845 				MGETHDR(m, M_TRYWAIT, MT_DATA);
846 				if (m == NULL) {
847 					error = ENOBUFS;
848 					goto out;
849 				}
850 				m->m_pkthdr.len = 0;
851 				m->m_pkthdr.rcvif = NULL;
852 			} else {
853 				MGET(m, M_TRYWAIT, MT_DATA);
854 				if (m == NULL) {
855 					error = ENOBUFS;
856 					goto out;
857 				}
858 			}
859 			if (so_zero_copy_send &&
860 			    resid>=PAGE_SIZE &&
861 			    *space>=PAGE_SIZE &&
862 			    uio->uio_iov->iov_len>=PAGE_SIZE) {
863 				so_zerocp_stats.size_ok++;
864 				so_zerocp_stats.align_ok++;
865 				cow_send = socow_setup(m, uio);
866 				len = cow_send;
867 			}
868 			if (!cow_send) {
869 				MCLGET(m, M_TRYWAIT);
870 				if ((m->m_flags & M_EXT) == 0) {
871 					m_free(m);
872 					m = NULL;
873 				} else {
874 					len = min(min(MCLBYTES, resid),
875 					    *space);
876 				}
877 			}
878 #else /* ZERO_COPY_SOCKETS */
879 			if (top == NULL) {
880 				m = m_getcl(M_TRYWAIT, MT_DATA, M_PKTHDR);
881 				m->m_pkthdr.len = 0;
882 				m->m_pkthdr.rcvif = NULL;
883 			} else
884 				m = m_getcl(M_TRYWAIT, 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_TRYWAIT, 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_TRYWAIT, 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 
935 #define	SBLOCKWAIT(f)	(((f) & MSG_DONTWAIT) ? M_NOWAIT : M_WAITOK)
936 
937 int
938 sosend_dgram(so, addr, uio, top, control, flags, td)
939 	struct socket *so;
940 	struct sockaddr *addr;
941 	struct uio *uio;
942 	struct mbuf *top;
943 	struct mbuf *control;
944 	int flags;
945 	struct thread *td;
946 {
947 	long space, resid;
948 	int clen = 0, error, dontroute;
949 	int atomic = sosendallatonce(so) || top;
950 
951 	KASSERT(so->so_type == SOCK_DGRAM, ("sodgram_send: !SOCK_DGRAM"));
952 	KASSERT(so->so_proto->pr_flags & PR_ATOMIC,
953 	    ("sodgram_send: !PR_ATOMIC"));
954 
955 	if (uio != NULL)
956 		resid = uio->uio_resid;
957 	else
958 		resid = top->m_pkthdr.len;
959 	/*
960 	 * In theory resid should be unsigned.  However, space must be
961 	 * signed, as it might be less than 0 if we over-committed, and we
962 	 * must use a signed comparison of space and resid.  On the other
963 	 * hand, a negative resid causes us to loop sending 0-length
964 	 * segments to the protocol.
965 	 *
966 	 * Also check to make sure that MSG_EOR isn't used on SOCK_STREAM
967 	 * type sockets since that's an error.
968 	 */
969 	if (resid < 0) {
970 		error = EINVAL;
971 		goto out;
972 	}
973 
974 	dontroute =
975 	    (flags & MSG_DONTROUTE) && (so->so_options & SO_DONTROUTE) == 0;
976 	if (td != NULL)
977 		td->td_proc->p_stats->p_ru.ru_msgsnd++;
978 	if (control != NULL)
979 		clen = control->m_len;
980 
981 	SOCKBUF_LOCK(&so->so_snd);
982 	if (so->so_snd.sb_state & SBS_CANTSENDMORE) {
983 		SOCKBUF_UNLOCK(&so->so_snd);
984 		error = EPIPE;
985 		goto out;
986 	}
987 	if (so->so_error) {
988 		error = so->so_error;
989 		so->so_error = 0;
990 		SOCKBUF_UNLOCK(&so->so_snd);
991 		goto out;
992 	}
993 	if ((so->so_state & SS_ISCONNECTED) == 0) {
994 		/*
995 		 * `sendto' and `sendmsg' is allowed on a connection-based
996 		 * socket if it supports implied connect.  Return ENOTCONN if
997 		 * not connected and no address is supplied.
998 		 */
999 		if ((so->so_proto->pr_flags & PR_CONNREQUIRED) &&
1000 		    (so->so_proto->pr_flags & PR_IMPLOPCL) == 0) {
1001 			if ((so->so_state & SS_ISCONFIRMING) == 0 &&
1002 			    !(resid == 0 && clen != 0)) {
1003 				SOCKBUF_UNLOCK(&so->so_snd);
1004 				error = ENOTCONN;
1005 				goto out;
1006 			}
1007 		} else if (addr == NULL) {
1008 			if (so->so_proto->pr_flags & PR_CONNREQUIRED)
1009 				error = ENOTCONN;
1010 			else
1011 				error = EDESTADDRREQ;
1012 			SOCKBUF_UNLOCK(&so->so_snd);
1013 			goto out;
1014 		}
1015 	}
1016 
1017 	/*
1018 	 * Do we need MSG_OOB support in SOCK_DGRAM?  Signs here may be a
1019 	 * problem and need fixing.
1020 	 */
1021 	space = sbspace(&so->so_snd);
1022 	if (flags & MSG_OOB)
1023 		space += 1024;
1024 	space -= clen;
1025 	if (resid > space) {
1026 		error = EMSGSIZE;
1027 		goto out;
1028 	}
1029 	SOCKBUF_UNLOCK(&so->so_snd);
1030 	if (uio == NULL) {
1031 		resid = 0;
1032 		if (flags & MSG_EOR)
1033 			top->m_flags |= M_EOR;
1034 	} else {
1035 		error = sosend_copyin(uio, &top, atomic, &space, flags);
1036 		if (error)
1037 			goto out;
1038 		resid = uio->uio_resid;
1039 	}
1040 	KASSERT(resid == 0, ("sosend_dgram: resid != 0"));
1041 	/*
1042 	 * XXXRW: Frobbing SO_DONTROUTE here is even worse without sblock
1043 	 * than with.
1044 	 */
1045 	if (dontroute) {
1046 		SOCK_LOCK(so);
1047 		so->so_options |= SO_DONTROUTE;
1048 		SOCK_UNLOCK(so);
1049 	}
1050 	/*
1051 	 * XXX all the SBS_CANTSENDMORE checks previously done could be out
1052 	 * of date.  We could have recieved a reset packet in an interrupt or
1053 	 * maybe we slept while doing page faults in uiomove() etc.  We could
1054 	 * probably recheck again inside the locking protection here, but
1055 	 * there are probably other places that this also happens.  We must
1056 	 * rethink this.
1057 	 */
1058 	error = (*so->so_proto->pr_usrreqs->pru_send)(so,
1059 	    (flags & MSG_OOB) ? PRUS_OOB :
1060 	/*
1061 	 * If the user set MSG_EOF, the protocol understands this flag and
1062 	 * nothing left to send then use PRU_SEND_EOF instead of PRU_SEND.
1063 	 */
1064 	    ((flags & MSG_EOF) &&
1065 	     (so->so_proto->pr_flags & PR_IMPLOPCL) &&
1066 	     (resid <= 0)) ?
1067 		PRUS_EOF :
1068 		/* If there is more to send set PRUS_MORETOCOME */
1069 		(resid > 0 && space > 0) ? PRUS_MORETOCOME : 0,
1070 		top, addr, control, td);
1071 	if (dontroute) {
1072 		SOCK_LOCK(so);
1073 		so->so_options &= ~SO_DONTROUTE;
1074 		SOCK_UNLOCK(so);
1075 	}
1076 	clen = 0;
1077 	control = NULL;
1078 	top = NULL;
1079 out:
1080 	if (top != NULL)
1081 		m_freem(top);
1082 	if (control != NULL)
1083 		m_freem(control);
1084 	return (error);
1085 }
1086 
1087 /*
1088  * Send on a socket.  If send must go all at once and message is larger than
1089  * send buffering, then hard error.  Lock against other senders.  If must go
1090  * all at once and not enough room now, then inform user that this would
1091  * block and do nothing.  Otherwise, if nonblocking, send as much as
1092  * possible.  The data to be sent is described by "uio" if nonzero, otherwise
1093  * by the mbuf chain "top" (which must be null if uio is not).  Data provided
1094  * in mbuf chain must be small enough to send all at once.
1095  *
1096  * Returns nonzero on error, timeout or signal; callers must check for short
1097  * counts if EINTR/ERESTART are returned.  Data and control buffers are freed
1098  * on return.
1099  */
1100 #define	snderr(errno)	{ error = (errno); goto release; }
1101 int
1102 sosend_generic(so, addr, uio, top, control, flags, td)
1103 	struct socket *so;
1104 	struct sockaddr *addr;
1105 	struct uio *uio;
1106 	struct mbuf *top;
1107 	struct mbuf *control;
1108 	int flags;
1109 	struct thread *td;
1110 {
1111 	long space, resid;
1112 	int clen = 0, error, dontroute;
1113 	int atomic = sosendallatonce(so) || top;
1114 
1115 	if (uio != NULL)
1116 		resid = uio->uio_resid;
1117 	else
1118 		resid = top->m_pkthdr.len;
1119 	/*
1120 	 * In theory resid should be unsigned.  However, space must be
1121 	 * signed, as it might be less than 0 if we over-committed, and we
1122 	 * must use a signed comparison of space and resid.  On the other
1123 	 * hand, a negative resid causes us to loop sending 0-length
1124 	 * segments to the protocol.
1125 	 *
1126 	 * Also check to make sure that MSG_EOR isn't used on SOCK_STREAM
1127 	 * type sockets since that's an error.
1128 	 */
1129 	if (resid < 0 || (so->so_type == SOCK_STREAM && (flags & MSG_EOR))) {
1130 		error = EINVAL;
1131 		goto out;
1132 	}
1133 
1134 	dontroute =
1135 	    (flags & MSG_DONTROUTE) && (so->so_options & SO_DONTROUTE) == 0 &&
1136 	    (so->so_proto->pr_flags & PR_ATOMIC);
1137 	if (td != NULL)
1138 		td->td_proc->p_stats->p_ru.ru_msgsnd++;
1139 	if (control != NULL)
1140 		clen = control->m_len;
1141 
1142 	SOCKBUF_LOCK(&so->so_snd);
1143 restart:
1144 	SOCKBUF_LOCK_ASSERT(&so->so_snd);
1145 	error = sblock(&so->so_snd, SBLOCKWAIT(flags));
1146 	if (error)
1147 		goto out_locked;
1148 	do {
1149 		SOCKBUF_LOCK_ASSERT(&so->so_snd);
1150 		if (so->so_snd.sb_state & SBS_CANTSENDMORE)
1151 			snderr(EPIPE);
1152 		if (so->so_error) {
1153 			error = so->so_error;
1154 			so->so_error = 0;
1155 			goto release;
1156 		}
1157 		if ((so->so_state & SS_ISCONNECTED) == 0) {
1158 			/*
1159 			 * `sendto' and `sendmsg' is allowed on a connection-
1160 			 * based socket if it supports implied connect.
1161 			 * Return ENOTCONN if not connected and no address is
1162 			 * supplied.
1163 			 */
1164 			if ((so->so_proto->pr_flags & PR_CONNREQUIRED) &&
1165 			    (so->so_proto->pr_flags & PR_IMPLOPCL) == 0) {
1166 				if ((so->so_state & SS_ISCONFIRMING) == 0 &&
1167 				    !(resid == 0 && clen != 0))
1168 					snderr(ENOTCONN);
1169 			} else if (addr == NULL)
1170 			    snderr(so->so_proto->pr_flags & PR_CONNREQUIRED ?
1171 				   ENOTCONN : EDESTADDRREQ);
1172 		}
1173 		space = sbspace(&so->so_snd);
1174 		if (flags & MSG_OOB)
1175 			space += 1024;
1176 		if ((atomic && resid > so->so_snd.sb_hiwat) ||
1177 		    clen > so->so_snd.sb_hiwat)
1178 			snderr(EMSGSIZE);
1179 		if (space < resid + clen &&
1180 		    (atomic || space < so->so_snd.sb_lowat || space < clen)) {
1181 			if ((so->so_state & SS_NBIO) || (flags & MSG_NBIO))
1182 				snderr(EWOULDBLOCK);
1183 			sbunlock(&so->so_snd);
1184 			error = sbwait(&so->so_snd);
1185 			if (error)
1186 				goto out_locked;
1187 			goto restart;
1188 		}
1189 		SOCKBUF_UNLOCK(&so->so_snd);
1190 		space -= clen;
1191 		do {
1192 			if (uio == NULL) {
1193 				resid = 0;
1194 				if (flags & MSG_EOR)
1195 					top->m_flags |= M_EOR;
1196 			} else {
1197 				error = sosend_copyin(uio, &top, atomic,
1198 				    &space, flags);
1199 				if (error != 0) {
1200 					SOCKBUF_LOCK(&so->so_snd);
1201 					goto release;
1202 				}
1203 				resid = uio->uio_resid;
1204 			}
1205 			if (dontroute) {
1206 				SOCK_LOCK(so);
1207 				so->so_options |= SO_DONTROUTE;
1208 				SOCK_UNLOCK(so);
1209 			}
1210 			/*
1211 			 * XXX all the SBS_CANTSENDMORE checks previously
1212 			 * done could be out of date.  We could have recieved
1213 			 * a reset packet in an interrupt or maybe we slept
1214 			 * while doing page faults in uiomove() etc.  We
1215 			 * could probably recheck again inside the locking
1216 			 * protection here, but there are probably other
1217 			 * places that this also happens.  We must rethink
1218 			 * this.
1219 			 */
1220 			error = (*so->so_proto->pr_usrreqs->pru_send)(so,
1221 			    (flags & MSG_OOB) ? PRUS_OOB :
1222 			/*
1223 			 * If the user set MSG_EOF, the protocol understands
1224 			 * this flag and nothing left to send then use
1225 			 * PRU_SEND_EOF instead of PRU_SEND.
1226 			 */
1227 			    ((flags & MSG_EOF) &&
1228 			     (so->so_proto->pr_flags & PR_IMPLOPCL) &&
1229 			     (resid <= 0)) ?
1230 				PRUS_EOF :
1231 			/* If there is more to send set PRUS_MORETOCOME. */
1232 			    (resid > 0 && space > 0) ? PRUS_MORETOCOME : 0,
1233 			    top, addr, control, td);
1234 			if (dontroute) {
1235 				SOCK_LOCK(so);
1236 				so->so_options &= ~SO_DONTROUTE;
1237 				SOCK_UNLOCK(so);
1238 			}
1239 			clen = 0;
1240 			control = NULL;
1241 			top = NULL;
1242 			if (error) {
1243 				SOCKBUF_LOCK(&so->so_snd);
1244 				goto release;
1245 			}
1246 		} while (resid && space > 0);
1247 		SOCKBUF_LOCK(&so->so_snd);
1248 	} while (resid);
1249 
1250 release:
1251 	SOCKBUF_LOCK_ASSERT(&so->so_snd);
1252 	sbunlock(&so->so_snd);
1253 out_locked:
1254 	SOCKBUF_LOCK_ASSERT(&so->so_snd);
1255 	SOCKBUF_UNLOCK(&so->so_snd);
1256 out:
1257 	if (top != NULL)
1258 		m_freem(top);
1259 	if (control != NULL)
1260 		m_freem(control);
1261 	return (error);
1262 }
1263 #undef snderr
1264 
1265 int
1266 sosend(so, addr, uio, top, control, flags, td)
1267 	struct socket *so;
1268 	struct sockaddr *addr;
1269 	struct uio *uio;
1270 	struct mbuf *top;
1271 	struct mbuf *control;
1272 	int flags;
1273 	struct thread *td;
1274 {
1275 
1276 	/* XXXRW: Temporary debugging. */
1277 	KASSERT(so->so_proto->pr_usrreqs->pru_sosend != sosend,
1278 	    ("sosend: protocol calls sosend"));
1279 
1280 	return (so->so_proto->pr_usrreqs->pru_sosend(so, addr, uio, top,
1281 	    control, flags, td));
1282 }
1283 
1284 /*
1285  * The part of soreceive() that implements reading non-inline out-of-band
1286  * data from a socket.  For more complete comments, see soreceive(), from
1287  * which this code originated.
1288  *
1289  * Note that soreceive_rcvoob(), unlike the remainder of soreceive(), is
1290  * unable to return an mbuf chain to the caller.
1291  */
1292 static int
1293 soreceive_rcvoob(so, uio, flags)
1294 	struct socket *so;
1295 	struct uio *uio;
1296 	int flags;
1297 {
1298 	struct protosw *pr = so->so_proto;
1299 	struct mbuf *m;
1300 	int error;
1301 
1302 	KASSERT(flags & MSG_OOB, ("soreceive_rcvoob: (flags & MSG_OOB) == 0"));
1303 
1304 	m = m_get(M_TRYWAIT, MT_DATA);
1305 	if (m == NULL)
1306 		return (ENOBUFS);
1307 	error = (*pr->pr_usrreqs->pru_rcvoob)(so, m, flags & MSG_PEEK);
1308 	if (error)
1309 		goto bad;
1310 	do {
1311 #ifdef ZERO_COPY_SOCKETS
1312 		if (so_zero_copy_receive) {
1313 			int disposable;
1314 
1315 			if ((m->m_flags & M_EXT)
1316 			 && (m->m_ext.ext_type == EXT_DISPOSABLE))
1317 				disposable = 1;
1318 			else
1319 				disposable = 0;
1320 
1321 			error = uiomoveco(mtod(m, void *),
1322 					  min(uio->uio_resid, m->m_len),
1323 					  uio, disposable);
1324 		} else
1325 #endif /* ZERO_COPY_SOCKETS */
1326 		error = uiomove(mtod(m, void *),
1327 		    (int) min(uio->uio_resid, m->m_len), uio);
1328 		m = m_free(m);
1329 	} while (uio->uio_resid && error == 0 && m);
1330 bad:
1331 	if (m != NULL)
1332 		m_freem(m);
1333 	return (error);
1334 }
1335 
1336 /*
1337  * Following replacement or removal of the first mbuf on the first mbuf chain
1338  * of a socket buffer, push necessary state changes back into the socket
1339  * buffer so that other consumers see the values consistently.  'nextrecord'
1340  * is the callers locally stored value of the original value of
1341  * sb->sb_mb->m_nextpkt which must be restored when the lead mbuf changes.
1342  * NOTE: 'nextrecord' may be NULL.
1343  */
1344 static __inline void
1345 sockbuf_pushsync(struct sockbuf *sb, struct mbuf *nextrecord)
1346 {
1347 
1348 	SOCKBUF_LOCK_ASSERT(sb);
1349 	/*
1350 	 * First, update for the new value of nextrecord.  If necessary, make
1351 	 * it the first record.
1352 	 */
1353 	if (sb->sb_mb != NULL)
1354 		sb->sb_mb->m_nextpkt = nextrecord;
1355 	else
1356 		sb->sb_mb = nextrecord;
1357 
1358         /*
1359          * Now update any dependent socket buffer fields to reflect the new
1360          * state.  This is an expanded inline of SB_EMPTY_FIXUP(), with the
1361 	 * addition of a second clause that takes care of the case where
1362 	 * sb_mb has been updated, but remains the last record.
1363          */
1364         if (sb->sb_mb == NULL) {
1365                 sb->sb_mbtail = NULL;
1366                 sb->sb_lastrecord = NULL;
1367         } else if (sb->sb_mb->m_nextpkt == NULL)
1368                 sb->sb_lastrecord = sb->sb_mb;
1369 }
1370 
1371 
1372 /*
1373  * Implement receive operations on a socket.  We depend on the way that
1374  * records are added to the sockbuf by sbappend.  In particular, each record
1375  * (mbufs linked through m_next) must begin with an address if the protocol
1376  * so specifies, followed by an optional mbuf or mbufs containing ancillary
1377  * data, and then zero or more mbufs of data.  In order to allow parallelism
1378  * between network receive and copying to user space, as well as avoid
1379  * sleeping with a mutex held, we release the socket buffer mutex during the
1380  * user space copy.  Although the sockbuf is locked, new data may still be
1381  * appended, and thus we must maintain consistency of the sockbuf during that
1382  * time.
1383  *
1384  * The caller may receive the data as a single mbuf chain by supplying an
1385  * mbuf **mp0 for use in returning the chain.  The uio is then used only for
1386  * the count in uio_resid.
1387  */
1388 int
1389 soreceive_generic(so, psa, uio, mp0, controlp, flagsp)
1390 	struct socket *so;
1391 	struct sockaddr **psa;
1392 	struct uio *uio;
1393 	struct mbuf **mp0;
1394 	struct mbuf **controlp;
1395 	int *flagsp;
1396 {
1397 	struct mbuf *m, **mp;
1398 	int flags, len, error, offset;
1399 	struct protosw *pr = so->so_proto;
1400 	struct mbuf *nextrecord;
1401 	int moff, type = 0;
1402 	int orig_resid = uio->uio_resid;
1403 
1404 	mp = mp0;
1405 	if (psa != NULL)
1406 		*psa = NULL;
1407 	if (controlp != NULL)
1408 		*controlp = NULL;
1409 	if (flagsp != NULL)
1410 		flags = *flagsp &~ MSG_EOR;
1411 	else
1412 		flags = 0;
1413 	if (flags & MSG_OOB)
1414 		return (soreceive_rcvoob(so, uio, flags));
1415 	if (mp != NULL)
1416 		*mp = NULL;
1417 	if ((pr->pr_flags & PR_WANTRCVD) && (so->so_state & SS_ISCONFIRMING)
1418 	    && uio->uio_resid)
1419 		(*pr->pr_usrreqs->pru_rcvd)(so, 0);
1420 
1421 	SOCKBUF_LOCK(&so->so_rcv);
1422 restart:
1423 	SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1424 	error = sblock(&so->so_rcv, SBLOCKWAIT(flags));
1425 	if (error)
1426 		goto out;
1427 
1428 	m = so->so_rcv.sb_mb;
1429 	/*
1430 	 * If we have less data than requested, block awaiting more (subject
1431 	 * to any timeout) if:
1432 	 *   1. the current count is less than the low water mark, or
1433 	 *   2. MSG_WAITALL is set, and it is possible to do the entire
1434 	 *	receive operation at once if we block (resid <= hiwat).
1435 	 *   3. MSG_DONTWAIT is not set
1436 	 * If MSG_WAITALL is set but resid is larger than the receive buffer,
1437 	 * we have to do the receive in sections, and thus risk returning a
1438 	 * short count if a timeout or signal occurs after we start.
1439 	 */
1440 	if (m == NULL || (((flags & MSG_DONTWAIT) == 0 &&
1441 	    so->so_rcv.sb_cc < uio->uio_resid) &&
1442 	    (so->so_rcv.sb_cc < so->so_rcv.sb_lowat ||
1443 	    ((flags & MSG_WAITALL) && uio->uio_resid <= so->so_rcv.sb_hiwat)) &&
1444 	    m->m_nextpkt == NULL && (pr->pr_flags & PR_ATOMIC) == 0)) {
1445 		KASSERT(m != NULL || !so->so_rcv.sb_cc,
1446 		    ("receive: m == %p so->so_rcv.sb_cc == %u",
1447 		    m, so->so_rcv.sb_cc));
1448 		if (so->so_error) {
1449 			if (m != NULL)
1450 				goto dontblock;
1451 			error = so->so_error;
1452 			if ((flags & MSG_PEEK) == 0)
1453 				so->so_error = 0;
1454 			goto release;
1455 		}
1456 		SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1457 		if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
1458 			if (m)
1459 				goto dontblock;
1460 			else
1461 				goto release;
1462 		}
1463 		for (; m != NULL; m = m->m_next)
1464 			if (m->m_type == MT_OOBDATA  || (m->m_flags & M_EOR)) {
1465 				m = so->so_rcv.sb_mb;
1466 				goto dontblock;
1467 			}
1468 		if ((so->so_state & (SS_ISCONNECTED|SS_ISCONNECTING)) == 0 &&
1469 		    (so->so_proto->pr_flags & PR_CONNREQUIRED)) {
1470 			error = ENOTCONN;
1471 			goto release;
1472 		}
1473 		if (uio->uio_resid == 0)
1474 			goto release;
1475 		if ((so->so_state & SS_NBIO) ||
1476 		    (flags & (MSG_DONTWAIT|MSG_NBIO))) {
1477 			error = EWOULDBLOCK;
1478 			goto release;
1479 		}
1480 		SBLASTRECORDCHK(&so->so_rcv);
1481 		SBLASTMBUFCHK(&so->so_rcv);
1482 		sbunlock(&so->so_rcv);
1483 		error = sbwait(&so->so_rcv);
1484 		if (error)
1485 			goto out;
1486 		goto restart;
1487 	}
1488 dontblock:
1489 	/*
1490 	 * From this point onward, we maintain 'nextrecord' as a cache of the
1491 	 * pointer to the next record in the socket buffer.  We must keep the
1492 	 * various socket buffer pointers and local stack versions of the
1493 	 * pointers in sync, pushing out modifications before dropping the
1494 	 * socket buffer mutex, and re-reading them when picking it up.
1495 	 *
1496 	 * Otherwise, we will race with the network stack appending new data
1497 	 * or records onto the socket buffer by using inconsistent/stale
1498 	 * versions of the field, possibly resulting in socket buffer
1499 	 * corruption.
1500 	 *
1501 	 * By holding the high-level sblock(), we prevent simultaneous
1502 	 * readers from pulling off the front of the socket buffer.
1503 	 */
1504 	SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1505 	if (uio->uio_td)
1506 		uio->uio_td->td_proc->p_stats->p_ru.ru_msgrcv++;
1507 	KASSERT(m == so->so_rcv.sb_mb, ("soreceive: m != so->so_rcv.sb_mb"));
1508 	SBLASTRECORDCHK(&so->so_rcv);
1509 	SBLASTMBUFCHK(&so->so_rcv);
1510 	nextrecord = m->m_nextpkt;
1511 	if (pr->pr_flags & PR_ADDR) {
1512 		KASSERT(m->m_type == MT_SONAME,
1513 		    ("m->m_type == %d", m->m_type));
1514 		orig_resid = 0;
1515 		if (psa != NULL)
1516 			*psa = sodupsockaddr(mtod(m, struct sockaddr *),
1517 			    M_NOWAIT);
1518 		if (flags & MSG_PEEK) {
1519 			m = m->m_next;
1520 		} else {
1521 			sbfree(&so->so_rcv, m);
1522 			so->so_rcv.sb_mb = m_free(m);
1523 			m = so->so_rcv.sb_mb;
1524 			sockbuf_pushsync(&so->so_rcv, nextrecord);
1525 		}
1526 	}
1527 
1528 	/*
1529 	 * Process one or more MT_CONTROL mbufs present before any data mbufs
1530 	 * in the first mbuf chain on the socket buffer.  If MSG_PEEK, we
1531 	 * just copy the data; if !MSG_PEEK, we call into the protocol to
1532 	 * perform externalization (or freeing if controlp == NULL).
1533 	 */
1534 	if (m != NULL && m->m_type == MT_CONTROL) {
1535 		struct mbuf *cm = NULL, *cmn;
1536 		struct mbuf **cme = &cm;
1537 
1538 		do {
1539 			if (flags & MSG_PEEK) {
1540 				if (controlp != NULL) {
1541 					*controlp = m_copy(m, 0, m->m_len);
1542 					controlp = &(*controlp)->m_next;
1543 				}
1544 				m = m->m_next;
1545 			} else {
1546 				sbfree(&so->so_rcv, m);
1547 				so->so_rcv.sb_mb = m->m_next;
1548 				m->m_next = NULL;
1549 				*cme = m;
1550 				cme = &(*cme)->m_next;
1551 				m = so->so_rcv.sb_mb;
1552 			}
1553 		} while (m != NULL && m->m_type == MT_CONTROL);
1554 		if ((flags & MSG_PEEK) == 0)
1555 			sockbuf_pushsync(&so->so_rcv, nextrecord);
1556 		while (cm != NULL) {
1557 			cmn = cm->m_next;
1558 			cm->m_next = NULL;
1559 			if (pr->pr_domain->dom_externalize != NULL) {
1560 				SOCKBUF_UNLOCK(&so->so_rcv);
1561 				error = (*pr->pr_domain->dom_externalize)
1562 				    (cm, controlp);
1563 				SOCKBUF_LOCK(&so->so_rcv);
1564 			} else if (controlp != NULL)
1565 				*controlp = cm;
1566 			else
1567 				m_freem(cm);
1568 			if (controlp != NULL) {
1569 				orig_resid = 0;
1570 				while (*controlp != NULL)
1571 					controlp = &(*controlp)->m_next;
1572 			}
1573 			cm = cmn;
1574 		}
1575 		if (so->so_rcv.sb_mb)
1576 			nextrecord = so->so_rcv.sb_mb->m_nextpkt;
1577 		else
1578 			nextrecord = NULL;
1579 		orig_resid = 0;
1580 	}
1581 	if (m != NULL) {
1582 		if ((flags & MSG_PEEK) == 0) {
1583 			KASSERT(m->m_nextpkt == nextrecord,
1584 			    ("soreceive: post-control, nextrecord !sync"));
1585 			if (nextrecord == NULL) {
1586 				KASSERT(so->so_rcv.sb_mb == m,
1587 				    ("soreceive: post-control, sb_mb!=m"));
1588 				KASSERT(so->so_rcv.sb_lastrecord == m,
1589 				    ("soreceive: post-control, lastrecord!=m"));
1590 			}
1591 		}
1592 		type = m->m_type;
1593 		if (type == MT_OOBDATA)
1594 			flags |= MSG_OOB;
1595 	} else {
1596 		if ((flags & MSG_PEEK) == 0) {
1597 			KASSERT(so->so_rcv.sb_mb == nextrecord,
1598 			    ("soreceive: sb_mb != nextrecord"));
1599 			if (so->so_rcv.sb_mb == NULL) {
1600 				KASSERT(so->so_rcv.sb_lastrecord == NULL,
1601 				    ("soreceive: sb_lastercord != NULL"));
1602 			}
1603 		}
1604 	}
1605 	SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1606 	SBLASTRECORDCHK(&so->so_rcv);
1607 	SBLASTMBUFCHK(&so->so_rcv);
1608 
1609 	/*
1610 	 * Now continue to read any data mbufs off of the head of the socket
1611 	 * buffer until the read request is satisfied.  Note that 'type' is
1612 	 * used to store the type of any mbuf reads that have happened so far
1613 	 * such that soreceive() can stop reading if the type changes, which
1614 	 * causes soreceive() to return only one of regular data and inline
1615 	 * out-of-band data in a single socket receive operation.
1616 	 */
1617 	moff = 0;
1618 	offset = 0;
1619 	while (m != NULL && uio->uio_resid > 0 && error == 0) {
1620 		/*
1621 		 * If the type of mbuf has changed since the last mbuf
1622 		 * examined ('type'), end the receive operation.
1623 	 	 */
1624 		SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1625 		if (m->m_type == MT_OOBDATA) {
1626 			if (type != MT_OOBDATA)
1627 				break;
1628 		} else if (type == MT_OOBDATA)
1629 			break;
1630 		else
1631 		    KASSERT(m->m_type == MT_DATA,
1632 			("m->m_type == %d", m->m_type));
1633 		so->so_rcv.sb_state &= ~SBS_RCVATMARK;
1634 		len = uio->uio_resid;
1635 		if (so->so_oobmark && len > so->so_oobmark - offset)
1636 			len = so->so_oobmark - offset;
1637 		if (len > m->m_len - moff)
1638 			len = m->m_len - moff;
1639 		/*
1640 		 * If mp is set, just pass back the mbufs.  Otherwise copy
1641 		 * them out via the uio, then free.  Sockbuf must be
1642 		 * consistent here (points to current mbuf, it points to next
1643 		 * record) when we drop priority; we must note any additions
1644 		 * to the sockbuf when we block interrupts again.
1645 		 */
1646 		if (mp == NULL) {
1647 			SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1648 			SBLASTRECORDCHK(&so->so_rcv);
1649 			SBLASTMBUFCHK(&so->so_rcv);
1650 			SOCKBUF_UNLOCK(&so->so_rcv);
1651 #ifdef ZERO_COPY_SOCKETS
1652 			if (so_zero_copy_receive) {
1653 				int disposable;
1654 
1655 				if ((m->m_flags & M_EXT)
1656 				 && (m->m_ext.ext_type == EXT_DISPOSABLE))
1657 					disposable = 1;
1658 				else
1659 					disposable = 0;
1660 
1661 				error = uiomoveco(mtod(m, char *) + moff,
1662 						  (int)len, uio,
1663 						  disposable);
1664 			} else
1665 #endif /* ZERO_COPY_SOCKETS */
1666 			error = uiomove(mtod(m, char *) + moff, (int)len, uio);
1667 			SOCKBUF_LOCK(&so->so_rcv);
1668 			if (error)
1669 				goto release;
1670 		} else
1671 			uio->uio_resid -= len;
1672 		SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1673 		if (len == m->m_len - moff) {
1674 			if (m->m_flags & M_EOR)
1675 				flags |= MSG_EOR;
1676 			if (flags & MSG_PEEK) {
1677 				m = m->m_next;
1678 				moff = 0;
1679 			} else {
1680 				nextrecord = m->m_nextpkt;
1681 				sbfree(&so->so_rcv, m);
1682 				if (mp != NULL) {
1683 					*mp = m;
1684 					mp = &m->m_next;
1685 					so->so_rcv.sb_mb = m = m->m_next;
1686 					*mp = NULL;
1687 				} else {
1688 					so->so_rcv.sb_mb = m_free(m);
1689 					m = so->so_rcv.sb_mb;
1690 				}
1691 				sockbuf_pushsync(&so->so_rcv, nextrecord);
1692 				SBLASTRECORDCHK(&so->so_rcv);
1693 				SBLASTMBUFCHK(&so->so_rcv);
1694 			}
1695 		} else {
1696 			if (flags & MSG_PEEK)
1697 				moff += len;
1698 			else {
1699 				if (mp != NULL) {
1700 					int copy_flag;
1701 
1702 					if (flags & MSG_DONTWAIT)
1703 						copy_flag = M_DONTWAIT;
1704 					else
1705 						copy_flag = M_TRYWAIT;
1706 					if (copy_flag == M_TRYWAIT)
1707 						SOCKBUF_UNLOCK(&so->so_rcv);
1708 					*mp = m_copym(m, 0, len, copy_flag);
1709 					if (copy_flag == M_TRYWAIT)
1710 						SOCKBUF_LOCK(&so->so_rcv);
1711  					if (*mp == NULL) {
1712  						/*
1713  						 * m_copym() couldn't
1714 						 * allocate an mbuf.  Adjust
1715 						 * uio_resid back (it was
1716 						 * adjusted down by len
1717 						 * bytes, which we didn't end
1718 						 * up "copying" over).
1719  						 */
1720  						uio->uio_resid += len;
1721  						break;
1722  					}
1723 				}
1724 				m->m_data += len;
1725 				m->m_len -= len;
1726 				so->so_rcv.sb_cc -= len;
1727 			}
1728 		}
1729 		SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1730 		if (so->so_oobmark) {
1731 			if ((flags & MSG_PEEK) == 0) {
1732 				so->so_oobmark -= len;
1733 				if (so->so_oobmark == 0) {
1734 					so->so_rcv.sb_state |= SBS_RCVATMARK;
1735 					break;
1736 				}
1737 			} else {
1738 				offset += len;
1739 				if (offset == so->so_oobmark)
1740 					break;
1741 			}
1742 		}
1743 		if (flags & MSG_EOR)
1744 			break;
1745 		/*
1746 		 * If the MSG_WAITALL flag is set (for non-atomic socket), we
1747 		 * must not quit until "uio->uio_resid == 0" or an error
1748 		 * termination.  If a signal/timeout occurs, return with a
1749 		 * short count but without error.  Keep sockbuf locked
1750 		 * against other readers.
1751 		 */
1752 		while (flags & MSG_WAITALL && m == NULL && uio->uio_resid > 0 &&
1753 		    !sosendallatonce(so) && nextrecord == NULL) {
1754 			SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1755 			if (so->so_error || so->so_rcv.sb_state & SBS_CANTRCVMORE)
1756 				break;
1757 			/*
1758 			 * Notify the protocol that some data has been
1759 			 * drained before blocking.
1760 			 */
1761 			if (pr->pr_flags & PR_WANTRCVD) {
1762 				SOCKBUF_UNLOCK(&so->so_rcv);
1763 				(*pr->pr_usrreqs->pru_rcvd)(so, flags);
1764 				SOCKBUF_LOCK(&so->so_rcv);
1765 			}
1766 			SBLASTRECORDCHK(&so->so_rcv);
1767 			SBLASTMBUFCHK(&so->so_rcv);
1768 			error = sbwait(&so->so_rcv);
1769 			if (error)
1770 				goto release;
1771 			m = so->so_rcv.sb_mb;
1772 			if (m != NULL)
1773 				nextrecord = m->m_nextpkt;
1774 		}
1775 	}
1776 
1777 	SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1778 	if (m != NULL && pr->pr_flags & PR_ATOMIC) {
1779 		flags |= MSG_TRUNC;
1780 		if ((flags & MSG_PEEK) == 0)
1781 			(void) sbdroprecord_locked(&so->so_rcv);
1782 	}
1783 	if ((flags & MSG_PEEK) == 0) {
1784 		if (m == NULL) {
1785 			/*
1786 			 * First part is an inline SB_EMPTY_FIXUP().  Second
1787 			 * part makes sure sb_lastrecord is up-to-date if
1788 			 * there is still data in the socket buffer.
1789 			 */
1790 			so->so_rcv.sb_mb = nextrecord;
1791 			if (so->so_rcv.sb_mb == NULL) {
1792 				so->so_rcv.sb_mbtail = NULL;
1793 				so->so_rcv.sb_lastrecord = NULL;
1794 			} else if (nextrecord->m_nextpkt == NULL)
1795 				so->so_rcv.sb_lastrecord = nextrecord;
1796 		}
1797 		SBLASTRECORDCHK(&so->so_rcv);
1798 		SBLASTMBUFCHK(&so->so_rcv);
1799 		/*
1800 		 * If soreceive() is being done from the socket callback,
1801 		 * then don't need to generate ACK to peer to update window,
1802 		 * since ACK will be generated on return to TCP.
1803 		 */
1804 		if (!(flags & MSG_SOCALLBCK) &&
1805 		    (pr->pr_flags & PR_WANTRCVD)) {
1806 			SOCKBUF_UNLOCK(&so->so_rcv);
1807 			(*pr->pr_usrreqs->pru_rcvd)(so, flags);
1808 			SOCKBUF_LOCK(&so->so_rcv);
1809 		}
1810 	}
1811 	SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1812 	if (orig_resid == uio->uio_resid && orig_resid &&
1813 	    (flags & MSG_EOR) == 0 && (so->so_rcv.sb_state & SBS_CANTRCVMORE) == 0) {
1814 		sbunlock(&so->so_rcv);
1815 		goto restart;
1816 	}
1817 
1818 	if (flagsp != NULL)
1819 		*flagsp |= flags;
1820 release:
1821 	SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1822 	sbunlock(&so->so_rcv);
1823 out:
1824 	SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1825 	SOCKBUF_UNLOCK(&so->so_rcv);
1826 	return (error);
1827 }
1828 
1829 int
1830 soreceive(so, psa, uio, mp0, controlp, flagsp)
1831 	struct socket *so;
1832 	struct sockaddr **psa;
1833 	struct uio *uio;
1834 	struct mbuf **mp0;
1835 	struct mbuf **controlp;
1836 	int *flagsp;
1837 {
1838 
1839 	/* XXXRW: Temporary debugging. */
1840 	KASSERT(so->so_proto->pr_usrreqs->pru_soreceive != soreceive,
1841 	    ("soreceive: protocol calls soreceive"));
1842 
1843 	return (so->so_proto->pr_usrreqs->pru_soreceive(so, psa, uio, mp0,
1844 	    controlp, flagsp));
1845 }
1846 
1847 int
1848 soshutdown(so, how)
1849 	struct socket *so;
1850 	int how;
1851 {
1852 	struct protosw *pr = so->so_proto;
1853 
1854 	if (!(how == SHUT_RD || how == SHUT_WR || how == SHUT_RDWR))
1855 		return (EINVAL);
1856 
1857 	if (how != SHUT_WR)
1858 		sorflush(so);
1859 	if (how != SHUT_RD)
1860 		return ((*pr->pr_usrreqs->pru_shutdown)(so));
1861 	return (0);
1862 }
1863 
1864 void
1865 sorflush(so)
1866 	struct socket *so;
1867 {
1868 	struct sockbuf *sb = &so->so_rcv;
1869 	struct protosw *pr = so->so_proto;
1870 	struct sockbuf asb;
1871 
1872 	/*
1873 	 * XXXRW: This is quite ugly.  Previously, this code made a copy of
1874 	 * the socket buffer, then zero'd the original to clear the buffer
1875 	 * fields.  However, with mutexes in the socket buffer, this causes
1876 	 * problems.  We only clear the zeroable bits of the original;
1877 	 * however, we have to initialize and destroy the mutex in the copy
1878 	 * so that dom_dispose() and sbrelease() can lock t as needed.
1879 	 */
1880 	SOCKBUF_LOCK(sb);
1881 	sb->sb_flags |= SB_NOINTR;
1882 	(void) sblock(sb, M_WAITOK);
1883 	/*
1884 	 * socantrcvmore_locked() drops the socket buffer mutex so that it
1885 	 * can safely perform wakeups.  Re-acquire the mutex before
1886 	 * continuing.
1887 	 */
1888 	socantrcvmore_locked(so);
1889 	SOCKBUF_LOCK(sb);
1890 	sbunlock(sb);
1891 	/*
1892 	 * Invalidate/clear most of the sockbuf structure, but leave selinfo
1893 	 * and mutex data unchanged.
1894 	 */
1895 	bzero(&asb, offsetof(struct sockbuf, sb_startzero));
1896 	bcopy(&sb->sb_startzero, &asb.sb_startzero,
1897 	    sizeof(*sb) - offsetof(struct sockbuf, sb_startzero));
1898 	bzero(&sb->sb_startzero,
1899 	    sizeof(*sb) - offsetof(struct sockbuf, sb_startzero));
1900 	SOCKBUF_UNLOCK(sb);
1901 
1902 	SOCKBUF_LOCK_INIT(&asb, "so_rcv");
1903 	if (pr->pr_flags & PR_RIGHTS && pr->pr_domain->dom_dispose != NULL)
1904 		(*pr->pr_domain->dom_dispose)(asb.sb_mb);
1905 	sbrelease(&asb, so);
1906 	SOCKBUF_LOCK_DESTROY(&asb);
1907 }
1908 
1909 /*
1910  * Perhaps this routine, and sooptcopyout(), below, ought to come in an
1911  * additional variant to handle the case where the option value needs to be
1912  * some kind of integer, but not a specific size.  In addition to their use
1913  * here, these functions are also called by the protocol-level pr_ctloutput()
1914  * routines.
1915  */
1916 int
1917 sooptcopyin(sopt, buf, len, minlen)
1918 	struct	sockopt *sopt;
1919 	void	*buf;
1920 	size_t	len;
1921 	size_t	minlen;
1922 {
1923 	size_t	valsize;
1924 
1925 	/*
1926 	 * If the user gives us more than we wanted, we ignore it, but if we
1927 	 * don't get the minimum length the caller wants, we return EINVAL.
1928 	 * On success, sopt->sopt_valsize is set to however much we actually
1929 	 * retrieved.
1930 	 */
1931 	if ((valsize = sopt->sopt_valsize) < minlen)
1932 		return EINVAL;
1933 	if (valsize > len)
1934 		sopt->sopt_valsize = valsize = len;
1935 
1936 	if (sopt->sopt_td != NULL)
1937 		return (copyin(sopt->sopt_val, buf, valsize));
1938 
1939 	bcopy(sopt->sopt_val, buf, valsize);
1940 	return (0);
1941 }
1942 
1943 /*
1944  * Kernel version of setsockopt(2).
1945  *
1946  * XXX: optlen is size_t, not socklen_t
1947  */
1948 int
1949 so_setsockopt(struct socket *so, int level, int optname, void *optval,
1950     size_t optlen)
1951 {
1952 	struct sockopt sopt;
1953 
1954 	sopt.sopt_level = level;
1955 	sopt.sopt_name = optname;
1956 	sopt.sopt_dir = SOPT_SET;
1957 	sopt.sopt_val = optval;
1958 	sopt.sopt_valsize = optlen;
1959 	sopt.sopt_td = NULL;
1960 	return (sosetopt(so, &sopt));
1961 }
1962 
1963 int
1964 sosetopt(so, sopt)
1965 	struct socket *so;
1966 	struct sockopt *sopt;
1967 {
1968 	int	error, optval;
1969 	struct	linger l;
1970 	struct	timeval tv;
1971 	u_long  val;
1972 #ifdef MAC
1973 	struct mac extmac;
1974 #endif
1975 
1976 	error = 0;
1977 	if (sopt->sopt_level != SOL_SOCKET) {
1978 		if (so->so_proto && so->so_proto->pr_ctloutput)
1979 			return ((*so->so_proto->pr_ctloutput)
1980 				  (so, sopt));
1981 		error = ENOPROTOOPT;
1982 	} else {
1983 		switch (sopt->sopt_name) {
1984 #ifdef INET
1985 		case SO_ACCEPTFILTER:
1986 			error = do_setopt_accept_filter(so, sopt);
1987 			if (error)
1988 				goto bad;
1989 			break;
1990 #endif
1991 		case SO_LINGER:
1992 			error = sooptcopyin(sopt, &l, sizeof l, sizeof l);
1993 			if (error)
1994 				goto bad;
1995 
1996 			SOCK_LOCK(so);
1997 			so->so_linger = l.l_linger;
1998 			if (l.l_onoff)
1999 				so->so_options |= SO_LINGER;
2000 			else
2001 				so->so_options &= ~SO_LINGER;
2002 			SOCK_UNLOCK(so);
2003 			break;
2004 
2005 		case SO_DEBUG:
2006 		case SO_KEEPALIVE:
2007 		case SO_DONTROUTE:
2008 		case SO_USELOOPBACK:
2009 		case SO_BROADCAST:
2010 		case SO_REUSEADDR:
2011 		case SO_REUSEPORT:
2012 		case SO_OOBINLINE:
2013 		case SO_TIMESTAMP:
2014 		case SO_BINTIME:
2015 		case SO_NOSIGPIPE:
2016 			error = sooptcopyin(sopt, &optval, sizeof optval,
2017 					    sizeof optval);
2018 			if (error)
2019 				goto bad;
2020 			SOCK_LOCK(so);
2021 			if (optval)
2022 				so->so_options |= sopt->sopt_name;
2023 			else
2024 				so->so_options &= ~sopt->sopt_name;
2025 			SOCK_UNLOCK(so);
2026 			break;
2027 
2028 		case SO_SNDBUF:
2029 		case SO_RCVBUF:
2030 		case SO_SNDLOWAT:
2031 		case SO_RCVLOWAT:
2032 			error = sooptcopyin(sopt, &optval, sizeof optval,
2033 					    sizeof optval);
2034 			if (error)
2035 				goto bad;
2036 
2037 			/*
2038 			 * Values < 1 make no sense for any of these options,
2039 			 * so disallow them.
2040 			 */
2041 			if (optval < 1) {
2042 				error = EINVAL;
2043 				goto bad;
2044 			}
2045 
2046 			switch (sopt->sopt_name) {
2047 			case SO_SNDBUF:
2048 			case SO_RCVBUF:
2049 				if (sbreserve(sopt->sopt_name == SO_SNDBUF ?
2050 				    &so->so_snd : &so->so_rcv, (u_long)optval,
2051 				    so, curthread) == 0) {
2052 					error = ENOBUFS;
2053 					goto bad;
2054 				}
2055 				break;
2056 
2057 			/*
2058 			 * Make sure the low-water is never greater than the
2059 			 * high-water.
2060 			 */
2061 			case SO_SNDLOWAT:
2062 				SOCKBUF_LOCK(&so->so_snd);
2063 				so->so_snd.sb_lowat =
2064 				    (optval > so->so_snd.sb_hiwat) ?
2065 				    so->so_snd.sb_hiwat : optval;
2066 				SOCKBUF_UNLOCK(&so->so_snd);
2067 				break;
2068 			case SO_RCVLOWAT:
2069 				SOCKBUF_LOCK(&so->so_rcv);
2070 				so->so_rcv.sb_lowat =
2071 				    (optval > so->so_rcv.sb_hiwat) ?
2072 				    so->so_rcv.sb_hiwat : optval;
2073 				SOCKBUF_UNLOCK(&so->so_rcv);
2074 				break;
2075 			}
2076 			break;
2077 
2078 		case SO_SNDTIMEO:
2079 		case SO_RCVTIMEO:
2080 #ifdef COMPAT_IA32
2081 			if (curthread->td_proc->p_sysent == &ia32_freebsd_sysvec) {
2082 				struct timeval32 tv32;
2083 
2084 				error = sooptcopyin(sopt, &tv32, sizeof tv32,
2085 				    sizeof tv32);
2086 				CP(tv32, tv, tv_sec);
2087 				CP(tv32, tv, tv_usec);
2088 			} else
2089 #endif
2090 				error = sooptcopyin(sopt, &tv, sizeof tv,
2091 				    sizeof tv);
2092 			if (error)
2093 				goto bad;
2094 
2095 			/* assert(hz > 0); */
2096 			if (tv.tv_sec < 0 || tv.tv_sec > INT_MAX / hz ||
2097 			    tv.tv_usec < 0 || tv.tv_usec >= 1000000) {
2098 				error = EDOM;
2099 				goto bad;
2100 			}
2101 			/* assert(tick > 0); */
2102 			/* assert(ULONG_MAX - INT_MAX >= 1000000); */
2103 			val = (u_long)(tv.tv_sec * hz) + tv.tv_usec / tick;
2104 			if (val > INT_MAX) {
2105 				error = EDOM;
2106 				goto bad;
2107 			}
2108 			if (val == 0 && tv.tv_usec != 0)
2109 				val = 1;
2110 
2111 			switch (sopt->sopt_name) {
2112 			case SO_SNDTIMEO:
2113 				so->so_snd.sb_timeo = val;
2114 				break;
2115 			case SO_RCVTIMEO:
2116 				so->so_rcv.sb_timeo = val;
2117 				break;
2118 			}
2119 			break;
2120 
2121 		case SO_LABEL:
2122 #ifdef MAC
2123 			error = sooptcopyin(sopt, &extmac, sizeof extmac,
2124 			    sizeof extmac);
2125 			if (error)
2126 				goto bad;
2127 			error = mac_setsockopt_label(sopt->sopt_td->td_ucred,
2128 			    so, &extmac);
2129 #else
2130 			error = EOPNOTSUPP;
2131 #endif
2132 			break;
2133 
2134 		default:
2135 			error = ENOPROTOOPT;
2136 			break;
2137 		}
2138 		if (error == 0 && so->so_proto != NULL &&
2139 		    so->so_proto->pr_ctloutput != NULL) {
2140 			(void) ((*so->so_proto->pr_ctloutput)
2141 				  (so, sopt));
2142 		}
2143 	}
2144 bad:
2145 	return (error);
2146 }
2147 
2148 /*
2149  * Helper routine for getsockopt.
2150  */
2151 int
2152 sooptcopyout(struct sockopt *sopt, const void *buf, size_t len)
2153 {
2154 	int	error;
2155 	size_t	valsize;
2156 
2157 	error = 0;
2158 
2159 	/*
2160 	 * Documented get behavior is that we always return a value, possibly
2161 	 * truncated to fit in the user's buffer.  Traditional behavior is
2162 	 * that we always tell the user precisely how much we copied, rather
2163 	 * than something useful like the total amount we had available for
2164 	 * her.  Note that this interface is not idempotent; the entire
2165 	 * answer must generated ahead of time.
2166 	 */
2167 	valsize = min(len, sopt->sopt_valsize);
2168 	sopt->sopt_valsize = valsize;
2169 	if (sopt->sopt_val != NULL) {
2170 		if (sopt->sopt_td != NULL)
2171 			error = copyout(buf, sopt->sopt_val, valsize);
2172 		else
2173 			bcopy(buf, sopt->sopt_val, valsize);
2174 	}
2175 	return (error);
2176 }
2177 
2178 int
2179 sogetopt(so, sopt)
2180 	struct socket *so;
2181 	struct sockopt *sopt;
2182 {
2183 	int	error, optval;
2184 	struct	linger l;
2185 	struct	timeval tv;
2186 #ifdef MAC
2187 	struct mac extmac;
2188 #endif
2189 
2190 	error = 0;
2191 	if (sopt->sopt_level != SOL_SOCKET) {
2192 		if (so->so_proto && so->so_proto->pr_ctloutput) {
2193 			return ((*so->so_proto->pr_ctloutput)
2194 				  (so, sopt));
2195 		} else
2196 			return (ENOPROTOOPT);
2197 	} else {
2198 		switch (sopt->sopt_name) {
2199 #ifdef INET
2200 		case SO_ACCEPTFILTER:
2201 			error = do_getopt_accept_filter(so, sopt);
2202 			break;
2203 #endif
2204 		case SO_LINGER:
2205 			SOCK_LOCK(so);
2206 			l.l_onoff = so->so_options & SO_LINGER;
2207 			l.l_linger = so->so_linger;
2208 			SOCK_UNLOCK(so);
2209 			error = sooptcopyout(sopt, &l, sizeof l);
2210 			break;
2211 
2212 		case SO_USELOOPBACK:
2213 		case SO_DONTROUTE:
2214 		case SO_DEBUG:
2215 		case SO_KEEPALIVE:
2216 		case SO_REUSEADDR:
2217 		case SO_REUSEPORT:
2218 		case SO_BROADCAST:
2219 		case SO_OOBINLINE:
2220 		case SO_ACCEPTCONN:
2221 		case SO_TIMESTAMP:
2222 		case SO_BINTIME:
2223 		case SO_NOSIGPIPE:
2224 			optval = so->so_options & sopt->sopt_name;
2225 integer:
2226 			error = sooptcopyout(sopt, &optval, sizeof optval);
2227 			break;
2228 
2229 		case SO_TYPE:
2230 			optval = so->so_type;
2231 			goto integer;
2232 
2233 		case SO_ERROR:
2234 			SOCK_LOCK(so);
2235 			optval = so->so_error;
2236 			so->so_error = 0;
2237 			SOCK_UNLOCK(so);
2238 			goto integer;
2239 
2240 		case SO_SNDBUF:
2241 			optval = so->so_snd.sb_hiwat;
2242 			goto integer;
2243 
2244 		case SO_RCVBUF:
2245 			optval = so->so_rcv.sb_hiwat;
2246 			goto integer;
2247 
2248 		case SO_SNDLOWAT:
2249 			optval = so->so_snd.sb_lowat;
2250 			goto integer;
2251 
2252 		case SO_RCVLOWAT:
2253 			optval = so->so_rcv.sb_lowat;
2254 			goto integer;
2255 
2256 		case SO_SNDTIMEO:
2257 		case SO_RCVTIMEO:
2258 			optval = (sopt->sopt_name == SO_SNDTIMEO ?
2259 				  so->so_snd.sb_timeo : so->so_rcv.sb_timeo);
2260 
2261 			tv.tv_sec = optval / hz;
2262 			tv.tv_usec = (optval % hz) * tick;
2263 #ifdef COMPAT_IA32
2264 			if (curthread->td_proc->p_sysent == &ia32_freebsd_sysvec) {
2265 				struct timeval32 tv32;
2266 
2267 				CP(tv, tv32, tv_sec);
2268 				CP(tv, tv32, tv_usec);
2269 				error = sooptcopyout(sopt, &tv32, sizeof tv32);
2270 			} else
2271 #endif
2272 				error = sooptcopyout(sopt, &tv, sizeof tv);
2273 			break;
2274 
2275 		case SO_LABEL:
2276 #ifdef MAC
2277 			error = sooptcopyin(sopt, &extmac, sizeof(extmac),
2278 			    sizeof(extmac));
2279 			if (error)
2280 				return (error);
2281 			error = mac_getsockopt_label(sopt->sopt_td->td_ucred,
2282 			    so, &extmac);
2283 			if (error)
2284 				return (error);
2285 			error = sooptcopyout(sopt, &extmac, sizeof extmac);
2286 #else
2287 			error = EOPNOTSUPP;
2288 #endif
2289 			break;
2290 
2291 		case SO_PEERLABEL:
2292 #ifdef MAC
2293 			error = sooptcopyin(sopt, &extmac, sizeof(extmac),
2294 			    sizeof(extmac));
2295 			if (error)
2296 				return (error);
2297 			error = mac_getsockopt_peerlabel(
2298 			    sopt->sopt_td->td_ucred, so, &extmac);
2299 			if (error)
2300 				return (error);
2301 			error = sooptcopyout(sopt, &extmac, sizeof extmac);
2302 #else
2303 			error = EOPNOTSUPP;
2304 #endif
2305 			break;
2306 
2307 		case SO_LISTENQLIMIT:
2308 			optval = so->so_qlimit;
2309 			goto integer;
2310 
2311 		case SO_LISTENQLEN:
2312 			optval = so->so_qlen;
2313 			goto integer;
2314 
2315 		case SO_LISTENINCQLEN:
2316 			optval = so->so_incqlen;
2317 			goto integer;
2318 
2319 		default:
2320 			error = ENOPROTOOPT;
2321 			break;
2322 		}
2323 		return (error);
2324 	}
2325 }
2326 
2327 /* XXX; prepare mbuf for (__FreeBSD__ < 3) routines. */
2328 int
2329 soopt_getm(struct sockopt *sopt, struct mbuf **mp)
2330 {
2331 	struct mbuf *m, *m_prev;
2332 	int sopt_size = sopt->sopt_valsize;
2333 
2334 	MGET(m, sopt->sopt_td ? M_TRYWAIT : M_DONTWAIT, MT_DATA);
2335 	if (m == NULL)
2336 		return ENOBUFS;
2337 	if (sopt_size > MLEN) {
2338 		MCLGET(m, sopt->sopt_td ? M_TRYWAIT : M_DONTWAIT);
2339 		if ((m->m_flags & M_EXT) == 0) {
2340 			m_free(m);
2341 			return ENOBUFS;
2342 		}
2343 		m->m_len = min(MCLBYTES, sopt_size);
2344 	} else {
2345 		m->m_len = min(MLEN, sopt_size);
2346 	}
2347 	sopt_size -= m->m_len;
2348 	*mp = m;
2349 	m_prev = m;
2350 
2351 	while (sopt_size) {
2352 		MGET(m, sopt->sopt_td ? M_TRYWAIT : M_DONTWAIT, MT_DATA);
2353 		if (m == NULL) {
2354 			m_freem(*mp);
2355 			return ENOBUFS;
2356 		}
2357 		if (sopt_size > MLEN) {
2358 			MCLGET(m, sopt->sopt_td != NULL ? M_TRYWAIT :
2359 			    M_DONTWAIT);
2360 			if ((m->m_flags & M_EXT) == 0) {
2361 				m_freem(m);
2362 				m_freem(*mp);
2363 				return ENOBUFS;
2364 			}
2365 			m->m_len = min(MCLBYTES, sopt_size);
2366 		} else {
2367 			m->m_len = min(MLEN, sopt_size);
2368 		}
2369 		sopt_size -= m->m_len;
2370 		m_prev->m_next = m;
2371 		m_prev = m;
2372 	}
2373 	return (0);
2374 }
2375 
2376 /* XXX; copyin sopt data into mbuf chain for (__FreeBSD__ < 3) routines. */
2377 int
2378 soopt_mcopyin(struct sockopt *sopt, struct mbuf *m)
2379 {
2380 	struct mbuf *m0 = m;
2381 
2382 	if (sopt->sopt_val == NULL)
2383 		return (0);
2384 	while (m != NULL && sopt->sopt_valsize >= m->m_len) {
2385 		if (sopt->sopt_td != NULL) {
2386 			int error;
2387 
2388 			error = copyin(sopt->sopt_val, mtod(m, char *),
2389 				       m->m_len);
2390 			if (error != 0) {
2391 				m_freem(m0);
2392 				return(error);
2393 			}
2394 		} else
2395 			bcopy(sopt->sopt_val, mtod(m, char *), m->m_len);
2396 		sopt->sopt_valsize -= m->m_len;
2397 		sopt->sopt_val = (char *)sopt->sopt_val + m->m_len;
2398 		m = m->m_next;
2399 	}
2400 	if (m != NULL) /* should be allocated enoughly at ip6_sooptmcopyin() */
2401 		panic("ip6_sooptmcopyin");
2402 	return (0);
2403 }
2404 
2405 /* XXX; copyout mbuf chain data into soopt for (__FreeBSD__ < 3) routines. */
2406 int
2407 soopt_mcopyout(struct sockopt *sopt, struct mbuf *m)
2408 {
2409 	struct mbuf *m0 = m;
2410 	size_t valsize = 0;
2411 
2412 	if (sopt->sopt_val == NULL)
2413 		return (0);
2414 	while (m != NULL && sopt->sopt_valsize >= m->m_len) {
2415 		if (sopt->sopt_td != NULL) {
2416 			int error;
2417 
2418 			error = copyout(mtod(m, char *), sopt->sopt_val,
2419 				       m->m_len);
2420 			if (error != 0) {
2421 				m_freem(m0);
2422 				return(error);
2423 			}
2424 		} else
2425 			bcopy(mtod(m, char *), sopt->sopt_val, m->m_len);
2426 	       sopt->sopt_valsize -= m->m_len;
2427 	       sopt->sopt_val = (char *)sopt->sopt_val + m->m_len;
2428 	       valsize += m->m_len;
2429 	       m = m->m_next;
2430 	}
2431 	if (m != NULL) {
2432 		/* enough soopt buffer should be given from user-land */
2433 		m_freem(m0);
2434 		return(EINVAL);
2435 	}
2436 	sopt->sopt_valsize = valsize;
2437 	return (0);
2438 }
2439 
2440 /*
2441  * sohasoutofband(): protocol notifies socket layer of the arrival of new
2442  * out-of-band data, which will then notify socket consumers.
2443  */
2444 void
2445 sohasoutofband(so)
2446 	struct socket *so;
2447 {
2448 	if (so->so_sigio != NULL)
2449 		pgsigio(&so->so_sigio, SIGURG, 0);
2450 	selwakeuppri(&so->so_rcv.sb_sel, PSOCK);
2451 }
2452 
2453 int
2454 sopoll(struct socket *so, int events, struct ucred *active_cred,
2455     struct thread *td)
2456 {
2457 
2458 	/* XXXRW: Temporary debugging. */
2459 	KASSERT(so->so_proto->pr_usrreqs->pru_sopoll != sopoll,
2460 	    ("sopoll: protocol calls sopoll"));
2461 
2462 	return (so->so_proto->pr_usrreqs->pru_sopoll(so, events, active_cred,
2463 	    td));
2464 }
2465 
2466 int
2467 sopoll_generic(struct socket *so, int events, struct ucred *active_cred,
2468     struct thread *td)
2469 {
2470 	int revents = 0;
2471 
2472 	SOCKBUF_LOCK(&so->so_snd);
2473 	SOCKBUF_LOCK(&so->so_rcv);
2474 	if (events & (POLLIN | POLLRDNORM))
2475 		if (soreadable(so))
2476 			revents |= events & (POLLIN | POLLRDNORM);
2477 
2478 	if (events & POLLINIGNEOF)
2479 		if (so->so_rcv.sb_cc >= so->so_rcv.sb_lowat ||
2480 		    !TAILQ_EMPTY(&so->so_comp) || so->so_error)
2481 			revents |= POLLINIGNEOF;
2482 
2483 	if (events & (POLLOUT | POLLWRNORM))
2484 		if (sowriteable(so))
2485 			revents |= events & (POLLOUT | POLLWRNORM);
2486 
2487 	if (events & (POLLPRI | POLLRDBAND))
2488 		if (so->so_oobmark || (so->so_rcv.sb_state & SBS_RCVATMARK))
2489 			revents |= events & (POLLPRI | POLLRDBAND);
2490 
2491 	if (revents == 0) {
2492 		if (events &
2493 		    (POLLIN | POLLINIGNEOF | POLLPRI | POLLRDNORM |
2494 		     POLLRDBAND)) {
2495 			selrecord(td, &so->so_rcv.sb_sel);
2496 			so->so_rcv.sb_flags |= SB_SEL;
2497 		}
2498 
2499 		if (events & (POLLOUT | POLLWRNORM)) {
2500 			selrecord(td, &so->so_snd.sb_sel);
2501 			so->so_snd.sb_flags |= SB_SEL;
2502 		}
2503 	}
2504 
2505 	SOCKBUF_UNLOCK(&so->so_rcv);
2506 	SOCKBUF_UNLOCK(&so->so_snd);
2507 	return (revents);
2508 }
2509 
2510 int
2511 soo_kqfilter(struct file *fp, struct knote *kn)
2512 {
2513 	struct socket *so = kn->kn_fp->f_data;
2514 	struct sockbuf *sb;
2515 
2516 	switch (kn->kn_filter) {
2517 	case EVFILT_READ:
2518 		if (so->so_options & SO_ACCEPTCONN)
2519 			kn->kn_fop = &solisten_filtops;
2520 		else
2521 			kn->kn_fop = &soread_filtops;
2522 		sb = &so->so_rcv;
2523 		break;
2524 	case EVFILT_WRITE:
2525 		kn->kn_fop = &sowrite_filtops;
2526 		sb = &so->so_snd;
2527 		break;
2528 	default:
2529 		return (EINVAL);
2530 	}
2531 
2532 	SOCKBUF_LOCK(sb);
2533 	knlist_add(&sb->sb_sel.si_note, kn, 1);
2534 	sb->sb_flags |= SB_KNOTE;
2535 	SOCKBUF_UNLOCK(sb);
2536 	return (0);
2537 }
2538 
2539 static void
2540 filt_sordetach(struct knote *kn)
2541 {
2542 	struct socket *so = kn->kn_fp->f_data;
2543 
2544 	SOCKBUF_LOCK(&so->so_rcv);
2545 	knlist_remove(&so->so_rcv.sb_sel.si_note, kn, 1);
2546 	if (knlist_empty(&so->so_rcv.sb_sel.si_note))
2547 		so->so_rcv.sb_flags &= ~SB_KNOTE;
2548 	SOCKBUF_UNLOCK(&so->so_rcv);
2549 }
2550 
2551 /*ARGSUSED*/
2552 static int
2553 filt_soread(struct knote *kn, long hint)
2554 {
2555 	struct socket *so;
2556 
2557 	so = kn->kn_fp->f_data;
2558 	SOCKBUF_LOCK_ASSERT(&so->so_rcv);
2559 
2560 	kn->kn_data = so->so_rcv.sb_cc - so->so_rcv.sb_ctl;
2561 	if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
2562 		kn->kn_flags |= EV_EOF;
2563 		kn->kn_fflags = so->so_error;
2564 		return (1);
2565 	} else if (so->so_error)	/* temporary udp error */
2566 		return (1);
2567 	else if (kn->kn_sfflags & NOTE_LOWAT)
2568 		return (kn->kn_data >= kn->kn_sdata);
2569 	else
2570 		return (so->so_rcv.sb_cc >= so->so_rcv.sb_lowat);
2571 }
2572 
2573 static void
2574 filt_sowdetach(struct knote *kn)
2575 {
2576 	struct socket *so = kn->kn_fp->f_data;
2577 
2578 	SOCKBUF_LOCK(&so->so_snd);
2579 	knlist_remove(&so->so_snd.sb_sel.si_note, kn, 1);
2580 	if (knlist_empty(&so->so_snd.sb_sel.si_note))
2581 		so->so_snd.sb_flags &= ~SB_KNOTE;
2582 	SOCKBUF_UNLOCK(&so->so_snd);
2583 }
2584 
2585 /*ARGSUSED*/
2586 static int
2587 filt_sowrite(struct knote *kn, long hint)
2588 {
2589 	struct socket *so;
2590 
2591 	so = kn->kn_fp->f_data;
2592 	SOCKBUF_LOCK_ASSERT(&so->so_snd);
2593 	kn->kn_data = sbspace(&so->so_snd);
2594 	if (so->so_snd.sb_state & SBS_CANTSENDMORE) {
2595 		kn->kn_flags |= EV_EOF;
2596 		kn->kn_fflags = so->so_error;
2597 		return (1);
2598 	} else if (so->so_error)	/* temporary udp error */
2599 		return (1);
2600 	else if (((so->so_state & SS_ISCONNECTED) == 0) &&
2601 	    (so->so_proto->pr_flags & PR_CONNREQUIRED))
2602 		return (0);
2603 	else if (kn->kn_sfflags & NOTE_LOWAT)
2604 		return (kn->kn_data >= kn->kn_sdata);
2605 	else
2606 		return (kn->kn_data >= so->so_snd.sb_lowat);
2607 }
2608 
2609 /*ARGSUSED*/
2610 static int
2611 filt_solisten(struct knote *kn, long hint)
2612 {
2613 	struct socket *so = kn->kn_fp->f_data;
2614 
2615 	kn->kn_data = so->so_qlen;
2616 	return (! TAILQ_EMPTY(&so->so_comp));
2617 }
2618 
2619 int
2620 socheckuid(struct socket *so, uid_t uid)
2621 {
2622 
2623 	if (so == NULL)
2624 		return (EPERM);
2625 	if (so->so_cred->cr_uid != uid)
2626 		return (EPERM);
2627 	return (0);
2628 }
2629 
2630 static int
2631 somaxconn_sysctl(SYSCTL_HANDLER_ARGS)
2632 {
2633 	int error;
2634 	int val;
2635 
2636 	val = somaxconn;
2637 	error = sysctl_handle_int(oidp, &val, sizeof(int), req);
2638 	if (error || !req->newptr )
2639 		return (error);
2640 
2641 	if (val < 1 || val > USHRT_MAX)
2642 		return (EINVAL);
2643 
2644 	somaxconn = val;
2645 	return (0);
2646 }
2647