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