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