xref: /freebsd/sys/kern/uipc_socket.c (revision ceaec73d406831b1251babb61675df0a1aa54a31)
1 /*-
2  * Copyright (c) 2004 The FreeBSD Foundation
3  * Copyright (c) 2004-2005 Robert N. M. Watson
4  * Copyright (c) 1982, 1986, 1988, 1990, 1993
5  *	The Regents of the University of California.  All rights reserved.
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 #include <sys/cdefs.h>
35 __FBSDID("$FreeBSD$");
36 
37 #include "opt_inet.h"
38 #include "opt_mac.h"
39 #include "opt_zero.h"
40 
41 #include <sys/param.h>
42 #include <sys/systm.h>
43 #include <sys/fcntl.h>
44 #include <sys/limits.h>
45 #include <sys/lock.h>
46 #include <sys/mac.h>
47 #include <sys/malloc.h>
48 #include <sys/mbuf.h>
49 #include <sys/mutex.h>
50 #include <sys/domain.h>
51 #include <sys/file.h>			/* for struct knote */
52 #include <sys/kernel.h>
53 #include <sys/event.h>
54 #include <sys/poll.h>
55 #include <sys/proc.h>
56 #include <sys/protosw.h>
57 #include <sys/socket.h>
58 #include <sys/socketvar.h>
59 #include <sys/resourcevar.h>
60 #include <sys/signalvar.h>
61 #include <sys/sysctl.h>
62 #include <sys/uio.h>
63 #include <sys/jail.h>
64 
65 #include <vm/uma.h>
66 
67 
68 static int	soreceive_rcvoob(struct socket *so, struct uio *uio,
69 		    int flags);
70 
71 static void	filt_sordetach(struct knote *kn);
72 static int	filt_soread(struct knote *kn, long hint);
73 static void	filt_sowdetach(struct knote *kn);
74 static int	filt_sowrite(struct knote *kn, long hint);
75 static int	filt_solisten(struct knote *kn, long hint);
76 
77 static struct filterops solisten_filtops =
78 	{ 1, NULL, filt_sordetach, filt_solisten };
79 static struct filterops soread_filtops =
80 	{ 1, NULL, filt_sordetach, filt_soread };
81 static struct filterops sowrite_filtops =
82 	{ 1, NULL, filt_sowdetach, filt_sowrite };
83 
84 uma_zone_t socket_zone;
85 so_gen_t	so_gencnt;	/* generation count for sockets */
86 
87 MALLOC_DEFINE(M_SONAME, "soname", "socket name");
88 MALLOC_DEFINE(M_PCB, "pcb", "protocol control block");
89 
90 SYSCTL_DECL(_kern_ipc);
91 
92 static int somaxconn = SOMAXCONN;
93 static int somaxconn_sysctl(SYSCTL_HANDLER_ARGS);
94 /* XXX: we dont have SYSCTL_USHORT */
95 SYSCTL_PROC(_kern_ipc, KIPC_SOMAXCONN, somaxconn, CTLTYPE_UINT | CTLFLAG_RW,
96     0, sizeof(int), somaxconn_sysctl, "I", "Maximum pending socket connection "
97     "queue size");
98 static int numopensockets;
99 SYSCTL_INT(_kern_ipc, OID_AUTO, numopensockets, CTLFLAG_RD,
100     &numopensockets, 0, "Number of open sockets");
101 #ifdef ZERO_COPY_SOCKETS
102 /* These aren't static because they're used in other files. */
103 int so_zero_copy_send = 1;
104 int so_zero_copy_receive = 1;
105 SYSCTL_NODE(_kern_ipc, OID_AUTO, zero_copy, CTLFLAG_RD, 0,
106     "Zero copy controls");
107 SYSCTL_INT(_kern_ipc_zero_copy, OID_AUTO, receive, CTLFLAG_RW,
108     &so_zero_copy_receive, 0, "Enable zero copy receive");
109 SYSCTL_INT(_kern_ipc_zero_copy, OID_AUTO, send, CTLFLAG_RW,
110     &so_zero_copy_send, 0, "Enable zero copy send");
111 #endif /* ZERO_COPY_SOCKETS */
112 
113 /*
114  * accept_mtx locks down per-socket fields relating to accept queues.  See
115  * socketvar.h for an annotation of the protected fields of struct socket.
116  */
117 struct mtx accept_mtx;
118 MTX_SYSINIT(accept_mtx, &accept_mtx, "accept", MTX_DEF);
119 
120 /*
121  * so_global_mtx protects so_gencnt, numopensockets, and the per-socket
122  * so_gencnt field.
123  */
124 static struct mtx so_global_mtx;
125 MTX_SYSINIT(so_global_mtx, &so_global_mtx, "so_glabel", MTX_DEF);
126 
127 /*
128  * Socket operation routines.
129  * These routines are called by the routines in
130  * sys_socket.c or from a system process, and
131  * implement the semantics of socket operations by
132  * switching out to the protocol specific routines.
133  */
134 
135 /*
136  * Get a socket structure from our zone, and initialize it.
137  * Note that it would probably be better to allocate socket
138  * and PCB at the same time, but I'm not convinced that all
139  * the protocols can be easily modified to do this.
140  *
141  * soalloc() returns a socket with a ref count of 0.
142  */
143 struct socket *
144 soalloc(int mflags)
145 {
146 	struct socket *so;
147 
148 	so = uma_zalloc(socket_zone, mflags | M_ZERO);
149 	if (so != NULL) {
150 #ifdef MAC
151 		if (mac_init_socket(so, mflags) != 0) {
152 			uma_zfree(socket_zone, so);
153 			return (NULL);
154 		}
155 #endif
156 		SOCKBUF_LOCK_INIT(&so->so_snd, "so_snd");
157 		SOCKBUF_LOCK_INIT(&so->so_rcv, "so_rcv");
158 		TAILQ_INIT(&so->so_aiojobq);
159 		mtx_lock(&so_global_mtx);
160 		so->so_gencnt = ++so_gencnt;
161 		++numopensockets;
162 		mtx_unlock(&so_global_mtx);
163 	}
164 	return (so);
165 }
166 
167 /*
168  * socreate returns a socket with a ref count of 1.  The socket should be
169  * closed with soclose().
170  */
171 int
172 socreate(dom, aso, type, proto, cred, td)
173 	int dom;
174 	struct socket **aso;
175 	int type;
176 	int proto;
177 	struct ucred *cred;
178 	struct thread *td;
179 {
180 	struct protosw *prp;
181 	struct socket *so;
182 	int error;
183 
184 	if (proto)
185 		prp = pffindproto(dom, proto, type);
186 	else
187 		prp = pffindtype(dom, type);
188 
189 	if (prp == NULL || prp->pr_usrreqs->pru_attach == NULL ||
190 	    prp->pr_usrreqs->pru_attach == pru_attach_notsupp)
191 		return (EPROTONOSUPPORT);
192 
193 	if (jailed(cred) && jail_socket_unixiproute_only &&
194 	    prp->pr_domain->dom_family != PF_LOCAL &&
195 	    prp->pr_domain->dom_family != PF_INET &&
196 	    prp->pr_domain->dom_family != PF_ROUTE) {
197 		return (EPROTONOSUPPORT);
198 	}
199 
200 	if (prp->pr_type != type)
201 		return (EPROTOTYPE);
202 	so = soalloc(M_WAITOK);
203 	if (so == NULL)
204 		return (ENOBUFS);
205 
206 	TAILQ_INIT(&so->so_incomp);
207 	TAILQ_INIT(&so->so_comp);
208 	so->so_type = type;
209 	so->so_cred = crhold(cred);
210 	so->so_proto = prp;
211 #ifdef MAC
212 	mac_create_socket(cred, so);
213 #endif
214 	knlist_init(&so->so_rcv.sb_sel.si_note, SOCKBUF_MTX(&so->so_rcv));
215 	knlist_init(&so->so_snd.sb_sel.si_note, SOCKBUF_MTX(&so->so_snd));
216 	so->so_count = 1;
217 	error = (*prp->pr_usrreqs->pru_attach)(so, proto, td);
218 	if (error) {
219 		ACCEPT_LOCK();
220 		SOCK_LOCK(so);
221 		so->so_state |= SS_NOFDREF;
222 		sorele(so);
223 		return (error);
224 	}
225 	*aso = so;
226 	return (0);
227 }
228 
229 int
230 sobind(so, nam, td)
231 	struct socket *so;
232 	struct sockaddr *nam;
233 	struct thread *td;
234 {
235 
236 	return ((*so->so_proto->pr_usrreqs->pru_bind)(so, nam, td));
237 }
238 
239 void
240 sodealloc(struct socket *so)
241 {
242 
243 	KASSERT(so->so_count == 0, ("sodealloc(): so_count %d", so->so_count));
244 	mtx_lock(&so_global_mtx);
245 	so->so_gencnt = ++so_gencnt;
246 	mtx_unlock(&so_global_mtx);
247 	if (so->so_rcv.sb_hiwat)
248 		(void)chgsbsize(so->so_cred->cr_uidinfo,
249 		    &so->so_rcv.sb_hiwat, 0, RLIM_INFINITY);
250 	if (so->so_snd.sb_hiwat)
251 		(void)chgsbsize(so->so_cred->cr_uidinfo,
252 		    &so->so_snd.sb_hiwat, 0, RLIM_INFINITY);
253 #ifdef INET
254 	/* remove acccept filter if one is present. */
255 	if (so->so_accf != NULL)
256 		do_setopt_accept_filter(so, NULL);
257 #endif
258 #ifdef MAC
259 	mac_destroy_socket(so);
260 #endif
261 	crfree(so->so_cred);
262 	SOCKBUF_LOCK_DESTROY(&so->so_snd);
263 	SOCKBUF_LOCK_DESTROY(&so->so_rcv);
264 	uma_zfree(socket_zone, so);
265 	mtx_lock(&so_global_mtx);
266 	--numopensockets;
267 	mtx_unlock(&so_global_mtx);
268 }
269 
270 /*
271  * solisten() transitions a socket from a non-listening state to a listening
272  * state, but can also be used to update the listen queue depth on an
273  * existing listen socket.  The protocol will call back into the sockets
274  * layer using solisten_proto_check() and solisten_proto() to check and set
275  * socket-layer listen state.  Call backs are used so that the protocol can
276  * acquire both protocol and socket layer locks in whatever order is reuiqred
277  * by the protocol.
278  *
279  * Protocol implementors are advised to hold the socket lock across the
280  * socket-layer test and set to avoid races at the socket layer.
281  */
282 int
283 solisten(so, backlog, td)
284 	struct socket *so;
285 	int backlog;
286 	struct thread *td;
287 {
288 	int error;
289 
290 	error = (*so->so_proto->pr_usrreqs->pru_listen)(so, td);
291 	if (error)
292 		return (error);
293 
294 	/*
295 	 * XXXRW: The following state adjustment should occur in
296 	 * solisten_proto(), but we don't currently pass the backlog request
297 	 * to the protocol via pru_listen().
298 	 */
299 	if (backlog < 0 || backlog > somaxconn)
300 		backlog = somaxconn;
301 	so->so_qlimit = backlog;
302 	return (0);
303 }
304 
305 int
306 solisten_proto_check(so)
307 	struct socket *so;
308 {
309 
310 	SOCK_LOCK_ASSERT(so);
311 
312 	if (so->so_state & (SS_ISCONNECTED | SS_ISCONNECTING |
313 	    SS_ISDISCONNECTING))
314 		return (EINVAL);
315 	return (0);
316 }
317 
318 void
319 solisten_proto(so)
320 	struct socket *so;
321 {
322 
323 	SOCK_LOCK_ASSERT(so);
324 
325 	so->so_options |= SO_ACCEPTCONN;
326 }
327 
328 /*
329  * Attempt to free a socket.  This should really be sotryfree().
330  *
331  * We free the socket if the protocol is no longer interested in the socket,
332  * there's no file descriptor reference, and the refcount is 0.  While the
333  * calling macro sotryfree() tests the refcount, sofree() has to test it
334  * again as it's possible to race with an accept()ing thread if the socket is
335  * in an listen queue of a listen socket, as being in the listen queue
336  * doesn't elevate the reference count.  sofree() acquires the accept mutex
337  * early for this test in order to avoid that race.
338  */
339 void
340 sofree(so)
341 	struct socket *so;
342 {
343 	struct socket *head;
344 
345 	ACCEPT_LOCK_ASSERT();
346 	SOCK_LOCK_ASSERT(so);
347 
348 	if (so->so_pcb != NULL || (so->so_state & SS_NOFDREF) == 0 ||
349 	    so->so_count != 0) {
350 		SOCK_UNLOCK(so);
351 		ACCEPT_UNLOCK();
352 		return;
353 	}
354 
355 	head = so->so_head;
356 	if (head != NULL) {
357 		KASSERT((so->so_qstate & SQ_COMP) != 0 ||
358 		    (so->so_qstate & SQ_INCOMP) != 0,
359 		    ("sofree: so_head != NULL, but neither SQ_COMP nor "
360 		    "SQ_INCOMP"));
361 		KASSERT((so->so_qstate & SQ_COMP) == 0 ||
362 		    (so->so_qstate & SQ_INCOMP) == 0,
363 		    ("sofree: so->so_qstate is SQ_COMP and also SQ_INCOMP"));
364 		/*
365 		 * accept(2) is responsible draining the completed
366 		 * connection queue and freeing those sockets, so
367 		 * we just return here if this socket is currently
368 		 * on the completed connection queue.  Otherwise,
369 		 * accept(2) may hang after select(2) has indicating
370 		 * that a listening socket was ready.  If it's an
371 		 * incomplete connection, we remove it from the queue
372 		 * and free it; otherwise, it won't be released until
373 		 * the listening socket is closed.
374 		 */
375 		if ((so->so_qstate & SQ_COMP) != 0) {
376 			SOCK_UNLOCK(so);
377 			ACCEPT_UNLOCK();
378 			return;
379 		}
380 		TAILQ_REMOVE(&head->so_incomp, so, so_list);
381 		head->so_incqlen--;
382 		so->so_qstate &= ~SQ_INCOMP;
383 		so->so_head = NULL;
384 	}
385 	KASSERT((so->so_qstate & SQ_COMP) == 0 &&
386 	    (so->so_qstate & SQ_INCOMP) == 0,
387 	    ("sofree: so_head == NULL, but still SQ_COMP(%d) or SQ_INCOMP(%d)",
388 	    so->so_qstate & SQ_COMP, so->so_qstate & SQ_INCOMP));
389 	SOCK_UNLOCK(so);
390 	ACCEPT_UNLOCK();
391 	SOCKBUF_LOCK(&so->so_snd);
392 	so->so_snd.sb_flags |= SB_NOINTR;
393 	(void)sblock(&so->so_snd, M_WAITOK);
394 	/*
395 	 * socantsendmore_locked() drops the socket buffer mutex so that it
396 	 * can safely perform wakeups.  Re-acquire the mutex before
397 	 * continuing.
398 	 */
399 	socantsendmore_locked(so);
400 	SOCKBUF_LOCK(&so->so_snd);
401 	sbunlock(&so->so_snd);
402 	sbrelease_locked(&so->so_snd, so);
403 	SOCKBUF_UNLOCK(&so->so_snd);
404 	sorflush(so);
405 	knlist_destroy(&so->so_rcv.sb_sel.si_note);
406 	knlist_destroy(&so->so_snd.sb_sel.si_note);
407 	sodealloc(so);
408 }
409 
410 /*
411  * Close a socket on last file table reference removal.
412  * Initiate disconnect if connected.
413  * Free socket when disconnect complete.
414  *
415  * This function will sorele() the socket.  Note that soclose() may be
416  * called prior to the ref count reaching zero.  The actual socket
417  * structure will not be freed until the ref count reaches zero.
418  */
419 int
420 soclose(so)
421 	struct socket *so;
422 {
423 	int error = 0;
424 
425 	KASSERT(!(so->so_state & SS_NOFDREF), ("soclose: SS_NOFDREF on enter"));
426 
427 	funsetown(&so->so_sigio);
428 	if (so->so_options & SO_ACCEPTCONN) {
429 		struct socket *sp;
430 		ACCEPT_LOCK();
431 		while ((sp = TAILQ_FIRST(&so->so_incomp)) != NULL) {
432 			TAILQ_REMOVE(&so->so_incomp, sp, so_list);
433 			so->so_incqlen--;
434 			sp->so_qstate &= ~SQ_INCOMP;
435 			sp->so_head = NULL;
436 			ACCEPT_UNLOCK();
437 			(void) soabort(sp);
438 			ACCEPT_LOCK();
439 		}
440 		while ((sp = TAILQ_FIRST(&so->so_comp)) != NULL) {
441 			TAILQ_REMOVE(&so->so_comp, sp, so_list);
442 			so->so_qlen--;
443 			sp->so_qstate &= ~SQ_COMP;
444 			sp->so_head = NULL;
445 			ACCEPT_UNLOCK();
446 			(void) soabort(sp);
447 			ACCEPT_LOCK();
448 		}
449 		ACCEPT_UNLOCK();
450 	}
451 	if (so->so_pcb == NULL)
452 		goto discard;
453 	if (so->so_state & SS_ISCONNECTED) {
454 		if ((so->so_state & SS_ISDISCONNECTING) == 0) {
455 			error = sodisconnect(so);
456 			if (error)
457 				goto drop;
458 		}
459 		if (so->so_options & SO_LINGER) {
460 			if ((so->so_state & SS_ISDISCONNECTING) &&
461 			    (so->so_state & SS_NBIO))
462 				goto drop;
463 			while (so->so_state & SS_ISCONNECTED) {
464 				error = tsleep(&so->so_timeo,
465 				    PSOCK | PCATCH, "soclos", so->so_linger * hz);
466 				if (error)
467 					break;
468 			}
469 		}
470 	}
471 drop:
472 	if (so->so_pcb != NULL) {
473 		int error2 = (*so->so_proto->pr_usrreqs->pru_detach)(so);
474 		if (error == 0)
475 			error = error2;
476 	}
477 discard:
478 	ACCEPT_LOCK();
479 	SOCK_LOCK(so);
480 	KASSERT((so->so_state & SS_NOFDREF) == 0, ("soclose: NOFDREF"));
481 	so->so_state |= SS_NOFDREF;
482 	sorele(so);
483 	return (error);
484 }
485 
486 /*
487  * soabort() must not be called with any socket locks held, as it calls
488  * into the protocol, which will call back into the socket code causing
489  * it to acquire additional socket locks that may cause recursion or lock
490  * order reversals.
491  */
492 int
493 soabort(so)
494 	struct socket *so;
495 {
496 	int error;
497 
498 	error = (*so->so_proto->pr_usrreqs->pru_abort)(so);
499 	if (error) {
500 		ACCEPT_LOCK();
501 		SOCK_LOCK(so);
502 		sotryfree(so);	/* note: does not decrement the ref count */
503 		return error;
504 	}
505 	return (0);
506 }
507 
508 int
509 soaccept(so, nam)
510 	struct socket *so;
511 	struct sockaddr **nam;
512 {
513 	int error;
514 
515 	SOCK_LOCK(so);
516 	KASSERT((so->so_state & SS_NOFDREF) != 0, ("soaccept: !NOFDREF"));
517 	so->so_state &= ~SS_NOFDREF;
518 	SOCK_UNLOCK(so);
519 	error = (*so->so_proto->pr_usrreqs->pru_accept)(so, nam);
520 	return (error);
521 }
522 
523 int
524 soconnect(so, nam, td)
525 	struct socket *so;
526 	struct sockaddr *nam;
527 	struct thread *td;
528 {
529 	int error;
530 
531 	if (so->so_options & SO_ACCEPTCONN)
532 		return (EOPNOTSUPP);
533 	/*
534 	 * If protocol is connection-based, can only connect once.
535 	 * Otherwise, if connected, try to disconnect first.
536 	 * This allows user to disconnect by connecting to, e.g.,
537 	 * a null address.
538 	 */
539 	if (so->so_state & (SS_ISCONNECTED|SS_ISCONNECTING) &&
540 	    ((so->so_proto->pr_flags & PR_CONNREQUIRED) ||
541 	    (error = sodisconnect(so)))) {
542 		error = EISCONN;
543 	} else {
544 		/*
545 		 * Prevent accumulated error from previous connection
546 		 * from biting us.
547 		 */
548 		so->so_error = 0;
549 		error = (*so->so_proto->pr_usrreqs->pru_connect)(so, nam, td);
550 	}
551 
552 	return (error);
553 }
554 
555 int
556 soconnect2(so1, so2)
557 	struct socket *so1;
558 	struct socket *so2;
559 {
560 
561 	return ((*so1->so_proto->pr_usrreqs->pru_connect2)(so1, so2));
562 }
563 
564 int
565 sodisconnect(so)
566 	struct socket *so;
567 {
568 	int error;
569 
570 	if ((so->so_state & SS_ISCONNECTED) == 0)
571 		return (ENOTCONN);
572 	if (so->so_state & SS_ISDISCONNECTING)
573 		return (EALREADY);
574 	error = (*so->so_proto->pr_usrreqs->pru_disconnect)(so);
575 	return (error);
576 }
577 
578 #define	SBLOCKWAIT(f)	(((f) & MSG_DONTWAIT) ? M_NOWAIT : M_WAITOK)
579 /*
580  * Send on a socket.
581  * If send must go all at once and message is larger than
582  * send buffering, then hard error.
583  * Lock against other senders.
584  * If must go all at once and not enough room now, then
585  * inform user that this would block and do nothing.
586  * Otherwise, if nonblocking, send as much as possible.
587  * The data to be sent is described by "uio" if nonzero,
588  * otherwise by the mbuf chain "top" (which must be null
589  * if uio is not).  Data provided in mbuf chain must be small
590  * enough to send all at once.
591  *
592  * Returns nonzero on error, timeout or signal; callers
593  * must check for short counts if EINTR/ERESTART are returned.
594  * Data and control buffers are freed on return.
595  */
596 
597 #ifdef ZERO_COPY_SOCKETS
598 struct so_zerocopy_stats{
599 	int size_ok;
600 	int align_ok;
601 	int found_ifp;
602 };
603 struct so_zerocopy_stats so_zerocp_stats = {0,0,0};
604 #include <netinet/in.h>
605 #include <net/route.h>
606 #include <netinet/in_pcb.h>
607 #include <vm/vm.h>
608 #include <vm/vm_page.h>
609 #include <vm/vm_object.h>
610 #endif /*ZERO_COPY_SOCKETS*/
611 
612 int
613 sosend(so, addr, uio, top, control, flags, td)
614 	struct socket *so;
615 	struct sockaddr *addr;
616 	struct uio *uio;
617 	struct mbuf *top;
618 	struct mbuf *control;
619 	int flags;
620 	struct thread *td;
621 {
622 	struct mbuf **mp;
623 	struct mbuf *m;
624 	long space, len = 0, resid;
625 	int clen = 0, error, dontroute;
626 	int atomic = sosendallatonce(so) || top;
627 #ifdef ZERO_COPY_SOCKETS
628 	int cow_send;
629 #endif /* ZERO_COPY_SOCKETS */
630 
631 	if (uio != NULL)
632 		resid = uio->uio_resid;
633 	else
634 		resid = top->m_pkthdr.len;
635 	/*
636 	 * In theory resid should be unsigned.
637 	 * However, space must be signed, as it might be less than 0
638 	 * if we over-committed, and we must use a signed comparison
639 	 * of space and resid.  On the other hand, a negative resid
640 	 * causes us to loop sending 0-length segments to the protocol.
641 	 *
642 	 * Also check to make sure that MSG_EOR isn't used on SOCK_STREAM
643 	 * type sockets since that's an error.
644 	 */
645 	if (resid < 0 || (so->so_type == SOCK_STREAM && (flags & MSG_EOR))) {
646 		error = EINVAL;
647 		goto out;
648 	}
649 
650 	dontroute =
651 	    (flags & MSG_DONTROUTE) && (so->so_options & SO_DONTROUTE) == 0 &&
652 	    (so->so_proto->pr_flags & PR_ATOMIC);
653 	if (td != NULL)
654 		td->td_proc->p_stats->p_ru.ru_msgsnd++;
655 	if (control != NULL)
656 		clen = control->m_len;
657 #define	snderr(errno)	{ error = (errno); goto release; }
658 
659 	SOCKBUF_LOCK(&so->so_snd);
660 restart:
661 	SOCKBUF_LOCK_ASSERT(&so->so_snd);
662 	error = sblock(&so->so_snd, SBLOCKWAIT(flags));
663 	if (error)
664 		goto out_locked;
665 	do {
666 		SOCKBUF_LOCK_ASSERT(&so->so_snd);
667 		if (so->so_snd.sb_state & SBS_CANTSENDMORE)
668 			snderr(EPIPE);
669 		if (so->so_error) {
670 			error = so->so_error;
671 			so->so_error = 0;
672 			goto release;
673 		}
674 		if ((so->so_state & SS_ISCONNECTED) == 0) {
675 			/*
676 			 * `sendto' and `sendmsg' is allowed on a connection-
677 			 * based socket if it supports implied connect.
678 			 * Return ENOTCONN if not connected and no address is
679 			 * supplied.
680 			 */
681 			if ((so->so_proto->pr_flags & PR_CONNREQUIRED) &&
682 			    (so->so_proto->pr_flags & PR_IMPLOPCL) == 0) {
683 				if ((so->so_state & SS_ISCONFIRMING) == 0 &&
684 				    !(resid == 0 && clen != 0))
685 					snderr(ENOTCONN);
686 			} else if (addr == NULL)
687 			    snderr(so->so_proto->pr_flags & PR_CONNREQUIRED ?
688 				   ENOTCONN : EDESTADDRREQ);
689 		}
690 		space = sbspace(&so->so_snd);
691 		if (flags & MSG_OOB)
692 			space += 1024;
693 		if ((atomic && resid > so->so_snd.sb_hiwat) ||
694 		    clen > so->so_snd.sb_hiwat)
695 			snderr(EMSGSIZE);
696 		if (space < resid + clen &&
697 		    (atomic || space < so->so_snd.sb_lowat || space < clen)) {
698 			if ((so->so_state & SS_NBIO) || (flags & MSG_NBIO))
699 				snderr(EWOULDBLOCK);
700 			sbunlock(&so->so_snd);
701 			error = sbwait(&so->so_snd);
702 			if (error)
703 				goto out_locked;
704 			goto restart;
705 		}
706 		SOCKBUF_UNLOCK(&so->so_snd);
707 		mp = &top;
708 		space -= clen;
709 		do {
710 		    if (uio == NULL) {
711 			/*
712 			 * Data is prepackaged in "top".
713 			 */
714 			resid = 0;
715 			if (flags & MSG_EOR)
716 				top->m_flags |= M_EOR;
717 		    } else do {
718 #ifdef ZERO_COPY_SOCKETS
719 			cow_send = 0;
720 #endif /* ZERO_COPY_SOCKETS */
721 			if (resid >= MINCLSIZE) {
722 #ifdef ZERO_COPY_SOCKETS
723 				if (top == NULL) {
724 					MGETHDR(m, M_TRYWAIT, MT_DATA);
725 					if (m == NULL) {
726 						error = ENOBUFS;
727 						SOCKBUF_LOCK(&so->so_snd);
728 						goto release;
729 					}
730 					m->m_pkthdr.len = 0;
731 					m->m_pkthdr.rcvif = (struct ifnet *)0;
732 				} else {
733 					MGET(m, M_TRYWAIT, MT_DATA);
734 					if (m == NULL) {
735 						error = ENOBUFS;
736 						SOCKBUF_LOCK(&so->so_snd);
737 						goto release;
738 					}
739 				}
740 				if (so_zero_copy_send &&
741 				    resid>=PAGE_SIZE &&
742 				    space>=PAGE_SIZE &&
743 				    uio->uio_iov->iov_len>=PAGE_SIZE) {
744 					so_zerocp_stats.size_ok++;
745 					if (!((vm_offset_t)
746 					  uio->uio_iov->iov_base & PAGE_MASK)){
747 						so_zerocp_stats.align_ok++;
748 						cow_send = socow_setup(m, uio);
749 					}
750 				}
751 				if (!cow_send) {
752 					MCLGET(m, M_TRYWAIT);
753 					if ((m->m_flags & M_EXT) == 0) {
754 						m_free(m);
755 						m = NULL;
756 					} else {
757 						len = min(min(MCLBYTES, resid), space);
758 					}
759 				} else
760 					len = PAGE_SIZE;
761 #else /* ZERO_COPY_SOCKETS */
762 				if (top == NULL) {
763 					m = m_getcl(M_TRYWAIT, MT_DATA, M_PKTHDR);
764 					m->m_pkthdr.len = 0;
765 					m->m_pkthdr.rcvif = (struct ifnet *)0;
766 				} else
767 					m = m_getcl(M_TRYWAIT, MT_DATA, 0);
768 				len = min(min(MCLBYTES, resid), space);
769 #endif /* ZERO_COPY_SOCKETS */
770 			} else {
771 				if (top == NULL) {
772 					m = m_gethdr(M_TRYWAIT, MT_DATA);
773 					m->m_pkthdr.len = 0;
774 					m->m_pkthdr.rcvif = (struct ifnet *)0;
775 
776 					len = min(min(MHLEN, resid), space);
777 					/*
778 					 * For datagram protocols, leave room
779 					 * for protocol headers in first mbuf.
780 					 */
781 					if (atomic && m && len < MHLEN)
782 						MH_ALIGN(m, len);
783 				} else {
784 					m = m_get(M_TRYWAIT, MT_DATA);
785 					len = min(min(MLEN, resid), space);
786 				}
787 			}
788 			if (m == NULL) {
789 				error = ENOBUFS;
790 				SOCKBUF_LOCK(&so->so_snd);
791 				goto release;
792 			}
793 
794 			space -= len;
795 #ifdef ZERO_COPY_SOCKETS
796 			if (cow_send)
797 				error = 0;
798 			else
799 #endif /* ZERO_COPY_SOCKETS */
800 			error = uiomove(mtod(m, void *), (int)len, uio);
801 			resid = uio->uio_resid;
802 			m->m_len = len;
803 			*mp = m;
804 			top->m_pkthdr.len += len;
805 			if (error) {
806 				SOCKBUF_LOCK(&so->so_snd);
807 				goto release;
808 			}
809 			mp = &m->m_next;
810 			if (resid <= 0) {
811 				if (flags & MSG_EOR)
812 					top->m_flags |= M_EOR;
813 				break;
814 			}
815 		    } while (space > 0 && atomic);
816 		    if (dontroute) {
817 			    SOCK_LOCK(so);
818 			    so->so_options |= SO_DONTROUTE;
819 			    SOCK_UNLOCK(so);
820 		    }
821 		    /*
822 		     * XXX all the SBS_CANTSENDMORE checks previously
823 		     * done could be out of date.  We could have recieved
824 		     * a reset packet in an interrupt or maybe we slept
825 		     * while doing page faults in uiomove() etc. We could
826 		     * probably recheck again inside the locking protection
827 		     * here, but there are probably other places that this
828 		     * also happens.  We must rethink this.
829 		     */
830 		    error = (*so->so_proto->pr_usrreqs->pru_send)(so,
831 			(flags & MSG_OOB) ? PRUS_OOB :
832 			/*
833 			 * If the user set MSG_EOF, the protocol
834 			 * understands this flag and nothing left to
835 			 * send then use PRU_SEND_EOF instead of PRU_SEND.
836 			 */
837 			((flags & MSG_EOF) &&
838 			 (so->so_proto->pr_flags & PR_IMPLOPCL) &&
839 			 (resid <= 0)) ?
840 				PRUS_EOF :
841 			/* If there is more to send set PRUS_MORETOCOME */
842 			(resid > 0 && space > 0) ? PRUS_MORETOCOME : 0,
843 			top, addr, control, td);
844 		    if (dontroute) {
845 			    SOCK_LOCK(so);
846 			    so->so_options &= ~SO_DONTROUTE;
847 			    SOCK_UNLOCK(so);
848 		    }
849 		    clen = 0;
850 		    control = NULL;
851 		    top = NULL;
852 		    mp = &top;
853 		    if (error) {
854 			SOCKBUF_LOCK(&so->so_snd);
855 			goto release;
856 		    }
857 		} while (resid && space > 0);
858 		SOCKBUF_LOCK(&so->so_snd);
859 	} while (resid);
860 
861 release:
862 	SOCKBUF_LOCK_ASSERT(&so->so_snd);
863 	sbunlock(&so->so_snd);
864 out_locked:
865 	SOCKBUF_LOCK_ASSERT(&so->so_snd);
866 	SOCKBUF_UNLOCK(&so->so_snd);
867 out:
868 	if (top != NULL)
869 		m_freem(top);
870 	if (control != NULL)
871 		m_freem(control);
872 	return (error);
873 }
874 
875 /*
876  * The part of soreceive() that implements reading non-inline out-of-band
877  * data from a socket.  For more complete comments, see soreceive(), from
878  * which this code originated.
879  *
880  * Note that soreceive_rcvoob(), unlike the remainder of soreceive(), is
881  * unable to return an mbuf chain to the caller.
882  */
883 static int
884 soreceive_rcvoob(so, uio, flags)
885 	struct socket *so;
886 	struct uio *uio;
887 	int flags;
888 {
889 	struct protosw *pr = so->so_proto;
890 	struct mbuf *m;
891 	int error;
892 
893 	KASSERT(flags & MSG_OOB, ("soreceive_rcvoob: (flags & MSG_OOB) == 0"));
894 
895 	m = m_get(M_TRYWAIT, MT_DATA);
896 	if (m == NULL)
897 		return (ENOBUFS);
898 	error = (*pr->pr_usrreqs->pru_rcvoob)(so, m, flags & MSG_PEEK);
899 	if (error)
900 		goto bad;
901 	do {
902 #ifdef ZERO_COPY_SOCKETS
903 		if (so_zero_copy_receive) {
904 			int disposable;
905 
906 			if ((m->m_flags & M_EXT)
907 			 && (m->m_ext.ext_type == EXT_DISPOSABLE))
908 				disposable = 1;
909 			else
910 				disposable = 0;
911 
912 			error = uiomoveco(mtod(m, void *),
913 					  min(uio->uio_resid, m->m_len),
914 					  uio, disposable);
915 		} else
916 #endif /* ZERO_COPY_SOCKETS */
917 		error = uiomove(mtod(m, void *),
918 		    (int) min(uio->uio_resid, m->m_len), uio);
919 		m = m_free(m);
920 	} while (uio->uio_resid && error == 0 && m);
921 bad:
922 	if (m != NULL)
923 		m_freem(m);
924 	return (error);
925 }
926 
927 /*
928  * Following replacement or removal of the first mbuf on the first mbuf chain
929  * of a socket buffer, push necessary state changes back into the socket
930  * buffer so that other consumers see the values consistently.  'nextrecord'
931  * is the callers locally stored value of the original value of
932  * sb->sb_mb->m_nextpkt which must be restored when the lead mbuf changes.
933  * NOTE: 'nextrecord' may be NULL.
934  */
935 static __inline void
936 sockbuf_pushsync(struct sockbuf *sb, struct mbuf *nextrecord)
937 {
938 
939 	SOCKBUF_LOCK_ASSERT(sb);
940 	/*
941 	 * First, update for the new value of nextrecord.  If necessary, make
942 	 * it the first record.
943 	 */
944 	if (sb->sb_mb != NULL)
945 		sb->sb_mb->m_nextpkt = nextrecord;
946 	else
947 		sb->sb_mb = nextrecord;
948 
949         /*
950          * Now update any dependent socket buffer fields to reflect the new
951          * state.  This is an expanded inline of SB_EMPTY_FIXUP(), with the
952 	 * addition of a second clause that takes care of the case where
953 	 * sb_mb has been updated, but remains the last record.
954          */
955         if (sb->sb_mb == NULL) {
956                 sb->sb_mbtail = NULL;
957                 sb->sb_lastrecord = NULL;
958         } else if (sb->sb_mb->m_nextpkt == NULL)
959                 sb->sb_lastrecord = sb->sb_mb;
960 }
961 
962 
963 /*
964  * Implement receive operations on a socket.
965  * We depend on the way that records are added to the sockbuf
966  * by sbappend*.  In particular, each record (mbufs linked through m_next)
967  * must begin with an address if the protocol so specifies,
968  * followed by an optional mbuf or mbufs containing ancillary data,
969  * and then zero or more mbufs of data.
970  * In order to avoid blocking network interrupts for the entire time here,
971  * we splx() while doing the actual copy to user space.
972  * Although the sockbuf is locked, new data may still be appended,
973  * and thus we must maintain consistency of the sockbuf during that time.
974  *
975  * The caller may receive the data as a single mbuf chain by supplying
976  * an mbuf **mp0 for use in returning the chain.  The uio is then used
977  * only for the count in uio_resid.
978  */
979 int
980 soreceive(so, psa, uio, mp0, controlp, flagsp)
981 	struct socket *so;
982 	struct sockaddr **psa;
983 	struct uio *uio;
984 	struct mbuf **mp0;
985 	struct mbuf **controlp;
986 	int *flagsp;
987 {
988 	struct mbuf *m, **mp;
989 	int flags, len, error, offset;
990 	struct protosw *pr = so->so_proto;
991 	struct mbuf *nextrecord;
992 	int moff, type = 0;
993 	int orig_resid = uio->uio_resid;
994 
995 	mp = mp0;
996 	if (psa != NULL)
997 		*psa = NULL;
998 	if (controlp != NULL)
999 		*controlp = NULL;
1000 	if (flagsp != NULL)
1001 		flags = *flagsp &~ MSG_EOR;
1002 	else
1003 		flags = 0;
1004 	if (flags & MSG_OOB)
1005 		return (soreceive_rcvoob(so, uio, flags));
1006 	if (mp != NULL)
1007 		*mp = NULL;
1008 	if ((pr->pr_flags & PR_WANTRCVD) && (so->so_state & SS_ISCONFIRMING)
1009 	    && uio->uio_resid)
1010 		(*pr->pr_usrreqs->pru_rcvd)(so, 0);
1011 
1012 	SOCKBUF_LOCK(&so->so_rcv);
1013 restart:
1014 	SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1015 	error = sblock(&so->so_rcv, SBLOCKWAIT(flags));
1016 	if (error)
1017 		goto out;
1018 
1019 	m = so->so_rcv.sb_mb;
1020 	/*
1021 	 * If we have less data than requested, block awaiting more
1022 	 * (subject to any timeout) if:
1023 	 *   1. the current count is less than the low water mark, or
1024 	 *   2. MSG_WAITALL is set, and it is possible to do the entire
1025 	 *	receive operation at once if we block (resid <= hiwat).
1026 	 *   3. MSG_DONTWAIT is not set
1027 	 * If MSG_WAITALL is set but resid is larger than the receive buffer,
1028 	 * we have to do the receive in sections, and thus risk returning
1029 	 * a short count if a timeout or signal occurs after we start.
1030 	 */
1031 	if (m == NULL || (((flags & MSG_DONTWAIT) == 0 &&
1032 	    so->so_rcv.sb_cc < uio->uio_resid) &&
1033 	    (so->so_rcv.sb_cc < so->so_rcv.sb_lowat ||
1034 	    ((flags & MSG_WAITALL) && uio->uio_resid <= so->so_rcv.sb_hiwat)) &&
1035 	    m->m_nextpkt == NULL && (pr->pr_flags & PR_ATOMIC) == 0)) {
1036 		KASSERT(m != NULL || !so->so_rcv.sb_cc,
1037 		    ("receive: m == %p so->so_rcv.sb_cc == %u",
1038 		    m, so->so_rcv.sb_cc));
1039 		if (so->so_error) {
1040 			if (m != NULL)
1041 				goto dontblock;
1042 			error = so->so_error;
1043 			if ((flags & MSG_PEEK) == 0)
1044 				so->so_error = 0;
1045 			goto release;
1046 		}
1047 		SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1048 		if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
1049 			if (m)
1050 				goto dontblock;
1051 			else
1052 				goto release;
1053 		}
1054 		for (; m != NULL; m = m->m_next)
1055 			if (m->m_type == MT_OOBDATA  || (m->m_flags & M_EOR)) {
1056 				m = so->so_rcv.sb_mb;
1057 				goto dontblock;
1058 			}
1059 		if ((so->so_state & (SS_ISCONNECTED|SS_ISCONNECTING)) == 0 &&
1060 		    (so->so_proto->pr_flags & PR_CONNREQUIRED)) {
1061 			error = ENOTCONN;
1062 			goto release;
1063 		}
1064 		if (uio->uio_resid == 0)
1065 			goto release;
1066 		if ((so->so_state & SS_NBIO) ||
1067 		    (flags & (MSG_DONTWAIT|MSG_NBIO))) {
1068 			error = EWOULDBLOCK;
1069 			goto release;
1070 		}
1071 		SBLASTRECORDCHK(&so->so_rcv);
1072 		SBLASTMBUFCHK(&so->so_rcv);
1073 		sbunlock(&so->so_rcv);
1074 		error = sbwait(&so->so_rcv);
1075 		if (error)
1076 			goto out;
1077 		goto restart;
1078 	}
1079 dontblock:
1080 	/*
1081 	 * From this point onward, we maintain 'nextrecord' as a cache of the
1082 	 * pointer to the next record in the socket buffer.  We must keep the
1083 	 * various socket buffer pointers and local stack versions of the
1084 	 * pointers in sync, pushing out modifications before dropping the
1085 	 * socket buffer mutex, and re-reading them when picking it up.
1086 	 *
1087 	 * Otherwise, we will race with the network stack appending new data
1088 	 * or records onto the socket buffer by using inconsistent/stale
1089 	 * versions of the field, possibly resulting in socket buffer
1090 	 * corruption.
1091 	 *
1092 	 * By holding the high-level sblock(), we prevent simultaneous
1093 	 * readers from pulling off the front of the socket buffer.
1094 	 */
1095 	SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1096 	if (uio->uio_td)
1097 		uio->uio_td->td_proc->p_stats->p_ru.ru_msgrcv++;
1098 	KASSERT(m == so->so_rcv.sb_mb, ("soreceive: m != so->so_rcv.sb_mb"));
1099 	SBLASTRECORDCHK(&so->so_rcv);
1100 	SBLASTMBUFCHK(&so->so_rcv);
1101 	nextrecord = m->m_nextpkt;
1102 	if (pr->pr_flags & PR_ADDR) {
1103 		KASSERT(m->m_type == MT_SONAME,
1104 		    ("m->m_type == %d", m->m_type));
1105 		orig_resid = 0;
1106 		if (psa != NULL)
1107 			*psa = sodupsockaddr(mtod(m, struct sockaddr *),
1108 			    M_NOWAIT);
1109 		if (flags & MSG_PEEK) {
1110 			m = m->m_next;
1111 		} else {
1112 			sbfree(&so->so_rcv, m);
1113 			so->so_rcv.sb_mb = m_free(m);
1114 			m = so->so_rcv.sb_mb;
1115 			sockbuf_pushsync(&so->so_rcv, nextrecord);
1116 		}
1117 	}
1118 
1119 	/*
1120 	 * Process one or more MT_CONTROL mbufs present before any data mbufs
1121 	 * in the first mbuf chain on the socket buffer.  If MSG_PEEK, we
1122 	 * just copy the data; if !MSG_PEEK, we call into the protocol to
1123 	 * perform externalization (or freeing if controlp == NULL).
1124 	 */
1125 	if (m != NULL && m->m_type == MT_CONTROL) {
1126 		struct mbuf *cm = NULL, *cmn;
1127 		struct mbuf **cme = &cm;
1128 
1129 		do {
1130 			if (flags & MSG_PEEK) {
1131 				if (controlp != NULL) {
1132 					*controlp = m_copy(m, 0, m->m_len);
1133 					controlp = &(*controlp)->m_next;
1134 				}
1135 				m = m->m_next;
1136 			} else {
1137 				sbfree(&so->so_rcv, m);
1138 				so->so_rcv.sb_mb = m->m_next;
1139 				m->m_next = NULL;
1140 				*cme = m;
1141 				cme = &(*cme)->m_next;
1142 				m = so->so_rcv.sb_mb;
1143 			}
1144 		} while (m != NULL && m->m_type == MT_CONTROL);
1145 		if ((flags & MSG_PEEK) == 0)
1146 			sockbuf_pushsync(&so->so_rcv, nextrecord);
1147 		while (cm != NULL) {
1148 			cmn = cm->m_next;
1149 			cm->m_next = NULL;
1150 			if (pr->pr_domain->dom_externalize != NULL) {
1151 				SOCKBUF_UNLOCK(&so->so_rcv);
1152 				error = (*pr->pr_domain->dom_externalize)
1153 				    (cm, controlp);
1154 				SOCKBUF_LOCK(&so->so_rcv);
1155 			} else if (controlp != NULL)
1156 				*controlp = cm;
1157 			else
1158 				m_freem(cm);
1159 			if (controlp != NULL) {
1160 				orig_resid = 0;
1161 				while (*controlp != NULL)
1162 					controlp = &(*controlp)->m_next;
1163 			}
1164 			cm = cmn;
1165 		}
1166 		nextrecord = so->so_rcv.sb_mb->m_nextpkt;
1167 		orig_resid = 0;
1168 	}
1169 	if (m != NULL) {
1170 		if ((flags & MSG_PEEK) == 0) {
1171 			KASSERT(m->m_nextpkt == nextrecord,
1172 			    ("soreceive: post-control, nextrecord !sync"));
1173 			if (nextrecord == NULL) {
1174 				KASSERT(so->so_rcv.sb_mb == m,
1175 				    ("soreceive: post-control, sb_mb!=m"));
1176 				KASSERT(so->so_rcv.sb_lastrecord == m,
1177 				    ("soreceive: post-control, lastrecord!=m"));
1178 			}
1179 		}
1180 		type = m->m_type;
1181 		if (type == MT_OOBDATA)
1182 			flags |= MSG_OOB;
1183 	} else {
1184 		if ((flags & MSG_PEEK) == 0) {
1185 			KASSERT(so->so_rcv.sb_mb == nextrecord,
1186 			    ("soreceive: sb_mb != nextrecord"));
1187 			if (so->so_rcv.sb_mb == NULL) {
1188 				KASSERT(so->so_rcv.sb_lastrecord == NULL,
1189 				    ("soreceive: sb_lastercord != NULL"));
1190 			}
1191 		}
1192 	}
1193 	SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1194 	SBLASTRECORDCHK(&so->so_rcv);
1195 	SBLASTMBUFCHK(&so->so_rcv);
1196 
1197 	/*
1198 	 * Now continue to read any data mbufs off of the head of the socket
1199 	 * buffer until the read request is satisfied.  Note that 'type' is
1200 	 * used to store the type of any mbuf reads that have happened so far
1201 	 * such that soreceive() can stop reading if the type changes, which
1202 	 * causes soreceive() to return only one of regular data and inline
1203 	 * out-of-band data in a single socket receive operation.
1204 	 */
1205 	moff = 0;
1206 	offset = 0;
1207 	while (m != NULL && uio->uio_resid > 0 && error == 0) {
1208 		/*
1209 		 * If the type of mbuf has changed since the last mbuf
1210 		 * examined ('type'), end the receive operation.
1211 	 	 */
1212 		SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1213 		if (m->m_type == MT_OOBDATA) {
1214 			if (type != MT_OOBDATA)
1215 				break;
1216 		} else if (type == MT_OOBDATA)
1217 			break;
1218 		else
1219 		    KASSERT(m->m_type == MT_DATA || m->m_type == MT_HEADER,
1220 			("m->m_type == %d", m->m_type));
1221 		so->so_rcv.sb_state &= ~SBS_RCVATMARK;
1222 		len = uio->uio_resid;
1223 		if (so->so_oobmark && len > so->so_oobmark - offset)
1224 			len = so->so_oobmark - offset;
1225 		if (len > m->m_len - moff)
1226 			len = m->m_len - moff;
1227 		/*
1228 		 * If mp is set, just pass back the mbufs.
1229 		 * Otherwise copy them out via the uio, then free.
1230 		 * Sockbuf must be consistent here (points to current mbuf,
1231 		 * it points to next record) when we drop priority;
1232 		 * we must note any additions to the sockbuf when we
1233 		 * block interrupts again.
1234 		 */
1235 		if (mp == NULL) {
1236 			SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1237 			SBLASTRECORDCHK(&so->so_rcv);
1238 			SBLASTMBUFCHK(&so->so_rcv);
1239 			SOCKBUF_UNLOCK(&so->so_rcv);
1240 #ifdef ZERO_COPY_SOCKETS
1241 			if (so_zero_copy_receive) {
1242 				int disposable;
1243 
1244 				if ((m->m_flags & M_EXT)
1245 				 && (m->m_ext.ext_type == EXT_DISPOSABLE))
1246 					disposable = 1;
1247 				else
1248 					disposable = 0;
1249 
1250 				error = uiomoveco(mtod(m, char *) + moff,
1251 						  (int)len, uio,
1252 						  disposable);
1253 			} else
1254 #endif /* ZERO_COPY_SOCKETS */
1255 			error = uiomove(mtod(m, char *) + moff, (int)len, uio);
1256 			SOCKBUF_LOCK(&so->so_rcv);
1257 			if (error)
1258 				goto release;
1259 		} else
1260 			uio->uio_resid -= len;
1261 		SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1262 		if (len == m->m_len - moff) {
1263 			if (m->m_flags & M_EOR)
1264 				flags |= MSG_EOR;
1265 			if (flags & MSG_PEEK) {
1266 				m = m->m_next;
1267 				moff = 0;
1268 			} else {
1269 				nextrecord = m->m_nextpkt;
1270 				sbfree(&so->so_rcv, m);
1271 				if (mp != NULL) {
1272 					*mp = m;
1273 					mp = &m->m_next;
1274 					so->so_rcv.sb_mb = m = m->m_next;
1275 					*mp = NULL;
1276 				} else {
1277 					so->so_rcv.sb_mb = m_free(m);
1278 					m = so->so_rcv.sb_mb;
1279 				}
1280 				if (m != NULL) {
1281 					m->m_nextpkt = nextrecord;
1282 					if (nextrecord == NULL)
1283 						so->so_rcv.sb_lastrecord = m;
1284 				} else {
1285 					so->so_rcv.sb_mb = nextrecord;
1286 					SB_EMPTY_FIXUP(&so->so_rcv);
1287 				}
1288 				SBLASTRECORDCHK(&so->so_rcv);
1289 				SBLASTMBUFCHK(&so->so_rcv);
1290 			}
1291 		} else {
1292 			if (flags & MSG_PEEK)
1293 				moff += len;
1294 			else {
1295 				if (mp != NULL) {
1296 					int copy_flag;
1297 
1298 					if (flags & MSG_DONTWAIT)
1299 						copy_flag = M_DONTWAIT;
1300 					else
1301 						copy_flag = M_TRYWAIT;
1302 					if (copy_flag == M_TRYWAIT)
1303 						SOCKBUF_UNLOCK(&so->so_rcv);
1304 					*mp = m_copym(m, 0, len, copy_flag);
1305 					if (copy_flag == M_TRYWAIT)
1306 						SOCKBUF_LOCK(&so->so_rcv);
1307  					if (*mp == NULL) {
1308  						/*
1309  						 * m_copym() couldn't allocate an mbuf.
1310 						 * Adjust uio_resid back (it was adjusted
1311 						 * down by len bytes, which we didn't end
1312 						 * up "copying" over).
1313  						 */
1314  						uio->uio_resid += len;
1315  						break;
1316  					}
1317 				}
1318 				m->m_data += len;
1319 				m->m_len -= len;
1320 				so->so_rcv.sb_cc -= len;
1321 			}
1322 		}
1323 		SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1324 		if (so->so_oobmark) {
1325 			if ((flags & MSG_PEEK) == 0) {
1326 				so->so_oobmark -= len;
1327 				if (so->so_oobmark == 0) {
1328 					so->so_rcv.sb_state |= SBS_RCVATMARK;
1329 					break;
1330 				}
1331 			} else {
1332 				offset += len;
1333 				if (offset == so->so_oobmark)
1334 					break;
1335 			}
1336 		}
1337 		if (flags & MSG_EOR)
1338 			break;
1339 		/*
1340 		 * If the MSG_WAITALL flag is set (for non-atomic socket),
1341 		 * we must not quit until "uio->uio_resid == 0" or an error
1342 		 * termination.  If a signal/timeout occurs, return
1343 		 * with a short count but without error.
1344 		 * Keep sockbuf locked against other readers.
1345 		 */
1346 		while (flags & MSG_WAITALL && m == NULL && uio->uio_resid > 0 &&
1347 		    !sosendallatonce(so) && nextrecord == NULL) {
1348 			SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1349 			if (so->so_error || so->so_rcv.sb_state & SBS_CANTRCVMORE)
1350 				break;
1351 			/*
1352 			 * Notify the protocol that some data has been
1353 			 * drained before blocking.
1354 			 */
1355 			if (pr->pr_flags & PR_WANTRCVD && so->so_pcb != NULL) {
1356 				SOCKBUF_UNLOCK(&so->so_rcv);
1357 				(*pr->pr_usrreqs->pru_rcvd)(so, flags);
1358 				SOCKBUF_LOCK(&so->so_rcv);
1359 			}
1360 			SBLASTRECORDCHK(&so->so_rcv);
1361 			SBLASTMBUFCHK(&so->so_rcv);
1362 			error = sbwait(&so->so_rcv);
1363 			if (error)
1364 				goto release;
1365 			m = so->so_rcv.sb_mb;
1366 			if (m != NULL)
1367 				nextrecord = m->m_nextpkt;
1368 		}
1369 	}
1370 
1371 	SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1372 	if (m != NULL && pr->pr_flags & PR_ATOMIC) {
1373 		flags |= MSG_TRUNC;
1374 		if ((flags & MSG_PEEK) == 0)
1375 			(void) sbdroprecord_locked(&so->so_rcv);
1376 	}
1377 	if ((flags & MSG_PEEK) == 0) {
1378 		if (m == NULL) {
1379 			/*
1380 			 * First part is an inline SB_EMPTY_FIXUP().  Second
1381 			 * part makes sure sb_lastrecord is up-to-date if
1382 			 * there is still data in the socket buffer.
1383 			 */
1384 			so->so_rcv.sb_mb = nextrecord;
1385 			if (so->so_rcv.sb_mb == NULL) {
1386 				so->so_rcv.sb_mbtail = NULL;
1387 				so->so_rcv.sb_lastrecord = NULL;
1388 			} else if (nextrecord->m_nextpkt == NULL)
1389 				so->so_rcv.sb_lastrecord = nextrecord;
1390 		}
1391 		SBLASTRECORDCHK(&so->so_rcv);
1392 		SBLASTMBUFCHK(&so->so_rcv);
1393 		/*
1394 		 * If soreceive() is being done from the socket callback, then
1395 		 * don't need to generate ACK to peer to update window, since
1396 		 * ACK will be generated on return to TCP.
1397 		 */
1398 		if (!(flags & MSG_SOCALLBCK) &&
1399 		    (pr->pr_flags & PR_WANTRCVD) && so->so_pcb) {
1400 			SOCKBUF_UNLOCK(&so->so_rcv);
1401 			(*pr->pr_usrreqs->pru_rcvd)(so, flags);
1402 			SOCKBUF_LOCK(&so->so_rcv);
1403 		}
1404 	}
1405 	SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1406 	if (orig_resid == uio->uio_resid && orig_resid &&
1407 	    (flags & MSG_EOR) == 0 && (so->so_rcv.sb_state & SBS_CANTRCVMORE) == 0) {
1408 		sbunlock(&so->so_rcv);
1409 		goto restart;
1410 	}
1411 
1412 	if (flagsp != NULL)
1413 		*flagsp |= flags;
1414 release:
1415 	SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1416 	sbunlock(&so->so_rcv);
1417 out:
1418 	SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1419 	SOCKBUF_UNLOCK(&so->so_rcv);
1420 	return (error);
1421 }
1422 
1423 int
1424 soshutdown(so, how)
1425 	struct socket *so;
1426 	int how;
1427 {
1428 	struct protosw *pr = so->so_proto;
1429 
1430 	if (!(how == SHUT_RD || how == SHUT_WR || how == SHUT_RDWR))
1431 		return (EINVAL);
1432 
1433 	if (how != SHUT_WR)
1434 		sorflush(so);
1435 	if (how != SHUT_RD)
1436 		return ((*pr->pr_usrreqs->pru_shutdown)(so));
1437 	return (0);
1438 }
1439 
1440 void
1441 sorflush(so)
1442 	struct socket *so;
1443 {
1444 	struct sockbuf *sb = &so->so_rcv;
1445 	struct protosw *pr = so->so_proto;
1446 	struct sockbuf asb;
1447 
1448 	/*
1449 	 * XXXRW: This is quite ugly.  Previously, this code made a copy of
1450 	 * the socket buffer, then zero'd the original to clear the buffer
1451 	 * fields.  However, with mutexes in the socket buffer, this causes
1452 	 * problems.  We only clear the zeroable bits of the original;
1453 	 * however, we have to initialize and destroy the mutex in the copy
1454 	 * so that dom_dispose() and sbrelease() can lock t as needed.
1455 	 */
1456 	SOCKBUF_LOCK(sb);
1457 	sb->sb_flags |= SB_NOINTR;
1458 	(void) sblock(sb, M_WAITOK);
1459 	/*
1460 	 * socantrcvmore_locked() drops the socket buffer mutex so that it
1461 	 * can safely perform wakeups.  Re-acquire the mutex before
1462 	 * continuing.
1463 	 */
1464 	socantrcvmore_locked(so);
1465 	SOCKBUF_LOCK(sb);
1466 	sbunlock(sb);
1467 	/*
1468 	 * Invalidate/clear most of the sockbuf structure, but leave
1469 	 * selinfo and mutex data unchanged.
1470 	 */
1471 	bzero(&asb, offsetof(struct sockbuf, sb_startzero));
1472 	bcopy(&sb->sb_startzero, &asb.sb_startzero,
1473 	    sizeof(*sb) - offsetof(struct sockbuf, sb_startzero));
1474 	bzero(&sb->sb_startzero,
1475 	    sizeof(*sb) - offsetof(struct sockbuf, sb_startzero));
1476 	SOCKBUF_UNLOCK(sb);
1477 
1478 	SOCKBUF_LOCK_INIT(&asb, "so_rcv");
1479 	if (pr->pr_flags & PR_RIGHTS && pr->pr_domain->dom_dispose != NULL)
1480 		(*pr->pr_domain->dom_dispose)(asb.sb_mb);
1481 	sbrelease(&asb, so);
1482 	SOCKBUF_LOCK_DESTROY(&asb);
1483 }
1484 
1485 /*
1486  * Perhaps this routine, and sooptcopyout(), below, ought to come in
1487  * an additional variant to handle the case where the option value needs
1488  * to be some kind of integer, but not a specific size.
1489  * In addition to their use here, these functions are also called by the
1490  * protocol-level pr_ctloutput() routines.
1491  */
1492 int
1493 sooptcopyin(sopt, buf, len, minlen)
1494 	struct	sockopt *sopt;
1495 	void	*buf;
1496 	size_t	len;
1497 	size_t	minlen;
1498 {
1499 	size_t	valsize;
1500 
1501 	/*
1502 	 * If the user gives us more than we wanted, we ignore it,
1503 	 * but if we don't get the minimum length the caller
1504 	 * wants, we return EINVAL.  On success, sopt->sopt_valsize
1505 	 * is set to however much we actually retrieved.
1506 	 */
1507 	if ((valsize = sopt->sopt_valsize) < minlen)
1508 		return EINVAL;
1509 	if (valsize > len)
1510 		sopt->sopt_valsize = valsize = len;
1511 
1512 	if (sopt->sopt_td != NULL)
1513 		return (copyin(sopt->sopt_val, buf, valsize));
1514 
1515 	bcopy(sopt->sopt_val, buf, valsize);
1516 	return 0;
1517 }
1518 
1519 /*
1520  * Kernel version of setsockopt(2)/
1521  * XXX: optlen is size_t, not socklen_t
1522  */
1523 int
1524 so_setsockopt(struct socket *so, int level, int optname, void *optval,
1525     size_t optlen)
1526 {
1527 	struct sockopt sopt;
1528 
1529 	sopt.sopt_level = level;
1530 	sopt.sopt_name = optname;
1531 	sopt.sopt_dir = SOPT_SET;
1532 	sopt.sopt_val = optval;
1533 	sopt.sopt_valsize = optlen;
1534 	sopt.sopt_td = NULL;
1535 	return (sosetopt(so, &sopt));
1536 }
1537 
1538 int
1539 sosetopt(so, sopt)
1540 	struct socket *so;
1541 	struct sockopt *sopt;
1542 {
1543 	int	error, optval;
1544 	struct	linger l;
1545 	struct	timeval tv;
1546 	u_long  val;
1547 #ifdef MAC
1548 	struct mac extmac;
1549 #endif
1550 
1551 	error = 0;
1552 	if (sopt->sopt_level != SOL_SOCKET) {
1553 		if (so->so_proto && so->so_proto->pr_ctloutput)
1554 			return ((*so->so_proto->pr_ctloutput)
1555 				  (so, sopt));
1556 		error = ENOPROTOOPT;
1557 	} else {
1558 		switch (sopt->sopt_name) {
1559 #ifdef INET
1560 		case SO_ACCEPTFILTER:
1561 			error = do_setopt_accept_filter(so, sopt);
1562 			if (error)
1563 				goto bad;
1564 			break;
1565 #endif
1566 		case SO_LINGER:
1567 			error = sooptcopyin(sopt, &l, sizeof l, sizeof l);
1568 			if (error)
1569 				goto bad;
1570 
1571 			SOCK_LOCK(so);
1572 			so->so_linger = l.l_linger;
1573 			if (l.l_onoff)
1574 				so->so_options |= SO_LINGER;
1575 			else
1576 				so->so_options &= ~SO_LINGER;
1577 			SOCK_UNLOCK(so);
1578 			break;
1579 
1580 		case SO_DEBUG:
1581 		case SO_KEEPALIVE:
1582 		case SO_DONTROUTE:
1583 		case SO_USELOOPBACK:
1584 		case SO_BROADCAST:
1585 		case SO_REUSEADDR:
1586 		case SO_REUSEPORT:
1587 		case SO_OOBINLINE:
1588 		case SO_TIMESTAMP:
1589 		case SO_BINTIME:
1590 		case SO_NOSIGPIPE:
1591 			error = sooptcopyin(sopt, &optval, sizeof optval,
1592 					    sizeof optval);
1593 			if (error)
1594 				goto bad;
1595 			SOCK_LOCK(so);
1596 			if (optval)
1597 				so->so_options |= sopt->sopt_name;
1598 			else
1599 				so->so_options &= ~sopt->sopt_name;
1600 			SOCK_UNLOCK(so);
1601 			break;
1602 
1603 		case SO_SNDBUF:
1604 		case SO_RCVBUF:
1605 		case SO_SNDLOWAT:
1606 		case SO_RCVLOWAT:
1607 			error = sooptcopyin(sopt, &optval, sizeof optval,
1608 					    sizeof optval);
1609 			if (error)
1610 				goto bad;
1611 
1612 			/*
1613 			 * Values < 1 make no sense for any of these
1614 			 * options, so disallow them.
1615 			 */
1616 			if (optval < 1) {
1617 				error = EINVAL;
1618 				goto bad;
1619 			}
1620 
1621 			switch (sopt->sopt_name) {
1622 			case SO_SNDBUF:
1623 			case SO_RCVBUF:
1624 				if (sbreserve(sopt->sopt_name == SO_SNDBUF ?
1625 				    &so->so_snd : &so->so_rcv, (u_long)optval,
1626 				    so, curthread) == 0) {
1627 					error = ENOBUFS;
1628 					goto bad;
1629 				}
1630 				break;
1631 
1632 			/*
1633 			 * Make sure the low-water is never greater than
1634 			 * the high-water.
1635 			 */
1636 			case SO_SNDLOWAT:
1637 				SOCKBUF_LOCK(&so->so_snd);
1638 				so->so_snd.sb_lowat =
1639 				    (optval > so->so_snd.sb_hiwat) ?
1640 				    so->so_snd.sb_hiwat : optval;
1641 				SOCKBUF_UNLOCK(&so->so_snd);
1642 				break;
1643 			case SO_RCVLOWAT:
1644 				SOCKBUF_LOCK(&so->so_rcv);
1645 				so->so_rcv.sb_lowat =
1646 				    (optval > so->so_rcv.sb_hiwat) ?
1647 				    so->so_rcv.sb_hiwat : optval;
1648 				SOCKBUF_UNLOCK(&so->so_rcv);
1649 				break;
1650 			}
1651 			break;
1652 
1653 		case SO_SNDTIMEO:
1654 		case SO_RCVTIMEO:
1655 			error = sooptcopyin(sopt, &tv, sizeof tv,
1656 					    sizeof tv);
1657 			if (error)
1658 				goto bad;
1659 
1660 			/* assert(hz > 0); */
1661 			if (tv.tv_sec < 0 || tv.tv_sec > INT_MAX / hz ||
1662 			    tv.tv_usec < 0 || tv.tv_usec >= 1000000) {
1663 				error = EDOM;
1664 				goto bad;
1665 			}
1666 			/* assert(tick > 0); */
1667 			/* assert(ULONG_MAX - INT_MAX >= 1000000); */
1668 			val = (u_long)(tv.tv_sec * hz) + tv.tv_usec / tick;
1669 			if (val > INT_MAX) {
1670 				error = EDOM;
1671 				goto bad;
1672 			}
1673 			if (val == 0 && tv.tv_usec != 0)
1674 				val = 1;
1675 
1676 			switch (sopt->sopt_name) {
1677 			case SO_SNDTIMEO:
1678 				so->so_snd.sb_timeo = val;
1679 				break;
1680 			case SO_RCVTIMEO:
1681 				so->so_rcv.sb_timeo = val;
1682 				break;
1683 			}
1684 			break;
1685 		case SO_LABEL:
1686 #ifdef MAC
1687 			error = sooptcopyin(sopt, &extmac, sizeof extmac,
1688 			    sizeof extmac);
1689 			if (error)
1690 				goto bad;
1691 			error = mac_setsockopt_label(sopt->sopt_td->td_ucred,
1692 			    so, &extmac);
1693 #else
1694 			error = EOPNOTSUPP;
1695 #endif
1696 			break;
1697 		default:
1698 			error = ENOPROTOOPT;
1699 			break;
1700 		}
1701 		if (error == 0 && so->so_proto != NULL &&
1702 		    so->so_proto->pr_ctloutput != NULL) {
1703 			(void) ((*so->so_proto->pr_ctloutput)
1704 				  (so, sopt));
1705 		}
1706 	}
1707 bad:
1708 	return (error);
1709 }
1710 
1711 /* Helper routine for getsockopt */
1712 int
1713 sooptcopyout(struct sockopt *sopt, const void *buf, size_t len)
1714 {
1715 	int	error;
1716 	size_t	valsize;
1717 
1718 	error = 0;
1719 
1720 	/*
1721 	 * Documented get behavior is that we always return a value,
1722 	 * possibly truncated to fit in the user's buffer.
1723 	 * Traditional behavior is that we always tell the user
1724 	 * precisely how much we copied, rather than something useful
1725 	 * like the total amount we had available for her.
1726 	 * Note that this interface is not idempotent; the entire answer must
1727 	 * generated ahead of time.
1728 	 */
1729 	valsize = min(len, sopt->sopt_valsize);
1730 	sopt->sopt_valsize = valsize;
1731 	if (sopt->sopt_val != NULL) {
1732 		if (sopt->sopt_td != NULL)
1733 			error = copyout(buf, sopt->sopt_val, valsize);
1734 		else
1735 			bcopy(buf, sopt->sopt_val, valsize);
1736 	}
1737 	return error;
1738 }
1739 
1740 int
1741 sogetopt(so, sopt)
1742 	struct socket *so;
1743 	struct sockopt *sopt;
1744 {
1745 	int	error, optval;
1746 	struct	linger l;
1747 	struct	timeval tv;
1748 #ifdef MAC
1749 	struct mac extmac;
1750 #endif
1751 
1752 	error = 0;
1753 	if (sopt->sopt_level != SOL_SOCKET) {
1754 		if (so->so_proto && so->so_proto->pr_ctloutput) {
1755 			return ((*so->so_proto->pr_ctloutput)
1756 				  (so, sopt));
1757 		} else
1758 			return (ENOPROTOOPT);
1759 	} else {
1760 		switch (sopt->sopt_name) {
1761 #ifdef INET
1762 		case SO_ACCEPTFILTER:
1763 			error = do_getopt_accept_filter(so, sopt);
1764 			break;
1765 #endif
1766 		case SO_LINGER:
1767 			SOCK_LOCK(so);
1768 			l.l_onoff = so->so_options & SO_LINGER;
1769 			l.l_linger = so->so_linger;
1770 			SOCK_UNLOCK(so);
1771 			error = sooptcopyout(sopt, &l, sizeof l);
1772 			break;
1773 
1774 		case SO_USELOOPBACK:
1775 		case SO_DONTROUTE:
1776 		case SO_DEBUG:
1777 		case SO_KEEPALIVE:
1778 		case SO_REUSEADDR:
1779 		case SO_REUSEPORT:
1780 		case SO_BROADCAST:
1781 		case SO_OOBINLINE:
1782 		case SO_TIMESTAMP:
1783 		case SO_BINTIME:
1784 		case SO_NOSIGPIPE:
1785 			optval = so->so_options & sopt->sopt_name;
1786 integer:
1787 			error = sooptcopyout(sopt, &optval, sizeof optval);
1788 			break;
1789 
1790 		case SO_TYPE:
1791 			optval = so->so_type;
1792 			goto integer;
1793 
1794 		case SO_ERROR:
1795 			optval = so->so_error;
1796 			so->so_error = 0;
1797 			goto integer;
1798 
1799 		case SO_SNDBUF:
1800 			optval = so->so_snd.sb_hiwat;
1801 			goto integer;
1802 
1803 		case SO_RCVBUF:
1804 			optval = so->so_rcv.sb_hiwat;
1805 			goto integer;
1806 
1807 		case SO_SNDLOWAT:
1808 			optval = so->so_snd.sb_lowat;
1809 			goto integer;
1810 
1811 		case SO_RCVLOWAT:
1812 			optval = so->so_rcv.sb_lowat;
1813 			goto integer;
1814 
1815 		case SO_SNDTIMEO:
1816 		case SO_RCVTIMEO:
1817 			optval = (sopt->sopt_name == SO_SNDTIMEO ?
1818 				  so->so_snd.sb_timeo : so->so_rcv.sb_timeo);
1819 
1820 			tv.tv_sec = optval / hz;
1821 			tv.tv_usec = (optval % hz) * tick;
1822 			error = sooptcopyout(sopt, &tv, sizeof tv);
1823 			break;
1824 		case SO_LABEL:
1825 #ifdef MAC
1826 			error = sooptcopyin(sopt, &extmac, sizeof(extmac),
1827 			    sizeof(extmac));
1828 			if (error)
1829 				return (error);
1830 			error = mac_getsockopt_label(sopt->sopt_td->td_ucred,
1831 			    so, &extmac);
1832 			if (error)
1833 				return (error);
1834 			error = sooptcopyout(sopt, &extmac, sizeof extmac);
1835 #else
1836 			error = EOPNOTSUPP;
1837 #endif
1838 			break;
1839 		case SO_PEERLABEL:
1840 #ifdef MAC
1841 			error = sooptcopyin(sopt, &extmac, sizeof(extmac),
1842 			    sizeof(extmac));
1843 			if (error)
1844 				return (error);
1845 			error = mac_getsockopt_peerlabel(
1846 			    sopt->sopt_td->td_ucred, so, &extmac);
1847 			if (error)
1848 				return (error);
1849 			error = sooptcopyout(sopt, &extmac, sizeof extmac);
1850 #else
1851 			error = EOPNOTSUPP;
1852 #endif
1853 			break;
1854 		default:
1855 			error = ENOPROTOOPT;
1856 			break;
1857 		}
1858 		return (error);
1859 	}
1860 }
1861 
1862 /* XXX; prepare mbuf for (__FreeBSD__ < 3) routines. */
1863 int
1864 soopt_getm(struct sockopt *sopt, struct mbuf **mp)
1865 {
1866 	struct mbuf *m, *m_prev;
1867 	int sopt_size = sopt->sopt_valsize;
1868 
1869 	MGET(m, sopt->sopt_td ? M_TRYWAIT : M_DONTWAIT, MT_DATA);
1870 	if (m == NULL)
1871 		return ENOBUFS;
1872 	if (sopt_size > MLEN) {
1873 		MCLGET(m, sopt->sopt_td ? M_TRYWAIT : M_DONTWAIT);
1874 		if ((m->m_flags & M_EXT) == 0) {
1875 			m_free(m);
1876 			return ENOBUFS;
1877 		}
1878 		m->m_len = min(MCLBYTES, sopt_size);
1879 	} else {
1880 		m->m_len = min(MLEN, sopt_size);
1881 	}
1882 	sopt_size -= m->m_len;
1883 	*mp = m;
1884 	m_prev = m;
1885 
1886 	while (sopt_size) {
1887 		MGET(m, sopt->sopt_td ? M_TRYWAIT : M_DONTWAIT, MT_DATA);
1888 		if (m == NULL) {
1889 			m_freem(*mp);
1890 			return ENOBUFS;
1891 		}
1892 		if (sopt_size > MLEN) {
1893 			MCLGET(m, sopt->sopt_td != NULL ? M_TRYWAIT :
1894 			    M_DONTWAIT);
1895 			if ((m->m_flags & M_EXT) == 0) {
1896 				m_freem(m);
1897 				m_freem(*mp);
1898 				return ENOBUFS;
1899 			}
1900 			m->m_len = min(MCLBYTES, sopt_size);
1901 		} else {
1902 			m->m_len = min(MLEN, sopt_size);
1903 		}
1904 		sopt_size -= m->m_len;
1905 		m_prev->m_next = m;
1906 		m_prev = m;
1907 	}
1908 	return 0;
1909 }
1910 
1911 /* XXX; copyin sopt data into mbuf chain for (__FreeBSD__ < 3) routines. */
1912 int
1913 soopt_mcopyin(struct sockopt *sopt, struct mbuf *m)
1914 {
1915 	struct mbuf *m0 = m;
1916 
1917 	if (sopt->sopt_val == NULL)
1918 		return 0;
1919 	while (m != NULL && sopt->sopt_valsize >= m->m_len) {
1920 		if (sopt->sopt_td != NULL) {
1921 			int error;
1922 
1923 			error = copyin(sopt->sopt_val, mtod(m, char *),
1924 				       m->m_len);
1925 			if (error != 0) {
1926 				m_freem(m0);
1927 				return(error);
1928 			}
1929 		} else
1930 			bcopy(sopt->sopt_val, mtod(m, char *), m->m_len);
1931 		sopt->sopt_valsize -= m->m_len;
1932 		sopt->sopt_val = (char *)sopt->sopt_val + m->m_len;
1933 		m = m->m_next;
1934 	}
1935 	if (m != NULL) /* should be allocated enoughly at ip6_sooptmcopyin() */
1936 		panic("ip6_sooptmcopyin");
1937 	return 0;
1938 }
1939 
1940 /* XXX; copyout mbuf chain data into soopt for (__FreeBSD__ < 3) routines. */
1941 int
1942 soopt_mcopyout(struct sockopt *sopt, struct mbuf *m)
1943 {
1944 	struct mbuf *m0 = m;
1945 	size_t valsize = 0;
1946 
1947 	if (sopt->sopt_val == NULL)
1948 		return 0;
1949 	while (m != NULL && sopt->sopt_valsize >= m->m_len) {
1950 		if (sopt->sopt_td != NULL) {
1951 			int error;
1952 
1953 			error = copyout(mtod(m, char *), sopt->sopt_val,
1954 				       m->m_len);
1955 			if (error != 0) {
1956 				m_freem(m0);
1957 				return(error);
1958 			}
1959 		} else
1960 			bcopy(mtod(m, char *), sopt->sopt_val, m->m_len);
1961 	       sopt->sopt_valsize -= m->m_len;
1962 	       sopt->sopt_val = (char *)sopt->sopt_val + m->m_len;
1963 	       valsize += m->m_len;
1964 	       m = m->m_next;
1965 	}
1966 	if (m != NULL) {
1967 		/* enough soopt buffer should be given from user-land */
1968 		m_freem(m0);
1969 		return(EINVAL);
1970 	}
1971 	sopt->sopt_valsize = valsize;
1972 	return 0;
1973 }
1974 
1975 void
1976 sohasoutofband(so)
1977 	struct socket *so;
1978 {
1979 	if (so->so_sigio != NULL)
1980 		pgsigio(&so->so_sigio, SIGURG, 0);
1981 	selwakeuppri(&so->so_rcv.sb_sel, PSOCK);
1982 }
1983 
1984 int
1985 sopoll(struct socket *so, int events, struct ucred *active_cred,
1986     struct thread *td)
1987 {
1988 	int revents = 0;
1989 
1990 	SOCKBUF_LOCK(&so->so_snd);
1991 	SOCKBUF_LOCK(&so->so_rcv);
1992 	if (events & (POLLIN | POLLRDNORM))
1993 		if (soreadable(so))
1994 			revents |= events & (POLLIN | POLLRDNORM);
1995 
1996 	if (events & POLLINIGNEOF)
1997 		if (so->so_rcv.sb_cc >= so->so_rcv.sb_lowat ||
1998 		    !TAILQ_EMPTY(&so->so_comp) || so->so_error)
1999 			revents |= POLLINIGNEOF;
2000 
2001 	if (events & (POLLOUT | POLLWRNORM))
2002 		if (sowriteable(so))
2003 			revents |= events & (POLLOUT | POLLWRNORM);
2004 
2005 	if (events & (POLLPRI | POLLRDBAND))
2006 		if (so->so_oobmark || (so->so_rcv.sb_state & SBS_RCVATMARK))
2007 			revents |= events & (POLLPRI | POLLRDBAND);
2008 
2009 	if (revents == 0) {
2010 		if (events &
2011 		    (POLLIN | POLLINIGNEOF | POLLPRI | POLLRDNORM |
2012 		     POLLRDBAND)) {
2013 			selrecord(td, &so->so_rcv.sb_sel);
2014 			so->so_rcv.sb_flags |= SB_SEL;
2015 		}
2016 
2017 		if (events & (POLLOUT | POLLWRNORM)) {
2018 			selrecord(td, &so->so_snd.sb_sel);
2019 			so->so_snd.sb_flags |= SB_SEL;
2020 		}
2021 	}
2022 
2023 	SOCKBUF_UNLOCK(&so->so_rcv);
2024 	SOCKBUF_UNLOCK(&so->so_snd);
2025 	return (revents);
2026 }
2027 
2028 int
2029 soo_kqfilter(struct file *fp, struct knote *kn)
2030 {
2031 	struct socket *so = kn->kn_fp->f_data;
2032 	struct sockbuf *sb;
2033 
2034 	switch (kn->kn_filter) {
2035 	case EVFILT_READ:
2036 		if (so->so_options & SO_ACCEPTCONN)
2037 			kn->kn_fop = &solisten_filtops;
2038 		else
2039 			kn->kn_fop = &soread_filtops;
2040 		sb = &so->so_rcv;
2041 		break;
2042 	case EVFILT_WRITE:
2043 		kn->kn_fop = &sowrite_filtops;
2044 		sb = &so->so_snd;
2045 		break;
2046 	default:
2047 		return (EINVAL);
2048 	}
2049 
2050 	SOCKBUF_LOCK(sb);
2051 	knlist_add(&sb->sb_sel.si_note, kn, 1);
2052 	sb->sb_flags |= SB_KNOTE;
2053 	SOCKBUF_UNLOCK(sb);
2054 	return (0);
2055 }
2056 
2057 static void
2058 filt_sordetach(struct knote *kn)
2059 {
2060 	struct socket *so = kn->kn_fp->f_data;
2061 
2062 	SOCKBUF_LOCK(&so->so_rcv);
2063 	knlist_remove(&so->so_rcv.sb_sel.si_note, kn, 1);
2064 	if (knlist_empty(&so->so_rcv.sb_sel.si_note))
2065 		so->so_rcv.sb_flags &= ~SB_KNOTE;
2066 	SOCKBUF_UNLOCK(&so->so_rcv);
2067 }
2068 
2069 /*ARGSUSED*/
2070 static int
2071 filt_soread(struct knote *kn, long hint)
2072 {
2073 	struct socket *so;
2074 
2075 	so = kn->kn_fp->f_data;
2076 	SOCKBUF_LOCK_ASSERT(&so->so_rcv);
2077 
2078 	kn->kn_data = so->so_rcv.sb_cc - so->so_rcv.sb_ctl;
2079 	if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
2080 		kn->kn_flags |= EV_EOF;
2081 		kn->kn_fflags = so->so_error;
2082 		return (1);
2083 	} else if (so->so_error)	/* temporary udp error */
2084 		return (1);
2085 	else if (kn->kn_sfflags & NOTE_LOWAT)
2086 		return (kn->kn_data >= kn->kn_sdata);
2087 	else
2088 		return (so->so_rcv.sb_cc >= so->so_rcv.sb_lowat);
2089 }
2090 
2091 static void
2092 filt_sowdetach(struct knote *kn)
2093 {
2094 	struct socket *so = kn->kn_fp->f_data;
2095 
2096 	SOCKBUF_LOCK(&so->so_snd);
2097 	knlist_remove(&so->so_snd.sb_sel.si_note, kn, 1);
2098 	if (knlist_empty(&so->so_snd.sb_sel.si_note))
2099 		so->so_snd.sb_flags &= ~SB_KNOTE;
2100 	SOCKBUF_UNLOCK(&so->so_snd);
2101 }
2102 
2103 /*ARGSUSED*/
2104 static int
2105 filt_sowrite(struct knote *kn, long hint)
2106 {
2107 	struct socket *so;
2108 
2109 	so = kn->kn_fp->f_data;
2110 	SOCKBUF_LOCK_ASSERT(&so->so_snd);
2111 	kn->kn_data = sbspace(&so->so_snd);
2112 	if (so->so_snd.sb_state & SBS_CANTSENDMORE) {
2113 		kn->kn_flags |= EV_EOF;
2114 		kn->kn_fflags = so->so_error;
2115 		return (1);
2116 	} else if (so->so_error)	/* temporary udp error */
2117 		return (1);
2118 	else if (((so->so_state & SS_ISCONNECTED) == 0) &&
2119 	    (so->so_proto->pr_flags & PR_CONNREQUIRED))
2120 		return (0);
2121 	else if (kn->kn_sfflags & NOTE_LOWAT)
2122 		return (kn->kn_data >= kn->kn_sdata);
2123 	else
2124 		return (kn->kn_data >= so->so_snd.sb_lowat);
2125 }
2126 
2127 /*ARGSUSED*/
2128 static int
2129 filt_solisten(struct knote *kn, long hint)
2130 {
2131 	struct socket *so = kn->kn_fp->f_data;
2132 
2133 	kn->kn_data = so->so_qlen;
2134 	return (! TAILQ_EMPTY(&so->so_comp));
2135 }
2136 
2137 int
2138 socheckuid(struct socket *so, uid_t uid)
2139 {
2140 
2141 	if (so == NULL)
2142 		return (EPERM);
2143 	if (so->so_cred->cr_uid != uid)
2144 		return (EPERM);
2145 	return (0);
2146 }
2147 
2148 static int
2149 somaxconn_sysctl(SYSCTL_HANDLER_ARGS)
2150 {
2151 	int error;
2152 	int val;
2153 
2154 	val = somaxconn;
2155 	error = sysctl_handle_int(oidp, &val, sizeof(int), req);
2156 	if (error || !req->newptr )
2157 		return (error);
2158 
2159 	if (val < 1 || val > USHRT_MAX)
2160 		return (EINVAL);
2161 
2162 	somaxconn = val;
2163 	return (0);
2164 }
2165